PackageManagerService.java revision 1c133105774835deaa99db78d9668b107246abef
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
46import static android.content.pm.PackageParser.isApkFile;
47import static android.os.Process.PACKAGE_INFO_GID;
48import static android.os.Process.SYSTEM_UID;
49import static android.system.OsConstants.O_CREAT;
50import static android.system.OsConstants.O_RDWR;
51import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
53import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
54import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
55import static com.android.internal.util.ArrayUtils.appendInt;
56import static com.android.internal.util.ArrayUtils.removeInt;
57
58import android.util.ArrayMap;
59
60import com.android.internal.R;
61import com.android.internal.app.IMediaContainerService;
62import com.android.internal.app.ResolverActivity;
63import com.android.internal.content.NativeLibraryHelper;
64import com.android.internal.content.PackageHelper;
65import com.android.internal.os.IParcelFileDescriptorFactory;
66import com.android.internal.util.ArrayUtils;
67import com.android.internal.util.FastPrintWriter;
68import com.android.internal.util.FastXmlSerializer;
69import com.android.internal.util.IndentingPrintWriter;
70import com.android.server.EventLogTags;
71import com.android.server.IntentResolver;
72import com.android.server.LocalServices;
73import com.android.server.ServiceThread;
74import com.android.server.SystemConfig;
75import com.android.server.Watchdog;
76import com.android.server.pm.Settings.DatabaseVersion;
77import com.android.server.storage.DeviceStorageMonitorInternal;
78
79import org.xmlpull.v1.XmlSerializer;
80
81import android.app.ActivityManager;
82import android.app.ActivityManagerNative;
83import android.app.IActivityManager;
84import android.app.admin.IDevicePolicyManager;
85import android.app.backup.IBackupManager;
86import android.content.BroadcastReceiver;
87import android.content.ComponentName;
88import android.content.Context;
89import android.content.IIntentReceiver;
90import android.content.Intent;
91import android.content.IntentFilter;
92import android.content.IntentSender;
93import android.content.IntentSender.SendIntentException;
94import android.content.ServiceConnection;
95import android.content.pm.ActivityInfo;
96import android.content.pm.ApplicationInfo;
97import android.content.pm.FeatureInfo;
98import android.content.pm.IPackageDataObserver;
99import android.content.pm.IPackageDeleteObserver;
100import android.content.pm.IPackageDeleteObserver2;
101import android.content.pm.IPackageInstallObserver2;
102import android.content.pm.IPackageInstaller;
103import android.content.pm.IPackageManager;
104import android.content.pm.IPackageMoveObserver;
105import android.content.pm.IPackageStatsObserver;
106import android.content.pm.InstrumentationInfo;
107import android.content.pm.KeySet;
108import android.content.pm.ManifestDigest;
109import android.content.pm.PackageCleanItem;
110import android.content.pm.PackageInfo;
111import android.content.pm.PackageInfoLite;
112import android.content.pm.PackageInstaller;
113import android.content.pm.PackageManager;
114import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
115import android.content.pm.PackageParser.ActivityIntentInfo;
116import android.content.pm.PackageParser.PackageLite;
117import android.content.pm.PackageParser.PackageParserException;
118import android.content.pm.PackageParser;
119import android.content.pm.PackageStats;
120import android.content.pm.PackageUserState;
121import android.content.pm.ParceledListSlice;
122import android.content.pm.PermissionGroupInfo;
123import android.content.pm.PermissionInfo;
124import android.content.pm.ProviderInfo;
125import android.content.pm.ResolveInfo;
126import android.content.pm.ServiceInfo;
127import android.content.pm.Signature;
128import android.content.pm.UserInfo;
129import android.content.pm.VerificationParams;
130import android.content.pm.VerifierDeviceIdentity;
131import android.content.pm.VerifierInfo;
132import android.content.res.Resources;
133import android.hardware.display.DisplayManager;
134import android.net.Uri;
135import android.os.Binder;
136import android.os.Build;
137import android.os.Bundle;
138import android.os.Environment;
139import android.os.Environment.UserEnvironment;
140import android.os.storage.StorageManager;
141import android.os.Debug;
142import android.os.FileUtils;
143import android.os.Handler;
144import android.os.IBinder;
145import android.os.Looper;
146import android.os.Message;
147import android.os.Parcel;
148import android.os.ParcelFileDescriptor;
149import android.os.Process;
150import android.os.RemoteException;
151import android.os.SELinux;
152import android.os.ServiceManager;
153import android.os.SystemClock;
154import android.os.SystemProperties;
155import android.os.UserHandle;
156import android.os.UserManager;
157import android.security.KeyStore;
158import android.security.SystemKeyStore;
159import android.system.ErrnoException;
160import android.system.Os;
161import android.system.StructStat;
162import android.text.TextUtils;
163import android.util.ArraySet;
164import android.util.AtomicFile;
165import android.util.DisplayMetrics;
166import android.util.EventLog;
167import android.util.ExceptionUtils;
168import android.util.Log;
169import android.util.LogPrinter;
170import android.util.PrintStreamPrinter;
171import android.util.Slog;
172import android.util.SparseArray;
173import android.util.SparseBooleanArray;
174import android.view.Display;
175
176import java.io.BufferedInputStream;
177import java.io.BufferedOutputStream;
178import java.io.BufferedReader;
179import java.io.File;
180import java.io.FileDescriptor;
181import java.io.FileInputStream;
182import java.io.FileNotFoundException;
183import java.io.FileOutputStream;
184import java.io.FileReader;
185import java.io.FilenameFilter;
186import java.io.IOException;
187import java.io.InputStream;
188import java.io.PrintWriter;
189import java.nio.charset.StandardCharsets;
190import java.security.NoSuchAlgorithmException;
191import java.security.PublicKey;
192import java.security.cert.CertificateEncodingException;
193import java.security.cert.CertificateException;
194import java.text.SimpleDateFormat;
195import java.util.ArrayList;
196import java.util.Arrays;
197import java.util.Collection;
198import java.util.Collections;
199import java.util.Comparator;
200import java.util.Date;
201import java.util.HashMap;
202import java.util.HashSet;
203import java.util.Iterator;
204import java.util.List;
205import java.util.Map;
206import java.util.Objects;
207import java.util.Set;
208import java.util.concurrent.atomic.AtomicBoolean;
209import java.util.concurrent.atomic.AtomicLong;
210
211import dalvik.system.DexFile;
212import dalvik.system.StaleDexCacheError;
213import dalvik.system.VMRuntime;
214
215import libcore.io.IoUtils;
216import libcore.util.EmptyArray;
217
218/**
219 * Keep track of all those .apks everywhere.
220 *
221 * This is very central to the platform's security; please run the unit
222 * tests whenever making modifications here:
223 *
224mmm frameworks/base/tests/AndroidTests
225adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
226adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
227 *
228 * {@hide}
229 */
230public class PackageManagerService extends IPackageManager.Stub {
231    static final String TAG = "PackageManager";
232    static final boolean DEBUG_SETTINGS = false;
233    static final boolean DEBUG_PREFERRED = false;
234    static final boolean DEBUG_UPGRADE = false;
235    private static final boolean DEBUG_INSTALL = false;
236    private static final boolean DEBUG_REMOVE = false;
237    private static final boolean DEBUG_BROADCASTS = false;
238    private static final boolean DEBUG_SHOW_INFO = false;
239    private static final boolean DEBUG_PACKAGE_INFO = false;
240    private static final boolean DEBUG_INTENT_MATCHING = false;
241    private static final boolean DEBUG_PACKAGE_SCANNING = false;
242    private static final boolean DEBUG_VERIFY = false;
243    private static final boolean DEBUG_DEXOPT = false;
244    private static final boolean DEBUG_ABI_SELECTION = false;
245
246    private static final int RADIO_UID = Process.PHONE_UID;
247    private static final int LOG_UID = Process.LOG_UID;
248    private static final int NFC_UID = Process.NFC_UID;
249    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
250    private static final int SHELL_UID = Process.SHELL_UID;
251
252    // Cap the size of permission trees that 3rd party apps can define
253    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
254
255    // Suffix used during package installation when copying/moving
256    // package apks to install directory.
257    private static final String INSTALL_PACKAGE_SUFFIX = "-";
258
259    static final int SCAN_NO_DEX = 1<<1;
260    static final int SCAN_FORCE_DEX = 1<<2;
261    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
262    static final int SCAN_NEW_INSTALL = 1<<4;
263    static final int SCAN_NO_PATHS = 1<<5;
264    static final int SCAN_UPDATE_TIME = 1<<6;
265    static final int SCAN_DEFER_DEX = 1<<7;
266    static final int SCAN_BOOTING = 1<<8;
267    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
268    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
269    static final int SCAN_REPLACING = 1<<11;
270
271    static final int REMOVE_CHATTY = 1<<16;
272
273    /**
274     * Timeout (in milliseconds) after which the watchdog should declare that
275     * our handler thread is wedged.  The usual default for such things is one
276     * minute but we sometimes do very lengthy I/O operations on this thread,
277     * such as installing multi-gigabyte applications, so ours needs to be longer.
278     */
279    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
280
281    /**
282     * Whether verification is enabled by default.
283     */
284    private static final boolean DEFAULT_VERIFY_ENABLE = true;
285
286    /**
287     * The default maximum time to wait for the verification agent to return in
288     * milliseconds.
289     */
290    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
291
292    /**
293     * The default response for package verification timeout.
294     *
295     * This can be either PackageManager.VERIFICATION_ALLOW or
296     * PackageManager.VERIFICATION_REJECT.
297     */
298    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
299
300    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
301
302    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
303            DEFAULT_CONTAINER_PACKAGE,
304            "com.android.defcontainer.DefaultContainerService");
305
306    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
307
308    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
309
310    private static String sPreferredInstructionSet;
311
312    final ServiceThread mHandlerThread;
313
314    private static final String IDMAP_PREFIX = "/data/resource-cache/";
315    private static final String IDMAP_SUFFIX = "@idmap";
316
317    final PackageHandler mHandler;
318
319    /**
320     * Messages for {@link #mHandler} that need to wait for system ready before
321     * being dispatched.
322     */
323    private ArrayList<Message> mPostSystemReadyMessages;
324
325    final int mSdkVersion = Build.VERSION.SDK_INT;
326
327    final Context mContext;
328    final boolean mFactoryTest;
329    final boolean mOnlyCore;
330    final boolean mLazyDexOpt;
331    final DisplayMetrics mMetrics;
332    final int mDefParseFlags;
333    final String[] mSeparateProcesses;
334
335    // This is where all application persistent data goes.
336    final File mAppDataDir;
337
338    // This is where all application persistent data goes for secondary users.
339    final File mUserAppDataDir;
340
341    /** The location for ASEC container files on internal storage. */
342    final String mAsecInternalPath;
343
344    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
345    // LOCK HELD.  Can be called with mInstallLock held.
346    final Installer mInstaller;
347
348    /** Directory where installed third-party apps stored */
349    final File mAppInstallDir;
350
351    /**
352     * Directory to which applications installed internally have their
353     * 32 bit native libraries copied.
354     */
355    private File mAppLib32InstallDir;
356
357    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
358    // apps.
359    final File mDrmAppPrivateInstallDir;
360
361    // ----------------------------------------------------------------
362
363    // Lock for state used when installing and doing other long running
364    // operations.  Methods that must be called with this lock held have
365    // the suffix "LI".
366    final Object mInstallLock = new Object();
367
368    // ----------------------------------------------------------------
369
370    // Keys are String (package name), values are Package.  This also serves
371    // as the lock for the global state.  Methods that must be called with
372    // this lock held have the prefix "LP".
373    final HashMap<String, PackageParser.Package> mPackages =
374            new HashMap<String, PackageParser.Package>();
375
376    // Tracks available target package names -> overlay package paths.
377    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
378        new HashMap<String, HashMap<String, PackageParser.Package>>();
379
380    final Settings mSettings;
381    boolean mRestoredSettings;
382
383    // System configuration read by SystemConfig.
384    final int[] mGlobalGids;
385    final SparseArray<HashSet<String>> mSystemPermissions;
386    final HashMap<String, FeatureInfo> mAvailableFeatures;
387
388    // If mac_permissions.xml was found for seinfo labeling.
389    boolean mFoundPolicyFile;
390
391    // If a recursive restorecon of /data/data/<pkg> is needed.
392    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
393
394    public static final class SharedLibraryEntry {
395        public final String path;
396        public final String apk;
397
398        SharedLibraryEntry(String _path, String _apk) {
399            path = _path;
400            apk = _apk;
401        }
402    }
403
404    // Currently known shared libraries.
405    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
406            new HashMap<String, SharedLibraryEntry>();
407
408    // All available activities, for your resolving pleasure.
409    final ActivityIntentResolver mActivities =
410            new ActivityIntentResolver();
411
412    // All available receivers, for your resolving pleasure.
413    final ActivityIntentResolver mReceivers =
414            new ActivityIntentResolver();
415
416    // All available services, for your resolving pleasure.
417    final ServiceIntentResolver mServices = new ServiceIntentResolver();
418
419    // All available providers, for your resolving pleasure.
420    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
421
422    // Mapping from provider base names (first directory in content URI codePath)
423    // to the provider information.
424    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
425            new HashMap<String, PackageParser.Provider>();
426
427    // Mapping from instrumentation class names to info about them.
428    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
429            new HashMap<ComponentName, PackageParser.Instrumentation>();
430
431    // Mapping from permission names to info about them.
432    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
433            new HashMap<String, PackageParser.PermissionGroup>();
434
435    // Packages whose data we have transfered into another package, thus
436    // should no longer exist.
437    final HashSet<String> mTransferedPackages = new HashSet<String>();
438
439    // Broadcast actions that are only available to the system.
440    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
441
442    /** List of packages waiting for verification. */
443    final SparseArray<PackageVerificationState> mPendingVerification
444            = new SparseArray<PackageVerificationState>();
445
446    /** Set of packages associated with each app op permission. */
447    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
448
449    final PackageInstallerService mInstallerService;
450
451    HashSet<PackageParser.Package> mDeferredDexOpt = null;
452
453    // Cache of users who need badging.
454    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
455
456    /** Token for keys in mPendingVerification. */
457    private int mPendingVerificationToken = 0;
458
459    volatile boolean mSystemReady;
460    volatile boolean mSafeMode;
461    volatile boolean mHasSystemUidErrors;
462
463    ApplicationInfo mAndroidApplication;
464    final ActivityInfo mResolveActivity = new ActivityInfo();
465    final ResolveInfo mResolveInfo = new ResolveInfo();
466    ComponentName mResolveComponentName;
467    PackageParser.Package mPlatformPackage;
468    ComponentName mCustomResolverComponentName;
469
470    boolean mResolverReplaced = false;
471
472    // Set of pending broadcasts for aggregating enable/disable of components.
473    static class PendingPackageBroadcasts {
474        // for each user id, a map of <package name -> components within that package>
475        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
476
477        public PendingPackageBroadcasts() {
478            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
479        }
480
481        public ArrayList<String> get(int userId, String packageName) {
482            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
483            return packages.get(packageName);
484        }
485
486        public void put(int userId, String packageName, ArrayList<String> components) {
487            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
488            packages.put(packageName, components);
489        }
490
491        public void remove(int userId, String packageName) {
492            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
493            if (packages != null) {
494                packages.remove(packageName);
495            }
496        }
497
498        public void remove(int userId) {
499            mUidMap.remove(userId);
500        }
501
502        public int userIdCount() {
503            return mUidMap.size();
504        }
505
506        public int userIdAt(int n) {
507            return mUidMap.keyAt(n);
508        }
509
510        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
511            return mUidMap.get(userId);
512        }
513
514        public int size() {
515            // total number of pending broadcast entries across all userIds
516            int num = 0;
517            for (int i = 0; i< mUidMap.size(); i++) {
518                num += mUidMap.valueAt(i).size();
519            }
520            return num;
521        }
522
523        public void clear() {
524            mUidMap.clear();
525        }
526
527        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
528            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
529            if (map == null) {
530                map = new HashMap<String, ArrayList<String>>();
531                mUidMap.put(userId, map);
532            }
533            return map;
534        }
535    }
536    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
537
538    // Service Connection to remote media container service to copy
539    // package uri's from external media onto secure containers
540    // or internal storage.
541    private IMediaContainerService mContainerService = null;
542
543    static final int SEND_PENDING_BROADCAST = 1;
544    static final int MCS_BOUND = 3;
545    static final int END_COPY = 4;
546    static final int INIT_COPY = 5;
547    static final int MCS_UNBIND = 6;
548    static final int START_CLEANING_PACKAGE = 7;
549    static final int FIND_INSTALL_LOC = 8;
550    static final int POST_INSTALL = 9;
551    static final int MCS_RECONNECT = 10;
552    static final int MCS_GIVE_UP = 11;
553    static final int UPDATED_MEDIA_STATUS = 12;
554    static final int WRITE_SETTINGS = 13;
555    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
556    static final int PACKAGE_VERIFIED = 15;
557    static final int CHECK_PENDING_VERIFICATION = 16;
558
559    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
560
561    // Delay time in millisecs
562    static final int BROADCAST_DELAY = 10 * 1000;
563
564    static UserManagerService sUserManager;
565
566    // Stores a list of users whose package restrictions file needs to be updated
567    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
568
569    final private DefaultContainerConnection mDefContainerConn =
570            new DefaultContainerConnection();
571    class DefaultContainerConnection implements ServiceConnection {
572        public void onServiceConnected(ComponentName name, IBinder service) {
573            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
574            IMediaContainerService imcs =
575                IMediaContainerService.Stub.asInterface(service);
576            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
577        }
578
579        public void onServiceDisconnected(ComponentName name) {
580            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
581        }
582    };
583
584    // Recordkeeping of restore-after-install operations that are currently in flight
585    // between the Package Manager and the Backup Manager
586    class PostInstallData {
587        public InstallArgs args;
588        public PackageInstalledInfo res;
589
590        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
591            args = _a;
592            res = _r;
593        }
594    };
595    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
596    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
597
598    private final String mRequiredVerifierPackage;
599
600    private final PackageUsage mPackageUsage = new PackageUsage();
601
602    private class PackageUsage {
603        private static final int WRITE_INTERVAL
604            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
605
606        private final Object mFileLock = new Object();
607        private final AtomicLong mLastWritten = new AtomicLong(0);
608        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
609
610        private boolean mIsHistoricalPackageUsageAvailable = true;
611
612        boolean isHistoricalPackageUsageAvailable() {
613            return mIsHistoricalPackageUsageAvailable;
614        }
615
616        void write(boolean force) {
617            if (force) {
618                writeInternal();
619                return;
620            }
621            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
622                && !DEBUG_DEXOPT) {
623                return;
624            }
625            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
626                new Thread("PackageUsage_DiskWriter") {
627                    @Override
628                    public void run() {
629                        try {
630                            writeInternal();
631                        } finally {
632                            mBackgroundWriteRunning.set(false);
633                        }
634                    }
635                }.start();
636            }
637        }
638
639        private void writeInternal() {
640            synchronized (mPackages) {
641                synchronized (mFileLock) {
642                    AtomicFile file = getFile();
643                    FileOutputStream f = null;
644                    try {
645                        f = file.startWrite();
646                        BufferedOutputStream out = new BufferedOutputStream(f);
647                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
648                        StringBuilder sb = new StringBuilder();
649                        for (PackageParser.Package pkg : mPackages.values()) {
650                            if (pkg.mLastPackageUsageTimeInMills == 0) {
651                                continue;
652                            }
653                            sb.setLength(0);
654                            sb.append(pkg.packageName);
655                            sb.append(' ');
656                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
657                            sb.append('\n');
658                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
659                        }
660                        out.flush();
661                        file.finishWrite(f);
662                    } catch (IOException e) {
663                        if (f != null) {
664                            file.failWrite(f);
665                        }
666                        Log.e(TAG, "Failed to write package usage times", e);
667                    }
668                }
669            }
670            mLastWritten.set(SystemClock.elapsedRealtime());
671        }
672
673        void readLP() {
674            synchronized (mFileLock) {
675                AtomicFile file = getFile();
676                BufferedInputStream in = null;
677                try {
678                    in = new BufferedInputStream(file.openRead());
679                    StringBuffer sb = new StringBuffer();
680                    while (true) {
681                        String packageName = readToken(in, sb, ' ');
682                        if (packageName == null) {
683                            break;
684                        }
685                        String timeInMillisString = readToken(in, sb, '\n');
686                        if (timeInMillisString == null) {
687                            throw new IOException("Failed to find last usage time for package "
688                                                  + packageName);
689                        }
690                        PackageParser.Package pkg = mPackages.get(packageName);
691                        if (pkg == null) {
692                            continue;
693                        }
694                        long timeInMillis;
695                        try {
696                            timeInMillis = Long.parseLong(timeInMillisString.toString());
697                        } catch (NumberFormatException e) {
698                            throw new IOException("Failed to parse " + timeInMillisString
699                                                  + " as a long.", e);
700                        }
701                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
702                    }
703                } catch (FileNotFoundException expected) {
704                    mIsHistoricalPackageUsageAvailable = false;
705                } catch (IOException e) {
706                    Log.w(TAG, "Failed to read package usage times", e);
707                } finally {
708                    IoUtils.closeQuietly(in);
709                }
710            }
711            mLastWritten.set(SystemClock.elapsedRealtime());
712        }
713
714        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
715                throws IOException {
716            sb.setLength(0);
717            while (true) {
718                int ch = in.read();
719                if (ch == -1) {
720                    if (sb.length() == 0) {
721                        return null;
722                    }
723                    throw new IOException("Unexpected EOF");
724                }
725                if (ch == endOfToken) {
726                    return sb.toString();
727                }
728                sb.append((char)ch);
729            }
730        }
731
732        private AtomicFile getFile() {
733            File dataDir = Environment.getDataDirectory();
734            File systemDir = new File(dataDir, "system");
735            File fname = new File(systemDir, "package-usage.list");
736            return new AtomicFile(fname);
737        }
738    }
739
740    class PackageHandler extends Handler {
741        private boolean mBound = false;
742        final ArrayList<HandlerParams> mPendingInstalls =
743            new ArrayList<HandlerParams>();
744
745        private boolean connectToService() {
746            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
747                    " DefaultContainerService");
748            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
749            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
750            if (mContext.bindServiceAsUser(service, mDefContainerConn,
751                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
752                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
753                mBound = true;
754                return true;
755            }
756            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
757            return false;
758        }
759
760        private void disconnectService() {
761            mContainerService = null;
762            mBound = false;
763            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
764            mContext.unbindService(mDefContainerConn);
765            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
766        }
767
768        PackageHandler(Looper looper) {
769            super(looper);
770        }
771
772        public void handleMessage(Message msg) {
773            try {
774                doHandleMessage(msg);
775            } finally {
776                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
777            }
778        }
779
780        void doHandleMessage(Message msg) {
781            switch (msg.what) {
782                case INIT_COPY: {
783                    HandlerParams params = (HandlerParams) msg.obj;
784                    int idx = mPendingInstalls.size();
785                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
786                    // If a bind was already initiated we dont really
787                    // need to do anything. The pending install
788                    // will be processed later on.
789                    if (!mBound) {
790                        // If this is the only one pending we might
791                        // have to bind to the service again.
792                        if (!connectToService()) {
793                            Slog.e(TAG, "Failed to bind to media container service");
794                            params.serviceError();
795                            return;
796                        } else {
797                            // Once we bind to the service, the first
798                            // pending request will be processed.
799                            mPendingInstalls.add(idx, params);
800                        }
801                    } else {
802                        mPendingInstalls.add(idx, params);
803                        // Already bound to the service. Just make
804                        // sure we trigger off processing the first request.
805                        if (idx == 0) {
806                            mHandler.sendEmptyMessage(MCS_BOUND);
807                        }
808                    }
809                    break;
810                }
811                case MCS_BOUND: {
812                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
813                    if (msg.obj != null) {
814                        mContainerService = (IMediaContainerService) msg.obj;
815                    }
816                    if (mContainerService == null) {
817                        // Something seriously wrong. Bail out
818                        Slog.e(TAG, "Cannot bind to media container service");
819                        for (HandlerParams params : mPendingInstalls) {
820                            // Indicate service bind error
821                            params.serviceError();
822                        }
823                        mPendingInstalls.clear();
824                    } else if (mPendingInstalls.size() > 0) {
825                        HandlerParams params = mPendingInstalls.get(0);
826                        if (params != null) {
827                            if (params.startCopy()) {
828                                // We are done...  look for more work or to
829                                // go idle.
830                                if (DEBUG_SD_INSTALL) Log.i(TAG,
831                                        "Checking for more work or unbind...");
832                                // Delete pending install
833                                if (mPendingInstalls.size() > 0) {
834                                    mPendingInstalls.remove(0);
835                                }
836                                if (mPendingInstalls.size() == 0) {
837                                    if (mBound) {
838                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
839                                                "Posting delayed MCS_UNBIND");
840                                        removeMessages(MCS_UNBIND);
841                                        Message ubmsg = obtainMessage(MCS_UNBIND);
842                                        // Unbind after a little delay, to avoid
843                                        // continual thrashing.
844                                        sendMessageDelayed(ubmsg, 10000);
845                                    }
846                                } else {
847                                    // There are more pending requests in queue.
848                                    // Just post MCS_BOUND message to trigger processing
849                                    // of next pending install.
850                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
851                                            "Posting MCS_BOUND for next work");
852                                    mHandler.sendEmptyMessage(MCS_BOUND);
853                                }
854                            }
855                        }
856                    } else {
857                        // Should never happen ideally.
858                        Slog.w(TAG, "Empty queue");
859                    }
860                    break;
861                }
862                case MCS_RECONNECT: {
863                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
864                    if (mPendingInstalls.size() > 0) {
865                        if (mBound) {
866                            disconnectService();
867                        }
868                        if (!connectToService()) {
869                            Slog.e(TAG, "Failed to bind to media container service");
870                            for (HandlerParams params : mPendingInstalls) {
871                                // Indicate service bind error
872                                params.serviceError();
873                            }
874                            mPendingInstalls.clear();
875                        }
876                    }
877                    break;
878                }
879                case MCS_UNBIND: {
880                    // If there is no actual work left, then time to unbind.
881                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
882
883                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
884                        if (mBound) {
885                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
886
887                            disconnectService();
888                        }
889                    } else if (mPendingInstalls.size() > 0) {
890                        // There are more pending requests in queue.
891                        // Just post MCS_BOUND message to trigger processing
892                        // of next pending install.
893                        mHandler.sendEmptyMessage(MCS_BOUND);
894                    }
895
896                    break;
897                }
898                case MCS_GIVE_UP: {
899                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
900                    mPendingInstalls.remove(0);
901                    break;
902                }
903                case SEND_PENDING_BROADCAST: {
904                    String packages[];
905                    ArrayList<String> components[];
906                    int size = 0;
907                    int uids[];
908                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
909                    synchronized (mPackages) {
910                        if (mPendingBroadcasts == null) {
911                            return;
912                        }
913                        size = mPendingBroadcasts.size();
914                        if (size <= 0) {
915                            // Nothing to be done. Just return
916                            return;
917                        }
918                        packages = new String[size];
919                        components = new ArrayList[size];
920                        uids = new int[size];
921                        int i = 0;  // filling out the above arrays
922
923                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
924                            int packageUserId = mPendingBroadcasts.userIdAt(n);
925                            Iterator<Map.Entry<String, ArrayList<String>>> it
926                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
927                                            .entrySet().iterator();
928                            while (it.hasNext() && i < size) {
929                                Map.Entry<String, ArrayList<String>> ent = it.next();
930                                packages[i] = ent.getKey();
931                                components[i] = ent.getValue();
932                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
933                                uids[i] = (ps != null)
934                                        ? UserHandle.getUid(packageUserId, ps.appId)
935                                        : -1;
936                                i++;
937                            }
938                        }
939                        size = i;
940                        mPendingBroadcasts.clear();
941                    }
942                    // Send broadcasts
943                    for (int i = 0; i < size; i++) {
944                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
945                    }
946                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
947                    break;
948                }
949                case START_CLEANING_PACKAGE: {
950                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
951                    final String packageName = (String)msg.obj;
952                    final int userId = msg.arg1;
953                    final boolean andCode = msg.arg2 != 0;
954                    synchronized (mPackages) {
955                        if (userId == UserHandle.USER_ALL) {
956                            int[] users = sUserManager.getUserIds();
957                            for (int user : users) {
958                                mSettings.addPackageToCleanLPw(
959                                        new PackageCleanItem(user, packageName, andCode));
960                            }
961                        } else {
962                            mSettings.addPackageToCleanLPw(
963                                    new PackageCleanItem(userId, packageName, andCode));
964                        }
965                    }
966                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
967                    startCleaningPackages();
968                } break;
969                case POST_INSTALL: {
970                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
971                    PostInstallData data = mRunningInstalls.get(msg.arg1);
972                    mRunningInstalls.delete(msg.arg1);
973                    boolean deleteOld = false;
974
975                    if (data != null) {
976                        InstallArgs args = data.args;
977                        PackageInstalledInfo res = data.res;
978
979                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
980                            res.removedInfo.sendBroadcast(false, true, false);
981                            Bundle extras = new Bundle(1);
982                            extras.putInt(Intent.EXTRA_UID, res.uid);
983                            // Determine the set of users who are adding this
984                            // package for the first time vs. those who are seeing
985                            // an update.
986                            int[] firstUsers;
987                            int[] updateUsers = new int[0];
988                            if (res.origUsers == null || res.origUsers.length == 0) {
989                                firstUsers = res.newUsers;
990                            } else {
991                                firstUsers = new int[0];
992                                for (int i=0; i<res.newUsers.length; i++) {
993                                    int user = res.newUsers[i];
994                                    boolean isNew = true;
995                                    for (int j=0; j<res.origUsers.length; j++) {
996                                        if (res.origUsers[j] == user) {
997                                            isNew = false;
998                                            break;
999                                        }
1000                                    }
1001                                    if (isNew) {
1002                                        int[] newFirst = new int[firstUsers.length+1];
1003                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1004                                                firstUsers.length);
1005                                        newFirst[firstUsers.length] = user;
1006                                        firstUsers = newFirst;
1007                                    } else {
1008                                        int[] newUpdate = new int[updateUsers.length+1];
1009                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1010                                                updateUsers.length);
1011                                        newUpdate[updateUsers.length] = user;
1012                                        updateUsers = newUpdate;
1013                                    }
1014                                }
1015                            }
1016                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1017                                    res.pkg.applicationInfo.packageName,
1018                                    extras, null, null, firstUsers);
1019                            final boolean update = res.removedInfo.removedPackage != null;
1020                            if (update) {
1021                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1022                            }
1023                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1024                                    res.pkg.applicationInfo.packageName,
1025                                    extras, null, null, updateUsers);
1026                            if (update) {
1027                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1028                                        res.pkg.applicationInfo.packageName,
1029                                        extras, null, null, updateUsers);
1030                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1031                                        null, null,
1032                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1033
1034                                // treat asec-hosted packages like removable media on upgrade
1035                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1036                                    if (DEBUG_INSTALL) {
1037                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1038                                                + " is ASEC-hosted -> AVAILABLE");
1039                                    }
1040                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1041                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1042                                    pkgList.add(res.pkg.applicationInfo.packageName);
1043                                    sendResourcesChangedBroadcast(true, true,
1044                                            pkgList,uidArray, null);
1045                                }
1046                            }
1047                            if (res.removedInfo.args != null) {
1048                                // Remove the replaced package's older resources safely now
1049                                deleteOld = true;
1050                            }
1051
1052                            // Log current value of "unknown sources" setting
1053                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1054                                getUnknownSourcesSettings());
1055                        }
1056                        // Force a gc to clear up things
1057                        Runtime.getRuntime().gc();
1058                        // We delete after a gc for applications  on sdcard.
1059                        if (deleteOld) {
1060                            synchronized (mInstallLock) {
1061                                res.removedInfo.args.doPostDeleteLI(true);
1062                            }
1063                        }
1064                        if (args.observer != null) {
1065                            try {
1066                                Bundle extras = extrasForInstallResult(res);
1067                                args.observer.onPackageInstalled(res.name, res.returnCode,
1068                                        res.returnMsg, extras);
1069                            } catch (RemoteException e) {
1070                                Slog.i(TAG, "Observer no longer exists.");
1071                            }
1072                        }
1073                    } else {
1074                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1075                    }
1076                } break;
1077                case UPDATED_MEDIA_STATUS: {
1078                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1079                    boolean reportStatus = msg.arg1 == 1;
1080                    boolean doGc = msg.arg2 == 1;
1081                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1082                    if (doGc) {
1083                        // Force a gc to clear up stale containers.
1084                        Runtime.getRuntime().gc();
1085                    }
1086                    if (msg.obj != null) {
1087                        @SuppressWarnings("unchecked")
1088                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1089                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1090                        // Unload containers
1091                        unloadAllContainers(args);
1092                    }
1093                    if (reportStatus) {
1094                        try {
1095                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1096                            PackageHelper.getMountService().finishMediaUpdate();
1097                        } catch (RemoteException e) {
1098                            Log.e(TAG, "MountService not running?");
1099                        }
1100                    }
1101                } break;
1102                case WRITE_SETTINGS: {
1103                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1104                    synchronized (mPackages) {
1105                        removeMessages(WRITE_SETTINGS);
1106                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1107                        mSettings.writeLPr();
1108                        mDirtyUsers.clear();
1109                    }
1110                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1111                } break;
1112                case WRITE_PACKAGE_RESTRICTIONS: {
1113                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1114                    synchronized (mPackages) {
1115                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1116                        for (int userId : mDirtyUsers) {
1117                            mSettings.writePackageRestrictionsLPr(userId);
1118                        }
1119                        mDirtyUsers.clear();
1120                    }
1121                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1122                } break;
1123                case CHECK_PENDING_VERIFICATION: {
1124                    final int verificationId = msg.arg1;
1125                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1126
1127                    if ((state != null) && !state.timeoutExtended()) {
1128                        final InstallArgs args = state.getInstallArgs();
1129                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1130
1131                        Slog.i(TAG, "Verification timed out for " + originUri);
1132                        mPendingVerification.remove(verificationId);
1133
1134                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1135
1136                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1137                            Slog.i(TAG, "Continuing with installation of " + originUri);
1138                            state.setVerifierResponse(Binder.getCallingUid(),
1139                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1140                            broadcastPackageVerified(verificationId, originUri,
1141                                    PackageManager.VERIFICATION_ALLOW,
1142                                    state.getInstallArgs().getUser());
1143                            try {
1144                                ret = args.copyApk(mContainerService, true);
1145                            } catch (RemoteException e) {
1146                                Slog.e(TAG, "Could not contact the ContainerService");
1147                            }
1148                        } else {
1149                            broadcastPackageVerified(verificationId, originUri,
1150                                    PackageManager.VERIFICATION_REJECT,
1151                                    state.getInstallArgs().getUser());
1152                        }
1153
1154                        processPendingInstall(args, ret);
1155                        mHandler.sendEmptyMessage(MCS_UNBIND);
1156                    }
1157                    break;
1158                }
1159                case PACKAGE_VERIFIED: {
1160                    final int verificationId = msg.arg1;
1161
1162                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1163                    if (state == null) {
1164                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1165                        break;
1166                    }
1167
1168                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1169
1170                    state.setVerifierResponse(response.callerUid, response.code);
1171
1172                    if (state.isVerificationComplete()) {
1173                        mPendingVerification.remove(verificationId);
1174
1175                        final InstallArgs args = state.getInstallArgs();
1176                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1177
1178                        int ret;
1179                        if (state.isInstallAllowed()) {
1180                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1181                            broadcastPackageVerified(verificationId, originUri,
1182                                    response.code, state.getInstallArgs().getUser());
1183                            try {
1184                                ret = args.copyApk(mContainerService, true);
1185                            } catch (RemoteException e) {
1186                                Slog.e(TAG, "Could not contact the ContainerService");
1187                            }
1188                        } else {
1189                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1190                        }
1191
1192                        processPendingInstall(args, ret);
1193
1194                        mHandler.sendEmptyMessage(MCS_UNBIND);
1195                    }
1196
1197                    break;
1198                }
1199            }
1200        }
1201    }
1202
1203    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1204        Bundle extras = null;
1205        switch (res.returnCode) {
1206            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1207                extras = new Bundle();
1208                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1209                        res.origPermission);
1210                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1211                        res.origPackage);
1212                break;
1213            }
1214        }
1215        return extras;
1216    }
1217
1218    void scheduleWriteSettingsLocked() {
1219        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1220            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1221        }
1222    }
1223
1224    void scheduleWritePackageRestrictionsLocked(int userId) {
1225        if (!sUserManager.exists(userId)) return;
1226        mDirtyUsers.add(userId);
1227        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1228            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1229        }
1230    }
1231
1232    public static final PackageManagerService main(Context context, Installer installer,
1233            boolean factoryTest, boolean onlyCore) {
1234        PackageManagerService m = new PackageManagerService(context, installer,
1235                factoryTest, onlyCore);
1236        ServiceManager.addService("package", m);
1237        return m;
1238    }
1239
1240    static String[] splitString(String str, char sep) {
1241        int count = 1;
1242        int i = 0;
1243        while ((i=str.indexOf(sep, i)) >= 0) {
1244            count++;
1245            i++;
1246        }
1247
1248        String[] res = new String[count];
1249        i=0;
1250        count = 0;
1251        int lastI=0;
1252        while ((i=str.indexOf(sep, i)) >= 0) {
1253            res[count] = str.substring(lastI, i);
1254            count++;
1255            i++;
1256            lastI = i;
1257        }
1258        res[count] = str.substring(lastI, str.length());
1259        return res;
1260    }
1261
1262    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1263        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1264                Context.DISPLAY_SERVICE);
1265        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1266    }
1267
1268    public PackageManagerService(Context context, Installer installer,
1269            boolean factoryTest, boolean onlyCore) {
1270        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1271                SystemClock.uptimeMillis());
1272
1273        if (mSdkVersion <= 0) {
1274            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1275        }
1276
1277        mContext = context;
1278        mFactoryTest = factoryTest;
1279        mOnlyCore = onlyCore;
1280        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1281        mMetrics = new DisplayMetrics();
1282        mSettings = new Settings(context);
1283        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1284                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1285        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1286                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1287        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1288                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1289        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1290                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1291        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1292                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1293        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1294                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1295
1296        String separateProcesses = SystemProperties.get("debug.separate_processes");
1297        if (separateProcesses != null && separateProcesses.length() > 0) {
1298            if ("*".equals(separateProcesses)) {
1299                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1300                mSeparateProcesses = null;
1301                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1302            } else {
1303                mDefParseFlags = 0;
1304                mSeparateProcesses = separateProcesses.split(",");
1305                Slog.w(TAG, "Running with debug.separate_processes: "
1306                        + separateProcesses);
1307            }
1308        } else {
1309            mDefParseFlags = 0;
1310            mSeparateProcesses = null;
1311        }
1312
1313        mInstaller = installer;
1314
1315        getDefaultDisplayMetrics(context, mMetrics);
1316
1317        SystemConfig systemConfig = SystemConfig.getInstance();
1318        mGlobalGids = systemConfig.getGlobalGids();
1319        mSystemPermissions = systemConfig.getSystemPermissions();
1320        mAvailableFeatures = systemConfig.getAvailableFeatures();
1321
1322        synchronized (mInstallLock) {
1323        // writer
1324        synchronized (mPackages) {
1325            mHandlerThread = new ServiceThread(TAG,
1326                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1327            mHandlerThread.start();
1328            mHandler = new PackageHandler(mHandlerThread.getLooper());
1329            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1330
1331            File dataDir = Environment.getDataDirectory();
1332            mAppDataDir = new File(dataDir, "data");
1333            mAppInstallDir = new File(dataDir, "app");
1334            mAppLib32InstallDir = new File(dataDir, "app-lib");
1335            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1336            mUserAppDataDir = new File(dataDir, "user");
1337            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1338
1339            sUserManager = new UserManagerService(context, this,
1340                    mInstallLock, mPackages);
1341
1342            // Propagate permission configuration in to package manager.
1343            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1344                    = systemConfig.getPermissions();
1345            for (int i=0; i<permConfig.size(); i++) {
1346                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1347                BasePermission bp = mSettings.mPermissions.get(perm.name);
1348                if (bp == null) {
1349                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1350                    mSettings.mPermissions.put(perm.name, bp);
1351                }
1352                if (perm.gids != null) {
1353                    bp.gids = appendInts(bp.gids, perm.gids);
1354                }
1355            }
1356
1357            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1358            for (int i=0; i<libConfig.size(); i++) {
1359                mSharedLibraries.put(libConfig.keyAt(i),
1360                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1361            }
1362
1363            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1364
1365            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1366                    mSdkVersion, mOnlyCore);
1367
1368            String customResolverActivity = Resources.getSystem().getString(
1369                    R.string.config_customResolverActivity);
1370            if (TextUtils.isEmpty(customResolverActivity)) {
1371                customResolverActivity = null;
1372            } else {
1373                mCustomResolverComponentName = ComponentName.unflattenFromString(
1374                        customResolverActivity);
1375            }
1376
1377            long startTime = SystemClock.uptimeMillis();
1378
1379            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1380                    startTime);
1381
1382            // Set flag to monitor and not change apk file paths when
1383            // scanning install directories.
1384            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1385
1386            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1387
1388            /**
1389             * Add everything in the in the boot class path to the
1390             * list of process files because dexopt will have been run
1391             * if necessary during zygote startup.
1392             */
1393            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1394            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1395
1396            if (bootClassPath != null) {
1397                String[] bootClassPathElements = splitString(bootClassPath, ':');
1398                for (String element : bootClassPathElements) {
1399                    alreadyDexOpted.add(element);
1400                }
1401            } else {
1402                Slog.w(TAG, "No BOOTCLASSPATH found!");
1403            }
1404
1405            if (systemServerClassPath != null) {
1406                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1407                for (String element : systemServerClassPathElements) {
1408                    alreadyDexOpted.add(element);
1409                }
1410            } else {
1411                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1412            }
1413
1414            boolean didDexOptLibraryOrTool = false;
1415
1416            final List<String> allInstructionSets = getAllInstructionSets();
1417            final String[] dexCodeInstructionSets =
1418                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1419
1420            /**
1421             * Ensure all external libraries have had dexopt run on them.
1422             */
1423            if (mSharedLibraries.size() > 0) {
1424                // NOTE: For now, we're compiling these system "shared libraries"
1425                // (and framework jars) into all available architectures. It's possible
1426                // to compile them only when we come across an app that uses them (there's
1427                // already logic for that in scanPackageLI) but that adds some complexity.
1428                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1429                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1430                        final String lib = libEntry.path;
1431                        if (lib == null) {
1432                            continue;
1433                        }
1434
1435                        try {
1436                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1437                                                                                 dexCodeInstructionSet,
1438                                                                                 false);
1439                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1440                                alreadyDexOpted.add(lib);
1441
1442                                // The list of "shared libraries" we have at this point is
1443                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1444                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1445                                } else {
1446                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1447                                }
1448                                didDexOptLibraryOrTool = true;
1449                            }
1450                        } catch (FileNotFoundException e) {
1451                            Slog.w(TAG, "Library not found: " + lib);
1452                        } catch (IOException e) {
1453                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1454                                    + e.getMessage());
1455                        }
1456                    }
1457                }
1458            }
1459
1460            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1461
1462            // Gross hack for now: we know this file doesn't contain any
1463            // code, so don't dexopt it to avoid the resulting log spew.
1464            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1465
1466            // Gross hack for now: we know this file is only part of
1467            // the boot class path for art, so don't dexopt it to
1468            // avoid the resulting log spew.
1469            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1470
1471            /**
1472             * And there are a number of commands implemented in Java, which
1473             * we currently need to do the dexopt on so that they can be
1474             * run from a non-root shell.
1475             */
1476            String[] frameworkFiles = frameworkDir.list();
1477            if (frameworkFiles != null) {
1478                // TODO: We could compile these only for the most preferred ABI. We should
1479                // first double check that the dex files for these commands are not referenced
1480                // by other system apps.
1481                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1482                    for (int i=0; i<frameworkFiles.length; i++) {
1483                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1484                        String path = libPath.getPath();
1485                        // Skip the file if we already did it.
1486                        if (alreadyDexOpted.contains(path)) {
1487                            continue;
1488                        }
1489                        // Skip the file if it is not a type we want to dexopt.
1490                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1491                            continue;
1492                        }
1493                        try {
1494                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1495                                                                                 dexCodeInstructionSet,
1496                                                                                 false);
1497                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1498                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1499                                didDexOptLibraryOrTool = true;
1500                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1501                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1502                                didDexOptLibraryOrTool = true;
1503                            }
1504                        } catch (FileNotFoundException e) {
1505                            Slog.w(TAG, "Jar not found: " + path);
1506                        } catch (IOException e) {
1507                            Slog.w(TAG, "Exception reading jar: " + path, e);
1508                        }
1509                    }
1510                }
1511            }
1512
1513            // Collect vendor overlay packages.
1514            // (Do this before scanning any apps.)
1515            // For security and version matching reason, only consider
1516            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1517            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1518            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1519                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1520
1521            // Find base frameworks (resource packages without code).
1522            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1523                    | PackageParser.PARSE_IS_SYSTEM_DIR
1524                    | PackageParser.PARSE_IS_PRIVILEGED,
1525                    scanFlags | SCAN_NO_DEX, 0);
1526
1527            // Collected privileged system packages.
1528            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1529            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1530                    | PackageParser.PARSE_IS_SYSTEM_DIR
1531                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1532
1533            // Collect ordinary system packages.
1534            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1535            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1536                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1537
1538            // Collect all vendor packages.
1539            File vendorAppDir = new File("/vendor/app");
1540            try {
1541                vendorAppDir = vendorAppDir.getCanonicalFile();
1542            } catch (IOException e) {
1543                // failed to look up canonical path, continue with original one
1544            }
1545            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1546                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1547
1548            // Collect all OEM packages.
1549            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1550            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1551                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1552
1553            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1554            mInstaller.moveFiles();
1555
1556            // Prune any system packages that no longer exist.
1557            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1558            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1559            if (!mOnlyCore) {
1560                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1561                while (psit.hasNext()) {
1562                    PackageSetting ps = psit.next();
1563
1564                    /*
1565                     * If this is not a system app, it can't be a
1566                     * disable system app.
1567                     */
1568                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1569                        continue;
1570                    }
1571
1572                    /*
1573                     * If the package is scanned, it's not erased.
1574                     */
1575                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1576                    if (scannedPkg != null) {
1577                        /*
1578                         * If the system app is both scanned and in the
1579                         * disabled packages list, then it must have been
1580                         * added via OTA. Remove it from the currently
1581                         * scanned package so the previously user-installed
1582                         * application can be scanned.
1583                         */
1584                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1585                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1586                                    + ps.name + "; removing system app.  Last known codePath="
1587                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1588                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1589                                    + scannedPkg.mVersionCode);
1590                            removePackageLI(ps, true);
1591                            expectingBetter.put(ps.name, ps.codePath);
1592                        }
1593
1594                        continue;
1595                    }
1596
1597                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1598                        psit.remove();
1599                        logCriticalInfo(Log.WARN, "System package " + ps.name
1600                                + " no longer exists; wiping its data");
1601                        removeDataDirsLI(ps.name);
1602                    } else {
1603                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1604                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1605                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1606                        }
1607                    }
1608                }
1609            }
1610
1611            //look for any incomplete package installations
1612            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1613            //clean up list
1614            for(int i = 0; i < deletePkgsList.size(); i++) {
1615                //clean up here
1616                cleanupInstallFailedPackage(deletePkgsList.get(i));
1617            }
1618            //delete tmp files
1619            deleteTempPackageFiles();
1620
1621            // Remove any shared userIDs that have no associated packages
1622            mSettings.pruneSharedUsersLPw();
1623
1624            if (!mOnlyCore) {
1625                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1626                        SystemClock.uptimeMillis());
1627                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1628
1629                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1630                        scanFlags, 0);
1631
1632                /**
1633                 * Remove disable package settings for any updated system
1634                 * apps that were removed via an OTA. If they're not a
1635                 * previously-updated app, remove them completely.
1636                 * Otherwise, just revoke their system-level permissions.
1637                 */
1638                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1639                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1640                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1641
1642                    String msg;
1643                    if (deletedPkg == null) {
1644                        msg = "Updated system package " + deletedAppName
1645                                + " no longer exists; wiping its data";
1646                        removeDataDirsLI(deletedAppName);
1647                    } else {
1648                        msg = "Updated system app + " + deletedAppName
1649                                + " no longer present; removing system privileges for "
1650                                + deletedAppName;
1651
1652                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1653
1654                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1655                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1656                    }
1657                    logCriticalInfo(Log.WARN, msg);
1658                }
1659
1660                /**
1661                 * Make sure all system apps that we expected to appear on
1662                 * the userdata partition actually showed up. If they never
1663                 * appeared, crawl back and revive the system version.
1664                 */
1665                for (int i = 0; i < expectingBetter.size(); i++) {
1666                    final String packageName = expectingBetter.keyAt(i);
1667                    if (!mPackages.containsKey(packageName)) {
1668                        final File scanFile = expectingBetter.valueAt(i);
1669
1670                        logCriticalInfo(Log.WARN, "Expected better " + packageName
1671                                + " but never showed up; reverting to system");
1672
1673                        final int reparseFlags;
1674                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
1675                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1676                                    | PackageParser.PARSE_IS_SYSTEM_DIR
1677                                    | PackageParser.PARSE_IS_PRIVILEGED;
1678                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
1679                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1680                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1681                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
1682                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1683                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1684                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
1685                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1686                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1687                        } else {
1688                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
1689                            continue;
1690                        }
1691
1692                        mSettings.enableSystemPackageLPw(packageName);
1693
1694                        try {
1695                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
1696                        } catch (PackageManagerException e) {
1697                            Slog.e(TAG, "Failed to parse original system package: "
1698                                    + e.getMessage());
1699                        }
1700                    }
1701                }
1702            }
1703
1704            // Now that we know all of the shared libraries, update all clients to have
1705            // the correct library paths.
1706            updateAllSharedLibrariesLPw();
1707
1708            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1709                // NOTE: We ignore potential failures here during a system scan (like
1710                // the rest of the commands above) because there's precious little we
1711                // can do about it. A settings error is reported, though.
1712                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1713                        false /* force dexopt */, false /* defer dexopt */);
1714            }
1715
1716            // Now that we know all the packages we are keeping,
1717            // read and update their last usage times.
1718            mPackageUsage.readLP();
1719
1720            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1721                    SystemClock.uptimeMillis());
1722            Slog.i(TAG, "Time to scan packages: "
1723                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1724                    + " seconds");
1725
1726            // If the platform SDK has changed since the last time we booted,
1727            // we need to re-grant app permission to catch any new ones that
1728            // appear.  This is really a hack, and means that apps can in some
1729            // cases get permissions that the user didn't initially explicitly
1730            // allow...  it would be nice to have some better way to handle
1731            // this situation.
1732            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1733                    != mSdkVersion;
1734            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1735                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1736                    + "; regranting permissions for internal storage");
1737            mSettings.mInternalSdkPlatform = mSdkVersion;
1738
1739            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1740                    | (regrantPermissions
1741                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1742                            : 0));
1743
1744            // If this is the first boot, and it is a normal boot, then
1745            // we need to initialize the default preferred apps.
1746            if (!mRestoredSettings && !onlyCore) {
1747                mSettings.readDefaultPreferredAppsLPw(this, 0);
1748            }
1749
1750            // If this is first boot after an OTA, and a normal boot, then
1751            // we need to clear code cache directories.
1752            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1753                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1754                for (String pkgName : mSettings.mPackages.keySet()) {
1755                    deleteCodeCacheDirsLI(pkgName);
1756                }
1757                mSettings.mFingerprint = Build.FINGERPRINT;
1758            }
1759
1760            // All the changes are done during package scanning.
1761            mSettings.updateInternalDatabaseVersion();
1762
1763            // can downgrade to reader
1764            mSettings.writeLPr();
1765
1766            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1767                    SystemClock.uptimeMillis());
1768
1769
1770            mRequiredVerifierPackage = getRequiredVerifierLPr();
1771        } // synchronized (mPackages)
1772        } // synchronized (mInstallLock)
1773
1774        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1775
1776        // Now after opening every single application zip, make sure they
1777        // are all flushed.  Not really needed, but keeps things nice and
1778        // tidy.
1779        Runtime.getRuntime().gc();
1780    }
1781
1782    @Override
1783    public boolean isFirstBoot() {
1784        return !mRestoredSettings;
1785    }
1786
1787    @Override
1788    public boolean isOnlyCoreApps() {
1789        return mOnlyCore;
1790    }
1791
1792    private String getRequiredVerifierLPr() {
1793        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1794        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1795                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1796
1797        String requiredVerifier = null;
1798
1799        final int N = receivers.size();
1800        for (int i = 0; i < N; i++) {
1801            final ResolveInfo info = receivers.get(i);
1802
1803            if (info.activityInfo == null) {
1804                continue;
1805            }
1806
1807            final String packageName = info.activityInfo.packageName;
1808
1809            final PackageSetting ps = mSettings.mPackages.get(packageName);
1810            if (ps == null) {
1811                continue;
1812            }
1813
1814            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1815            if (!gp.grantedPermissions
1816                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1817                continue;
1818            }
1819
1820            if (requiredVerifier != null) {
1821                throw new RuntimeException("There can be only one required verifier");
1822            }
1823
1824            requiredVerifier = packageName;
1825        }
1826
1827        return requiredVerifier;
1828    }
1829
1830    @Override
1831    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1832            throws RemoteException {
1833        try {
1834            return super.onTransact(code, data, reply, flags);
1835        } catch (RuntimeException e) {
1836            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1837                Slog.wtf(TAG, "Package Manager Crash", e);
1838            }
1839            throw e;
1840        }
1841    }
1842
1843    void cleanupInstallFailedPackage(PackageSetting ps) {
1844        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
1845
1846        removeDataDirsLI(ps.name);
1847        if (ps.codePath != null) {
1848            if (ps.codePath.isDirectory()) {
1849                FileUtils.deleteContents(ps.codePath);
1850            }
1851            ps.codePath.delete();
1852        }
1853        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1854            if (ps.resourcePath.isDirectory()) {
1855                FileUtils.deleteContents(ps.resourcePath);
1856            }
1857            ps.resourcePath.delete();
1858        }
1859        mSettings.removePackageLPw(ps.name);
1860    }
1861
1862    static int[] appendInts(int[] cur, int[] add) {
1863        if (add == null) return cur;
1864        if (cur == null) return add;
1865        final int N = add.length;
1866        for (int i=0; i<N; i++) {
1867            cur = appendInt(cur, add[i]);
1868        }
1869        return cur;
1870    }
1871
1872    static int[] removeInts(int[] cur, int[] rem) {
1873        if (rem == null) return cur;
1874        if (cur == null) return cur;
1875        final int N = rem.length;
1876        for (int i=0; i<N; i++) {
1877            cur = removeInt(cur, rem[i]);
1878        }
1879        return cur;
1880    }
1881
1882    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1883        if (!sUserManager.exists(userId)) return null;
1884        final PackageSetting ps = (PackageSetting) p.mExtras;
1885        if (ps == null) {
1886            return null;
1887        }
1888        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1889        final PackageUserState state = ps.readUserState(userId);
1890        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1891                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1892                state, userId);
1893    }
1894
1895    @Override
1896    public boolean isPackageAvailable(String packageName, int userId) {
1897        if (!sUserManager.exists(userId)) return false;
1898        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
1899        synchronized (mPackages) {
1900            PackageParser.Package p = mPackages.get(packageName);
1901            if (p != null) {
1902                final PackageSetting ps = (PackageSetting) p.mExtras;
1903                if (ps != null) {
1904                    final PackageUserState state = ps.readUserState(userId);
1905                    if (state != null) {
1906                        return PackageParser.isAvailable(state);
1907                    }
1908                }
1909            }
1910        }
1911        return false;
1912    }
1913
1914    @Override
1915    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1916        if (!sUserManager.exists(userId)) return null;
1917        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
1918        // reader
1919        synchronized (mPackages) {
1920            PackageParser.Package p = mPackages.get(packageName);
1921            if (DEBUG_PACKAGE_INFO)
1922                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1923            if (p != null) {
1924                return generatePackageInfo(p, flags, userId);
1925            }
1926            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1927                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1928            }
1929        }
1930        return null;
1931    }
1932
1933    @Override
1934    public String[] currentToCanonicalPackageNames(String[] names) {
1935        String[] out = new String[names.length];
1936        // reader
1937        synchronized (mPackages) {
1938            for (int i=names.length-1; i>=0; i--) {
1939                PackageSetting ps = mSettings.mPackages.get(names[i]);
1940                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1941            }
1942        }
1943        return out;
1944    }
1945
1946    @Override
1947    public String[] canonicalToCurrentPackageNames(String[] names) {
1948        String[] out = new String[names.length];
1949        // reader
1950        synchronized (mPackages) {
1951            for (int i=names.length-1; i>=0; i--) {
1952                String cur = mSettings.mRenamedPackages.get(names[i]);
1953                out[i] = cur != null ? cur : names[i];
1954            }
1955        }
1956        return out;
1957    }
1958
1959    @Override
1960    public int getPackageUid(String packageName, int userId) {
1961        if (!sUserManager.exists(userId)) return -1;
1962        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
1963        // reader
1964        synchronized (mPackages) {
1965            PackageParser.Package p = mPackages.get(packageName);
1966            if(p != null) {
1967                return UserHandle.getUid(userId, p.applicationInfo.uid);
1968            }
1969            PackageSetting ps = mSettings.mPackages.get(packageName);
1970            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1971                return -1;
1972            }
1973            p = ps.pkg;
1974            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1975        }
1976    }
1977
1978    @Override
1979    public int[] getPackageGids(String packageName) {
1980        // reader
1981        synchronized (mPackages) {
1982            PackageParser.Package p = mPackages.get(packageName);
1983            if (DEBUG_PACKAGE_INFO)
1984                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1985            if (p != null) {
1986                final PackageSetting ps = (PackageSetting)p.mExtras;
1987                return ps.getGids();
1988            }
1989        }
1990        // stupid thing to indicate an error.
1991        return new int[0];
1992    }
1993
1994    static final PermissionInfo generatePermissionInfo(
1995            BasePermission bp, int flags) {
1996        if (bp.perm != null) {
1997            return PackageParser.generatePermissionInfo(bp.perm, flags);
1998        }
1999        PermissionInfo pi = new PermissionInfo();
2000        pi.name = bp.name;
2001        pi.packageName = bp.sourcePackage;
2002        pi.nonLocalizedLabel = bp.name;
2003        pi.protectionLevel = bp.protectionLevel;
2004        return pi;
2005    }
2006
2007    @Override
2008    public PermissionInfo getPermissionInfo(String name, int flags) {
2009        // reader
2010        synchronized (mPackages) {
2011            final BasePermission p = mSettings.mPermissions.get(name);
2012            if (p != null) {
2013                return generatePermissionInfo(p, flags);
2014            }
2015            return null;
2016        }
2017    }
2018
2019    @Override
2020    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2021        // reader
2022        synchronized (mPackages) {
2023            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2024            for (BasePermission p : mSettings.mPermissions.values()) {
2025                if (group == null) {
2026                    if (p.perm == null || p.perm.info.group == null) {
2027                        out.add(generatePermissionInfo(p, flags));
2028                    }
2029                } else {
2030                    if (p.perm != null && group.equals(p.perm.info.group)) {
2031                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2032                    }
2033                }
2034            }
2035
2036            if (out.size() > 0) {
2037                return out;
2038            }
2039            return mPermissionGroups.containsKey(group) ? out : null;
2040        }
2041    }
2042
2043    @Override
2044    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2045        // reader
2046        synchronized (mPackages) {
2047            return PackageParser.generatePermissionGroupInfo(
2048                    mPermissionGroups.get(name), flags);
2049        }
2050    }
2051
2052    @Override
2053    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2054        // reader
2055        synchronized (mPackages) {
2056            final int N = mPermissionGroups.size();
2057            ArrayList<PermissionGroupInfo> out
2058                    = new ArrayList<PermissionGroupInfo>(N);
2059            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2060                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2061            }
2062            return out;
2063        }
2064    }
2065
2066    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2067            int userId) {
2068        if (!sUserManager.exists(userId)) return null;
2069        PackageSetting ps = mSettings.mPackages.get(packageName);
2070        if (ps != null) {
2071            if (ps.pkg == null) {
2072                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2073                        flags, userId);
2074                if (pInfo != null) {
2075                    return pInfo.applicationInfo;
2076                }
2077                return null;
2078            }
2079            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2080                    ps.readUserState(userId), userId);
2081        }
2082        return null;
2083    }
2084
2085    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2086            int userId) {
2087        if (!sUserManager.exists(userId)) return null;
2088        PackageSetting ps = mSettings.mPackages.get(packageName);
2089        if (ps != null) {
2090            PackageParser.Package pkg = ps.pkg;
2091            if (pkg == null) {
2092                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2093                    return null;
2094                }
2095                // Only data remains, so we aren't worried about code paths
2096                pkg = new PackageParser.Package(packageName);
2097                pkg.applicationInfo.packageName = packageName;
2098                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2099                pkg.applicationInfo.dataDir =
2100                        getDataPathForPackage(packageName, 0).getPath();
2101                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2102                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2103            }
2104            return generatePackageInfo(pkg, flags, userId);
2105        }
2106        return null;
2107    }
2108
2109    @Override
2110    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2111        if (!sUserManager.exists(userId)) return null;
2112        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2113        // writer
2114        synchronized (mPackages) {
2115            PackageParser.Package p = mPackages.get(packageName);
2116            if (DEBUG_PACKAGE_INFO) Log.v(
2117                    TAG, "getApplicationInfo " + packageName
2118                    + ": " + p);
2119            if (p != null) {
2120                PackageSetting ps = mSettings.mPackages.get(packageName);
2121                if (ps == null) return null;
2122                // Note: isEnabledLP() does not apply here - always return info
2123                return PackageParser.generateApplicationInfo(
2124                        p, flags, ps.readUserState(userId), userId);
2125            }
2126            if ("android".equals(packageName)||"system".equals(packageName)) {
2127                return mAndroidApplication;
2128            }
2129            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2130                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2131            }
2132        }
2133        return null;
2134    }
2135
2136
2137    @Override
2138    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2139        mContext.enforceCallingOrSelfPermission(
2140                android.Manifest.permission.CLEAR_APP_CACHE, null);
2141        // Queue up an async operation since clearing cache may take a little while.
2142        mHandler.post(new Runnable() {
2143            public void run() {
2144                mHandler.removeCallbacks(this);
2145                int retCode = -1;
2146                synchronized (mInstallLock) {
2147                    retCode = mInstaller.freeCache(freeStorageSize);
2148                    if (retCode < 0) {
2149                        Slog.w(TAG, "Couldn't clear application caches");
2150                    }
2151                }
2152                if (observer != null) {
2153                    try {
2154                        observer.onRemoveCompleted(null, (retCode >= 0));
2155                    } catch (RemoteException e) {
2156                        Slog.w(TAG, "RemoveException when invoking call back");
2157                    }
2158                }
2159            }
2160        });
2161    }
2162
2163    @Override
2164    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2165        mContext.enforceCallingOrSelfPermission(
2166                android.Manifest.permission.CLEAR_APP_CACHE, null);
2167        // Queue up an async operation since clearing cache may take a little while.
2168        mHandler.post(new Runnable() {
2169            public void run() {
2170                mHandler.removeCallbacks(this);
2171                int retCode = -1;
2172                synchronized (mInstallLock) {
2173                    retCode = mInstaller.freeCache(freeStorageSize);
2174                    if (retCode < 0) {
2175                        Slog.w(TAG, "Couldn't clear application caches");
2176                    }
2177                }
2178                if(pi != null) {
2179                    try {
2180                        // Callback via pending intent
2181                        int code = (retCode >= 0) ? 1 : 0;
2182                        pi.sendIntent(null, code, null,
2183                                null, null);
2184                    } catch (SendIntentException e1) {
2185                        Slog.i(TAG, "Failed to send pending intent");
2186                    }
2187                }
2188            }
2189        });
2190    }
2191
2192    void freeStorage(long freeStorageSize) throws IOException {
2193        synchronized (mInstallLock) {
2194            if (mInstaller.freeCache(freeStorageSize) < 0) {
2195                throw new IOException("Failed to free enough space");
2196            }
2197        }
2198    }
2199
2200    @Override
2201    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2202        if (!sUserManager.exists(userId)) return null;
2203        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2204        synchronized (mPackages) {
2205            PackageParser.Activity a = mActivities.mActivities.get(component);
2206
2207            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2208            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2209                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2210                if (ps == null) return null;
2211                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2212                        userId);
2213            }
2214            if (mResolveComponentName.equals(component)) {
2215                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2216                        new PackageUserState(), userId);
2217            }
2218        }
2219        return null;
2220    }
2221
2222    @Override
2223    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2224            String resolvedType) {
2225        synchronized (mPackages) {
2226            PackageParser.Activity a = mActivities.mActivities.get(component);
2227            if (a == null) {
2228                return false;
2229            }
2230            for (int i=0; i<a.intents.size(); i++) {
2231                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2232                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2233                    return true;
2234                }
2235            }
2236            return false;
2237        }
2238    }
2239
2240    @Override
2241    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2242        if (!sUserManager.exists(userId)) return null;
2243        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2244        synchronized (mPackages) {
2245            PackageParser.Activity a = mReceivers.mActivities.get(component);
2246            if (DEBUG_PACKAGE_INFO) Log.v(
2247                TAG, "getReceiverInfo " + component + ": " + a);
2248            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2249                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2250                if (ps == null) return null;
2251                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2252                        userId);
2253            }
2254        }
2255        return null;
2256    }
2257
2258    @Override
2259    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2260        if (!sUserManager.exists(userId)) return null;
2261        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2262        synchronized (mPackages) {
2263            PackageParser.Service s = mServices.mServices.get(component);
2264            if (DEBUG_PACKAGE_INFO) Log.v(
2265                TAG, "getServiceInfo " + component + ": " + s);
2266            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2267                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2268                if (ps == null) return null;
2269                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2270                        userId);
2271            }
2272        }
2273        return null;
2274    }
2275
2276    @Override
2277    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2278        if (!sUserManager.exists(userId)) return null;
2279        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2280        synchronized (mPackages) {
2281            PackageParser.Provider p = mProviders.mProviders.get(component);
2282            if (DEBUG_PACKAGE_INFO) Log.v(
2283                TAG, "getProviderInfo " + component + ": " + p);
2284            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2285                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2286                if (ps == null) return null;
2287                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2288                        userId);
2289            }
2290        }
2291        return null;
2292    }
2293
2294    @Override
2295    public String[] getSystemSharedLibraryNames() {
2296        Set<String> libSet;
2297        synchronized (mPackages) {
2298            libSet = mSharedLibraries.keySet();
2299            int size = libSet.size();
2300            if (size > 0) {
2301                String[] libs = new String[size];
2302                libSet.toArray(libs);
2303                return libs;
2304            }
2305        }
2306        return null;
2307    }
2308
2309    @Override
2310    public FeatureInfo[] getSystemAvailableFeatures() {
2311        Collection<FeatureInfo> featSet;
2312        synchronized (mPackages) {
2313            featSet = mAvailableFeatures.values();
2314            int size = featSet.size();
2315            if (size > 0) {
2316                FeatureInfo[] features = new FeatureInfo[size+1];
2317                featSet.toArray(features);
2318                FeatureInfo fi = new FeatureInfo();
2319                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2320                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2321                features[size] = fi;
2322                return features;
2323            }
2324        }
2325        return null;
2326    }
2327
2328    @Override
2329    public boolean hasSystemFeature(String name) {
2330        synchronized (mPackages) {
2331            return mAvailableFeatures.containsKey(name);
2332        }
2333    }
2334
2335    private void checkValidCaller(int uid, int userId) {
2336        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2337            return;
2338
2339        throw new SecurityException("Caller uid=" + uid
2340                + " is not privileged to communicate with user=" + userId);
2341    }
2342
2343    @Override
2344    public int checkPermission(String permName, String pkgName) {
2345        synchronized (mPackages) {
2346            PackageParser.Package p = mPackages.get(pkgName);
2347            if (p != null && p.mExtras != null) {
2348                PackageSetting ps = (PackageSetting)p.mExtras;
2349                if (ps.sharedUser != null) {
2350                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2351                        return PackageManager.PERMISSION_GRANTED;
2352                    }
2353                } else if (ps.grantedPermissions.contains(permName)) {
2354                    return PackageManager.PERMISSION_GRANTED;
2355                }
2356            }
2357        }
2358        return PackageManager.PERMISSION_DENIED;
2359    }
2360
2361    @Override
2362    public int checkUidPermission(String permName, int uid) {
2363        synchronized (mPackages) {
2364            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2365            if (obj != null) {
2366                GrantedPermissions gp = (GrantedPermissions)obj;
2367                if (gp.grantedPermissions.contains(permName)) {
2368                    return PackageManager.PERMISSION_GRANTED;
2369                }
2370            } else {
2371                HashSet<String> perms = mSystemPermissions.get(uid);
2372                if (perms != null && perms.contains(permName)) {
2373                    return PackageManager.PERMISSION_GRANTED;
2374                }
2375            }
2376        }
2377        return PackageManager.PERMISSION_DENIED;
2378    }
2379
2380    /**
2381     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2382     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2383     * @param checkShell TODO(yamasani):
2384     * @param message the message to log on security exception
2385     */
2386    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2387            boolean checkShell, String message) {
2388        if (userId < 0) {
2389            throw new IllegalArgumentException("Invalid userId " + userId);
2390        }
2391        if (checkShell) {
2392            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2393        }
2394        if (userId == UserHandle.getUserId(callingUid)) return;
2395        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2396            if (requireFullPermission) {
2397                mContext.enforceCallingOrSelfPermission(
2398                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2399            } else {
2400                try {
2401                    mContext.enforceCallingOrSelfPermission(
2402                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2403                } catch (SecurityException se) {
2404                    mContext.enforceCallingOrSelfPermission(
2405                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2406                }
2407            }
2408        }
2409    }
2410
2411    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2412        if (callingUid == Process.SHELL_UID) {
2413            if (userHandle >= 0
2414                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2415                throw new SecurityException("Shell does not have permission to access user "
2416                        + userHandle);
2417            } else if (userHandle < 0) {
2418                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2419                        + Debug.getCallers(3));
2420            }
2421        }
2422    }
2423
2424    private BasePermission findPermissionTreeLP(String permName) {
2425        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2426            if (permName.startsWith(bp.name) &&
2427                    permName.length() > bp.name.length() &&
2428                    permName.charAt(bp.name.length()) == '.') {
2429                return bp;
2430            }
2431        }
2432        return null;
2433    }
2434
2435    private BasePermission checkPermissionTreeLP(String permName) {
2436        if (permName != null) {
2437            BasePermission bp = findPermissionTreeLP(permName);
2438            if (bp != null) {
2439                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2440                    return bp;
2441                }
2442                throw new SecurityException("Calling uid "
2443                        + Binder.getCallingUid()
2444                        + " is not allowed to add to permission tree "
2445                        + bp.name + " owned by uid " + bp.uid);
2446            }
2447        }
2448        throw new SecurityException("No permission tree found for " + permName);
2449    }
2450
2451    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2452        if (s1 == null) {
2453            return s2 == null;
2454        }
2455        if (s2 == null) {
2456            return false;
2457        }
2458        if (s1.getClass() != s2.getClass()) {
2459            return false;
2460        }
2461        return s1.equals(s2);
2462    }
2463
2464    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2465        if (pi1.icon != pi2.icon) return false;
2466        if (pi1.logo != pi2.logo) return false;
2467        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2468        if (!compareStrings(pi1.name, pi2.name)) return false;
2469        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2470        // We'll take care of setting this one.
2471        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2472        // These are not currently stored in settings.
2473        //if (!compareStrings(pi1.group, pi2.group)) return false;
2474        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2475        //if (pi1.labelRes != pi2.labelRes) return false;
2476        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2477        return true;
2478    }
2479
2480    int permissionInfoFootprint(PermissionInfo info) {
2481        int size = info.name.length();
2482        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2483        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2484        return size;
2485    }
2486
2487    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2488        int size = 0;
2489        for (BasePermission perm : mSettings.mPermissions.values()) {
2490            if (perm.uid == tree.uid) {
2491                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2492            }
2493        }
2494        return size;
2495    }
2496
2497    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2498        // We calculate the max size of permissions defined by this uid and throw
2499        // if that plus the size of 'info' would exceed our stated maximum.
2500        if (tree.uid != Process.SYSTEM_UID) {
2501            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2502            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2503                throw new SecurityException("Permission tree size cap exceeded");
2504            }
2505        }
2506    }
2507
2508    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2509        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2510            throw new SecurityException("Label must be specified in permission");
2511        }
2512        BasePermission tree = checkPermissionTreeLP(info.name);
2513        BasePermission bp = mSettings.mPermissions.get(info.name);
2514        boolean added = bp == null;
2515        boolean changed = true;
2516        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2517        if (added) {
2518            enforcePermissionCapLocked(info, tree);
2519            bp = new BasePermission(info.name, tree.sourcePackage,
2520                    BasePermission.TYPE_DYNAMIC);
2521        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2522            throw new SecurityException(
2523                    "Not allowed to modify non-dynamic permission "
2524                    + info.name);
2525        } else {
2526            if (bp.protectionLevel == fixedLevel
2527                    && bp.perm.owner.equals(tree.perm.owner)
2528                    && bp.uid == tree.uid
2529                    && comparePermissionInfos(bp.perm.info, info)) {
2530                changed = false;
2531            }
2532        }
2533        bp.protectionLevel = fixedLevel;
2534        info = new PermissionInfo(info);
2535        info.protectionLevel = fixedLevel;
2536        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2537        bp.perm.info.packageName = tree.perm.info.packageName;
2538        bp.uid = tree.uid;
2539        if (added) {
2540            mSettings.mPermissions.put(info.name, bp);
2541        }
2542        if (changed) {
2543            if (!async) {
2544                mSettings.writeLPr();
2545            } else {
2546                scheduleWriteSettingsLocked();
2547            }
2548        }
2549        return added;
2550    }
2551
2552    @Override
2553    public boolean addPermission(PermissionInfo info) {
2554        synchronized (mPackages) {
2555            return addPermissionLocked(info, false);
2556        }
2557    }
2558
2559    @Override
2560    public boolean addPermissionAsync(PermissionInfo info) {
2561        synchronized (mPackages) {
2562            return addPermissionLocked(info, true);
2563        }
2564    }
2565
2566    @Override
2567    public void removePermission(String name) {
2568        synchronized (mPackages) {
2569            checkPermissionTreeLP(name);
2570            BasePermission bp = mSettings.mPermissions.get(name);
2571            if (bp != null) {
2572                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2573                    throw new SecurityException(
2574                            "Not allowed to modify non-dynamic permission "
2575                            + name);
2576                }
2577                mSettings.mPermissions.remove(name);
2578                mSettings.writeLPr();
2579            }
2580        }
2581    }
2582
2583    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2584        int index = pkg.requestedPermissions.indexOf(bp.name);
2585        if (index == -1) {
2586            throw new SecurityException("Package " + pkg.packageName
2587                    + " has not requested permission " + bp.name);
2588        }
2589        boolean isNormal =
2590                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2591                        == PermissionInfo.PROTECTION_NORMAL);
2592        boolean isDangerous =
2593                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2594                        == PermissionInfo.PROTECTION_DANGEROUS);
2595        boolean isDevelopment =
2596                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2597
2598        if (!isNormal && !isDangerous && !isDevelopment) {
2599            throw new SecurityException("Permission " + bp.name
2600                    + " is not a changeable permission type");
2601        }
2602
2603        if (isNormal || isDangerous) {
2604            if (pkg.requestedPermissionsRequired.get(index)) {
2605                throw new SecurityException("Can't change " + bp.name
2606                        + ". It is required by the application");
2607            }
2608        }
2609    }
2610
2611    @Override
2612    public void grantPermission(String packageName, String permissionName) {
2613        mContext.enforceCallingOrSelfPermission(
2614                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2615        synchronized (mPackages) {
2616            final PackageParser.Package pkg = mPackages.get(packageName);
2617            if (pkg == null) {
2618                throw new IllegalArgumentException("Unknown package: " + packageName);
2619            }
2620            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2621            if (bp == null) {
2622                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2623            }
2624
2625            checkGrantRevokePermissions(pkg, bp);
2626
2627            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2628            if (ps == null) {
2629                return;
2630            }
2631            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2632            if (gp.grantedPermissions.add(permissionName)) {
2633                if (ps.haveGids) {
2634                    gp.gids = appendInts(gp.gids, bp.gids);
2635                }
2636                mSettings.writeLPr();
2637            }
2638        }
2639    }
2640
2641    @Override
2642    public void revokePermission(String packageName, String permissionName) {
2643        int changedAppId = -1;
2644
2645        synchronized (mPackages) {
2646            final PackageParser.Package pkg = mPackages.get(packageName);
2647            if (pkg == null) {
2648                throw new IllegalArgumentException("Unknown package: " + packageName);
2649            }
2650            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2651                mContext.enforceCallingOrSelfPermission(
2652                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2653            }
2654            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2655            if (bp == null) {
2656                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2657            }
2658
2659            checkGrantRevokePermissions(pkg, bp);
2660
2661            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2662            if (ps == null) {
2663                return;
2664            }
2665            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2666            if (gp.grantedPermissions.remove(permissionName)) {
2667                gp.grantedPermissions.remove(permissionName);
2668                if (ps.haveGids) {
2669                    gp.gids = removeInts(gp.gids, bp.gids);
2670                }
2671                mSettings.writeLPr();
2672                changedAppId = ps.appId;
2673            }
2674        }
2675
2676        if (changedAppId >= 0) {
2677            // We changed the perm on someone, kill its processes.
2678            IActivityManager am = ActivityManagerNative.getDefault();
2679            if (am != null) {
2680                final int callingUserId = UserHandle.getCallingUserId();
2681                final long ident = Binder.clearCallingIdentity();
2682                try {
2683                    //XXX we should only revoke for the calling user's app permissions,
2684                    // but for now we impact all users.
2685                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2686                    //        "revoke " + permissionName);
2687                    int[] users = sUserManager.getUserIds();
2688                    for (int user : users) {
2689                        am.killUid(UserHandle.getUid(user, changedAppId),
2690                                "revoke " + permissionName);
2691                    }
2692                } catch (RemoteException e) {
2693                } finally {
2694                    Binder.restoreCallingIdentity(ident);
2695                }
2696            }
2697        }
2698    }
2699
2700    @Override
2701    public boolean isProtectedBroadcast(String actionName) {
2702        synchronized (mPackages) {
2703            return mProtectedBroadcasts.contains(actionName);
2704        }
2705    }
2706
2707    @Override
2708    public int checkSignatures(String pkg1, String pkg2) {
2709        synchronized (mPackages) {
2710            final PackageParser.Package p1 = mPackages.get(pkg1);
2711            final PackageParser.Package p2 = mPackages.get(pkg2);
2712            if (p1 == null || p1.mExtras == null
2713                    || p2 == null || p2.mExtras == null) {
2714                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2715            }
2716            return compareSignatures(p1.mSignatures, p2.mSignatures);
2717        }
2718    }
2719
2720    @Override
2721    public int checkUidSignatures(int uid1, int uid2) {
2722        // Map to base uids.
2723        uid1 = UserHandle.getAppId(uid1);
2724        uid2 = UserHandle.getAppId(uid2);
2725        // reader
2726        synchronized (mPackages) {
2727            Signature[] s1;
2728            Signature[] s2;
2729            Object obj = mSettings.getUserIdLPr(uid1);
2730            if (obj != null) {
2731                if (obj instanceof SharedUserSetting) {
2732                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2733                } else if (obj instanceof PackageSetting) {
2734                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2735                } else {
2736                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2737                }
2738            } else {
2739                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2740            }
2741            obj = mSettings.getUserIdLPr(uid2);
2742            if (obj != null) {
2743                if (obj instanceof SharedUserSetting) {
2744                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2745                } else if (obj instanceof PackageSetting) {
2746                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2747                } else {
2748                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2749                }
2750            } else {
2751                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2752            }
2753            return compareSignatures(s1, s2);
2754        }
2755    }
2756
2757    /**
2758     * Compares two sets of signatures. Returns:
2759     * <br />
2760     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2761     * <br />
2762     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2763     * <br />
2764     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2765     * <br />
2766     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2767     * <br />
2768     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2769     */
2770    static int compareSignatures(Signature[] s1, Signature[] s2) {
2771        if (s1 == null) {
2772            return s2 == null
2773                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2774                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2775        }
2776
2777        if (s2 == null) {
2778            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2779        }
2780
2781        if (s1.length != s2.length) {
2782            return PackageManager.SIGNATURE_NO_MATCH;
2783        }
2784
2785        // Since both signature sets are of size 1, we can compare without HashSets.
2786        if (s1.length == 1) {
2787            return s1[0].equals(s2[0]) ?
2788                    PackageManager.SIGNATURE_MATCH :
2789                    PackageManager.SIGNATURE_NO_MATCH;
2790        }
2791
2792        HashSet<Signature> set1 = new HashSet<Signature>();
2793        for (Signature sig : s1) {
2794            set1.add(sig);
2795        }
2796        HashSet<Signature> set2 = new HashSet<Signature>();
2797        for (Signature sig : s2) {
2798            set2.add(sig);
2799        }
2800        // Make sure s2 contains all signatures in s1.
2801        if (set1.equals(set2)) {
2802            return PackageManager.SIGNATURE_MATCH;
2803        }
2804        return PackageManager.SIGNATURE_NO_MATCH;
2805    }
2806
2807    /**
2808     * If the database version for this type of package (internal storage or
2809     * external storage) is less than the version where package signatures
2810     * were updated, return true.
2811     */
2812    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2813        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2814                DatabaseVersion.SIGNATURE_END_ENTITY))
2815                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2816                        DatabaseVersion.SIGNATURE_END_ENTITY));
2817    }
2818
2819    /**
2820     * Used for backward compatibility to make sure any packages with
2821     * certificate chains get upgraded to the new style. {@code existingSigs}
2822     * will be in the old format (since they were stored on disk from before the
2823     * system upgrade) and {@code scannedSigs} will be in the newer format.
2824     */
2825    private int compareSignaturesCompat(PackageSignatures existingSigs,
2826            PackageParser.Package scannedPkg) {
2827        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2828            return PackageManager.SIGNATURE_NO_MATCH;
2829        }
2830
2831        HashSet<Signature> existingSet = new HashSet<Signature>();
2832        for (Signature sig : existingSigs.mSignatures) {
2833            existingSet.add(sig);
2834        }
2835        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2836        for (Signature sig : scannedPkg.mSignatures) {
2837            try {
2838                Signature[] chainSignatures = sig.getChainSignatures();
2839                for (Signature chainSig : chainSignatures) {
2840                    scannedCompatSet.add(chainSig);
2841                }
2842            } catch (CertificateEncodingException e) {
2843                scannedCompatSet.add(sig);
2844            }
2845        }
2846        /*
2847         * Make sure the expanded scanned set contains all signatures in the
2848         * existing one.
2849         */
2850        if (scannedCompatSet.equals(existingSet)) {
2851            // Migrate the old signatures to the new scheme.
2852            existingSigs.assignSignatures(scannedPkg.mSignatures);
2853            // The new KeySets will be re-added later in the scanning process.
2854            synchronized (mPackages) {
2855                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2856            }
2857            return PackageManager.SIGNATURE_MATCH;
2858        }
2859        return PackageManager.SIGNATURE_NO_MATCH;
2860    }
2861
2862    @Override
2863    public String[] getPackagesForUid(int uid) {
2864        uid = UserHandle.getAppId(uid);
2865        // reader
2866        synchronized (mPackages) {
2867            Object obj = mSettings.getUserIdLPr(uid);
2868            if (obj instanceof SharedUserSetting) {
2869                final SharedUserSetting sus = (SharedUserSetting) obj;
2870                final int N = sus.packages.size();
2871                final String[] res = new String[N];
2872                final Iterator<PackageSetting> it = sus.packages.iterator();
2873                int i = 0;
2874                while (it.hasNext()) {
2875                    res[i++] = it.next().name;
2876                }
2877                return res;
2878            } else if (obj instanceof PackageSetting) {
2879                final PackageSetting ps = (PackageSetting) obj;
2880                return new String[] { ps.name };
2881            }
2882        }
2883        return null;
2884    }
2885
2886    @Override
2887    public String getNameForUid(int uid) {
2888        // reader
2889        synchronized (mPackages) {
2890            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2891            if (obj instanceof SharedUserSetting) {
2892                final SharedUserSetting sus = (SharedUserSetting) obj;
2893                return sus.name + ":" + sus.userId;
2894            } else if (obj instanceof PackageSetting) {
2895                final PackageSetting ps = (PackageSetting) obj;
2896                return ps.name;
2897            }
2898        }
2899        return null;
2900    }
2901
2902    @Override
2903    public int getUidForSharedUser(String sharedUserName) {
2904        if(sharedUserName == null) {
2905            return -1;
2906        }
2907        // reader
2908        synchronized (mPackages) {
2909            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2910            if (suid == null) {
2911                return -1;
2912            }
2913            return suid.userId;
2914        }
2915    }
2916
2917    @Override
2918    public int getFlagsForUid(int uid) {
2919        synchronized (mPackages) {
2920            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2921            if (obj instanceof SharedUserSetting) {
2922                final SharedUserSetting sus = (SharedUserSetting) obj;
2923                return sus.pkgFlags;
2924            } else if (obj instanceof PackageSetting) {
2925                final PackageSetting ps = (PackageSetting) obj;
2926                return ps.pkgFlags;
2927            }
2928        }
2929        return 0;
2930    }
2931
2932    @Override
2933    public String[] getAppOpPermissionPackages(String permissionName) {
2934        synchronized (mPackages) {
2935            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2936            if (pkgs == null) {
2937                return null;
2938            }
2939            return pkgs.toArray(new String[pkgs.size()]);
2940        }
2941    }
2942
2943    @Override
2944    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2945            int flags, int userId) {
2946        if (!sUserManager.exists(userId)) return null;
2947        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
2948        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2949        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2950    }
2951
2952    @Override
2953    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2954            IntentFilter filter, int match, ComponentName activity) {
2955        final int userId = UserHandle.getCallingUserId();
2956        if (DEBUG_PREFERRED) {
2957            Log.v(TAG, "setLastChosenActivity intent=" + intent
2958                + " resolvedType=" + resolvedType
2959                + " flags=" + flags
2960                + " filter=" + filter
2961                + " match=" + match
2962                + " activity=" + activity);
2963            filter.dump(new PrintStreamPrinter(System.out), "    ");
2964        }
2965        intent.setComponent(null);
2966        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2967        // Find any earlier preferred or last chosen entries and nuke them
2968        findPreferredActivity(intent, resolvedType,
2969                flags, query, 0, false, true, false, userId);
2970        // Add the new activity as the last chosen for this filter
2971        addPreferredActivityInternal(filter, match, null, activity, false, userId,
2972                "Setting last chosen");
2973    }
2974
2975    @Override
2976    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2977        final int userId = UserHandle.getCallingUserId();
2978        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2979        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2980        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2981                false, false, false, userId);
2982    }
2983
2984    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2985            int flags, List<ResolveInfo> query, int userId) {
2986        if (query != null) {
2987            final int N = query.size();
2988            if (N == 1) {
2989                return query.get(0);
2990            } else if (N > 1) {
2991                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2992                // If there is more than one activity with the same priority,
2993                // then let the user decide between them.
2994                ResolveInfo r0 = query.get(0);
2995                ResolveInfo r1 = query.get(1);
2996                if (DEBUG_INTENT_MATCHING || debug) {
2997                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2998                            + r1.activityInfo.name + "=" + r1.priority);
2999                }
3000                // If the first activity has a higher priority, or a different
3001                // default, then it is always desireable to pick it.
3002                if (r0.priority != r1.priority
3003                        || r0.preferredOrder != r1.preferredOrder
3004                        || r0.isDefault != r1.isDefault) {
3005                    return query.get(0);
3006                }
3007                // If we have saved a preference for a preferred activity for
3008                // this Intent, use that.
3009                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3010                        flags, query, r0.priority, true, false, debug, userId);
3011                if (ri != null) {
3012                    return ri;
3013                }
3014                if (userId != 0) {
3015                    ri = new ResolveInfo(mResolveInfo);
3016                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3017                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3018                            ri.activityInfo.applicationInfo);
3019                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3020                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3021                    return ri;
3022                }
3023                return mResolveInfo;
3024            }
3025        }
3026        return null;
3027    }
3028
3029    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3030            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3031        final int N = query.size();
3032        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3033                .get(userId);
3034        // Get the list of persistent preferred activities that handle the intent
3035        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3036        List<PersistentPreferredActivity> pprefs = ppir != null
3037                ? ppir.queryIntent(intent, resolvedType,
3038                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3039                : null;
3040        if (pprefs != null && pprefs.size() > 0) {
3041            final int M = pprefs.size();
3042            for (int i=0; i<M; i++) {
3043                final PersistentPreferredActivity ppa = pprefs.get(i);
3044                if (DEBUG_PREFERRED || debug) {
3045                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3046                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3047                            + "\n  component=" + ppa.mComponent);
3048                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3049                }
3050                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3051                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3052                if (DEBUG_PREFERRED || debug) {
3053                    Slog.v(TAG, "Found persistent preferred activity:");
3054                    if (ai != null) {
3055                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3056                    } else {
3057                        Slog.v(TAG, "  null");
3058                    }
3059                }
3060                if (ai == null) {
3061                    // This previously registered persistent preferred activity
3062                    // component is no longer known. Ignore it and do NOT remove it.
3063                    continue;
3064                }
3065                for (int j=0; j<N; j++) {
3066                    final ResolveInfo ri = query.get(j);
3067                    if (!ri.activityInfo.applicationInfo.packageName
3068                            .equals(ai.applicationInfo.packageName)) {
3069                        continue;
3070                    }
3071                    if (!ri.activityInfo.name.equals(ai.name)) {
3072                        continue;
3073                    }
3074                    //  Found a persistent preference that can handle the intent.
3075                    if (DEBUG_PREFERRED || debug) {
3076                        Slog.v(TAG, "Returning persistent preferred activity: " +
3077                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3078                    }
3079                    return ri;
3080                }
3081            }
3082        }
3083        return null;
3084    }
3085
3086    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3087            List<ResolveInfo> query, int priority, boolean always,
3088            boolean removeMatches, boolean debug, int userId) {
3089        if (!sUserManager.exists(userId)) return null;
3090        // writer
3091        synchronized (mPackages) {
3092            if (intent.getSelector() != null) {
3093                intent = intent.getSelector();
3094            }
3095            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3096
3097            // Try to find a matching persistent preferred activity.
3098            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3099                    debug, userId);
3100
3101            // If a persistent preferred activity matched, use it.
3102            if (pri != null) {
3103                return pri;
3104            }
3105
3106            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3107            // Get the list of preferred activities that handle the intent
3108            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3109            List<PreferredActivity> prefs = pir != null
3110                    ? pir.queryIntent(intent, resolvedType,
3111                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3112                    : null;
3113            if (prefs != null && prefs.size() > 0) {
3114                boolean changed = false;
3115                try {
3116                    // First figure out how good the original match set is.
3117                    // We will only allow preferred activities that came
3118                    // from the same match quality.
3119                    int match = 0;
3120
3121                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3122
3123                    final int N = query.size();
3124                    for (int j=0; j<N; j++) {
3125                        final ResolveInfo ri = query.get(j);
3126                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3127                                + ": 0x" + Integer.toHexString(match));
3128                        if (ri.match > match) {
3129                            match = ri.match;
3130                        }
3131                    }
3132
3133                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3134                            + Integer.toHexString(match));
3135
3136                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3137                    final int M = prefs.size();
3138                    for (int i=0; i<M; i++) {
3139                        final PreferredActivity pa = prefs.get(i);
3140                        if (DEBUG_PREFERRED || debug) {
3141                            Slog.v(TAG, "Checking PreferredActivity ds="
3142                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3143                                    + "\n  component=" + pa.mPref.mComponent);
3144                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3145                        }
3146                        if (pa.mPref.mMatch != match) {
3147                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3148                                    + Integer.toHexString(pa.mPref.mMatch));
3149                            continue;
3150                        }
3151                        // If it's not an "always" type preferred activity and that's what we're
3152                        // looking for, skip it.
3153                        if (always && !pa.mPref.mAlways) {
3154                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3155                            continue;
3156                        }
3157                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3158                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3159                        if (DEBUG_PREFERRED || debug) {
3160                            Slog.v(TAG, "Found preferred activity:");
3161                            if (ai != null) {
3162                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3163                            } else {
3164                                Slog.v(TAG, "  null");
3165                            }
3166                        }
3167                        if (ai == null) {
3168                            // This previously registered preferred activity
3169                            // component is no longer known.  Most likely an update
3170                            // to the app was installed and in the new version this
3171                            // component no longer exists.  Clean it up by removing
3172                            // it from the preferred activities list, and skip it.
3173                            Slog.w(TAG, "Removing dangling preferred activity: "
3174                                    + pa.mPref.mComponent);
3175                            pir.removeFilter(pa);
3176                            changed = true;
3177                            continue;
3178                        }
3179                        for (int j=0; j<N; j++) {
3180                            final ResolveInfo ri = query.get(j);
3181                            if (!ri.activityInfo.applicationInfo.packageName
3182                                    .equals(ai.applicationInfo.packageName)) {
3183                                continue;
3184                            }
3185                            if (!ri.activityInfo.name.equals(ai.name)) {
3186                                continue;
3187                            }
3188
3189                            if (removeMatches) {
3190                                pir.removeFilter(pa);
3191                                changed = true;
3192                                if (DEBUG_PREFERRED) {
3193                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3194                                }
3195                                break;
3196                            }
3197
3198                            // Okay we found a previously set preferred or last chosen app.
3199                            // If the result set is different from when this
3200                            // was created, we need to clear it and re-ask the
3201                            // user their preference, if we're looking for an "always" type entry.
3202                            if (always && !pa.mPref.sameSet(query, priority)) {
3203                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3204                                        + intent + " type " + resolvedType);
3205                                if (DEBUG_PREFERRED) {
3206                                    Slog.v(TAG, "Removing preferred activity since set changed "
3207                                            + pa.mPref.mComponent);
3208                                }
3209                                pir.removeFilter(pa);
3210                                // Re-add the filter as a "last chosen" entry (!always)
3211                                PreferredActivity lastChosen = new PreferredActivity(
3212                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3213                                pir.addFilter(lastChosen);
3214                                changed = true;
3215                                return null;
3216                            }
3217
3218                            // Yay! Either the set matched or we're looking for the last chosen
3219                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3220                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3221                            return ri;
3222                        }
3223                    }
3224                } finally {
3225                    if (changed) {
3226                        if (DEBUG_PREFERRED) {
3227                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3228                        }
3229                        mSettings.writePackageRestrictionsLPr(userId);
3230                    }
3231                }
3232            }
3233        }
3234        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3235        return null;
3236    }
3237
3238    /*
3239     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3240     */
3241    @Override
3242    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3243            int targetUserId) {
3244        mContext.enforceCallingOrSelfPermission(
3245                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3246        List<CrossProfileIntentFilter> matches =
3247                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3248        if (matches != null) {
3249            int size = matches.size();
3250            for (int i = 0; i < size; i++) {
3251                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3252            }
3253        }
3254        return false;
3255    }
3256
3257    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3258            String resolvedType, int userId) {
3259        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3260        if (resolver != null) {
3261            return resolver.queryIntent(intent, resolvedType, false, userId);
3262        }
3263        return null;
3264    }
3265
3266    @Override
3267    public List<ResolveInfo> queryIntentActivities(Intent intent,
3268            String resolvedType, int flags, int userId) {
3269        if (!sUserManager.exists(userId)) return Collections.emptyList();
3270        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3271        ComponentName comp = intent.getComponent();
3272        if (comp == null) {
3273            if (intent.getSelector() != null) {
3274                intent = intent.getSelector();
3275                comp = intent.getComponent();
3276            }
3277        }
3278
3279        if (comp != null) {
3280            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3281            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3282            if (ai != null) {
3283                final ResolveInfo ri = new ResolveInfo();
3284                ri.activityInfo = ai;
3285                list.add(ri);
3286            }
3287            return list;
3288        }
3289
3290        // reader
3291        synchronized (mPackages) {
3292            final String pkgName = intent.getPackage();
3293            if (pkgName == null) {
3294                List<CrossProfileIntentFilter> matchingFilters =
3295                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3296                // Check for results that need to skip the current profile.
3297                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3298                        resolvedType, flags, userId);
3299                if (resolveInfo != null) {
3300                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3301                    result.add(resolveInfo);
3302                    return result;
3303                }
3304                // Check for cross profile results.
3305                resolveInfo = queryCrossProfileIntents(
3306                        matchingFilters, intent, resolvedType, flags, userId);
3307
3308                // Check for results in the current profile.
3309                List<ResolveInfo> result = mActivities.queryIntent(
3310                        intent, resolvedType, flags, userId);
3311                if (resolveInfo != null) {
3312                    result.add(resolveInfo);
3313                    Collections.sort(result, mResolvePrioritySorter);
3314                }
3315                return result;
3316            }
3317            final PackageParser.Package pkg = mPackages.get(pkgName);
3318            if (pkg != null) {
3319                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3320                        pkg.activities, userId);
3321            }
3322            return new ArrayList<ResolveInfo>();
3323        }
3324    }
3325
3326    private ResolveInfo querySkipCurrentProfileIntents(
3327            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3328            int flags, int sourceUserId) {
3329        if (matchingFilters != null) {
3330            int size = matchingFilters.size();
3331            for (int i = 0; i < size; i ++) {
3332                CrossProfileIntentFilter filter = matchingFilters.get(i);
3333                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3334                    // Checking if there are activities in the target user that can handle the
3335                    // intent.
3336                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3337                            flags, sourceUserId);
3338                    if (resolveInfo != null) {
3339                        return resolveInfo;
3340                    }
3341                }
3342            }
3343        }
3344        return null;
3345    }
3346
3347    // Return matching ResolveInfo if any for skip current profile intent filters.
3348    private ResolveInfo queryCrossProfileIntents(
3349            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3350            int flags, int sourceUserId) {
3351        if (matchingFilters != null) {
3352            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3353            // match the same intent. For performance reasons, it is better not to
3354            // run queryIntent twice for the same userId
3355            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3356            int size = matchingFilters.size();
3357            for (int i = 0; i < size; i++) {
3358                CrossProfileIntentFilter filter = matchingFilters.get(i);
3359                int targetUserId = filter.getTargetUserId();
3360                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3361                        && !alreadyTriedUserIds.get(targetUserId)) {
3362                    // Checking if there are activities in the target user that can handle the
3363                    // intent.
3364                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3365                            flags, sourceUserId);
3366                    if (resolveInfo != null) return resolveInfo;
3367                    alreadyTriedUserIds.put(targetUserId, true);
3368                }
3369            }
3370        }
3371        return null;
3372    }
3373
3374    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3375            String resolvedType, int flags, int sourceUserId) {
3376        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3377                resolvedType, flags, filter.getTargetUserId());
3378        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3379            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3380        }
3381        return null;
3382    }
3383
3384    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3385            int sourceUserId, int targetUserId) {
3386        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3387        String className;
3388        if (targetUserId == UserHandle.USER_OWNER) {
3389            className = FORWARD_INTENT_TO_USER_OWNER;
3390        } else {
3391            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3392        }
3393        ComponentName forwardingActivityComponentName = new ComponentName(
3394                mAndroidApplication.packageName, className);
3395        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3396                sourceUserId);
3397        if (targetUserId == UserHandle.USER_OWNER) {
3398            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3399            forwardingResolveInfo.noResourceId = true;
3400        }
3401        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3402        forwardingResolveInfo.priority = 0;
3403        forwardingResolveInfo.preferredOrder = 0;
3404        forwardingResolveInfo.match = 0;
3405        forwardingResolveInfo.isDefault = true;
3406        forwardingResolveInfo.filter = filter;
3407        forwardingResolveInfo.targetUserId = targetUserId;
3408        return forwardingResolveInfo;
3409    }
3410
3411    @Override
3412    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3413            Intent[] specifics, String[] specificTypes, Intent intent,
3414            String resolvedType, int flags, int userId) {
3415        if (!sUserManager.exists(userId)) return Collections.emptyList();
3416        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3417                false, "query intent activity options");
3418        final String resultsAction = intent.getAction();
3419
3420        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3421                | PackageManager.GET_RESOLVED_FILTER, userId);
3422
3423        if (DEBUG_INTENT_MATCHING) {
3424            Log.v(TAG, "Query " + intent + ": " + results);
3425        }
3426
3427        int specificsPos = 0;
3428        int N;
3429
3430        // todo: note that the algorithm used here is O(N^2).  This
3431        // isn't a problem in our current environment, but if we start running
3432        // into situations where we have more than 5 or 10 matches then this
3433        // should probably be changed to something smarter...
3434
3435        // First we go through and resolve each of the specific items
3436        // that were supplied, taking care of removing any corresponding
3437        // duplicate items in the generic resolve list.
3438        if (specifics != null) {
3439            for (int i=0; i<specifics.length; i++) {
3440                final Intent sintent = specifics[i];
3441                if (sintent == null) {
3442                    continue;
3443                }
3444
3445                if (DEBUG_INTENT_MATCHING) {
3446                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3447                }
3448
3449                String action = sintent.getAction();
3450                if (resultsAction != null && resultsAction.equals(action)) {
3451                    // If this action was explicitly requested, then don't
3452                    // remove things that have it.
3453                    action = null;
3454                }
3455
3456                ResolveInfo ri = null;
3457                ActivityInfo ai = null;
3458
3459                ComponentName comp = sintent.getComponent();
3460                if (comp == null) {
3461                    ri = resolveIntent(
3462                        sintent,
3463                        specificTypes != null ? specificTypes[i] : null,
3464                            flags, userId);
3465                    if (ri == null) {
3466                        continue;
3467                    }
3468                    if (ri == mResolveInfo) {
3469                        // ACK!  Must do something better with this.
3470                    }
3471                    ai = ri.activityInfo;
3472                    comp = new ComponentName(ai.applicationInfo.packageName,
3473                            ai.name);
3474                } else {
3475                    ai = getActivityInfo(comp, flags, userId);
3476                    if (ai == null) {
3477                        continue;
3478                    }
3479                }
3480
3481                // Look for any generic query activities that are duplicates
3482                // of this specific one, and remove them from the results.
3483                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3484                N = results.size();
3485                int j;
3486                for (j=specificsPos; j<N; j++) {
3487                    ResolveInfo sri = results.get(j);
3488                    if ((sri.activityInfo.name.equals(comp.getClassName())
3489                            && sri.activityInfo.applicationInfo.packageName.equals(
3490                                    comp.getPackageName()))
3491                        || (action != null && sri.filter.matchAction(action))) {
3492                        results.remove(j);
3493                        if (DEBUG_INTENT_MATCHING) Log.v(
3494                            TAG, "Removing duplicate item from " + j
3495                            + " due to specific " + specificsPos);
3496                        if (ri == null) {
3497                            ri = sri;
3498                        }
3499                        j--;
3500                        N--;
3501                    }
3502                }
3503
3504                // Add this specific item to its proper place.
3505                if (ri == null) {
3506                    ri = new ResolveInfo();
3507                    ri.activityInfo = ai;
3508                }
3509                results.add(specificsPos, ri);
3510                ri.specificIndex = i;
3511                specificsPos++;
3512            }
3513        }
3514
3515        // Now we go through the remaining generic results and remove any
3516        // duplicate actions that are found here.
3517        N = results.size();
3518        for (int i=specificsPos; i<N-1; i++) {
3519            final ResolveInfo rii = results.get(i);
3520            if (rii.filter == null) {
3521                continue;
3522            }
3523
3524            // Iterate over all of the actions of this result's intent
3525            // filter...  typically this should be just one.
3526            final Iterator<String> it = rii.filter.actionsIterator();
3527            if (it == null) {
3528                continue;
3529            }
3530            while (it.hasNext()) {
3531                final String action = it.next();
3532                if (resultsAction != null && resultsAction.equals(action)) {
3533                    // If this action was explicitly requested, then don't
3534                    // remove things that have it.
3535                    continue;
3536                }
3537                for (int j=i+1; j<N; j++) {
3538                    final ResolveInfo rij = results.get(j);
3539                    if (rij.filter != null && rij.filter.hasAction(action)) {
3540                        results.remove(j);
3541                        if (DEBUG_INTENT_MATCHING) Log.v(
3542                            TAG, "Removing duplicate item from " + j
3543                            + " due to action " + action + " at " + i);
3544                        j--;
3545                        N--;
3546                    }
3547                }
3548            }
3549
3550            // If the caller didn't request filter information, drop it now
3551            // so we don't have to marshall/unmarshall it.
3552            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3553                rii.filter = null;
3554            }
3555        }
3556
3557        // Filter out the caller activity if so requested.
3558        if (caller != null) {
3559            N = results.size();
3560            for (int i=0; i<N; i++) {
3561                ActivityInfo ainfo = results.get(i).activityInfo;
3562                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3563                        && caller.getClassName().equals(ainfo.name)) {
3564                    results.remove(i);
3565                    break;
3566                }
3567            }
3568        }
3569
3570        // If the caller didn't request filter information,
3571        // drop them now so we don't have to
3572        // marshall/unmarshall it.
3573        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3574            N = results.size();
3575            for (int i=0; i<N; i++) {
3576                results.get(i).filter = null;
3577            }
3578        }
3579
3580        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3581        return results;
3582    }
3583
3584    @Override
3585    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3586            int userId) {
3587        if (!sUserManager.exists(userId)) return Collections.emptyList();
3588        ComponentName comp = intent.getComponent();
3589        if (comp == null) {
3590            if (intent.getSelector() != null) {
3591                intent = intent.getSelector();
3592                comp = intent.getComponent();
3593            }
3594        }
3595        if (comp != null) {
3596            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3597            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3598            if (ai != null) {
3599                ResolveInfo ri = new ResolveInfo();
3600                ri.activityInfo = ai;
3601                list.add(ri);
3602            }
3603            return list;
3604        }
3605
3606        // reader
3607        synchronized (mPackages) {
3608            String pkgName = intent.getPackage();
3609            if (pkgName == null) {
3610                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3611            }
3612            final PackageParser.Package pkg = mPackages.get(pkgName);
3613            if (pkg != null) {
3614                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3615                        userId);
3616            }
3617            return null;
3618        }
3619    }
3620
3621    @Override
3622    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3623        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3624        if (!sUserManager.exists(userId)) return null;
3625        if (query != null) {
3626            if (query.size() >= 1) {
3627                // If there is more than one service with the same priority,
3628                // just arbitrarily pick the first one.
3629                return query.get(0);
3630            }
3631        }
3632        return null;
3633    }
3634
3635    @Override
3636    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3637            int userId) {
3638        if (!sUserManager.exists(userId)) return Collections.emptyList();
3639        ComponentName comp = intent.getComponent();
3640        if (comp == null) {
3641            if (intent.getSelector() != null) {
3642                intent = intent.getSelector();
3643                comp = intent.getComponent();
3644            }
3645        }
3646        if (comp != null) {
3647            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3648            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3649            if (si != null) {
3650                final ResolveInfo ri = new ResolveInfo();
3651                ri.serviceInfo = si;
3652                list.add(ri);
3653            }
3654            return list;
3655        }
3656
3657        // reader
3658        synchronized (mPackages) {
3659            String pkgName = intent.getPackage();
3660            if (pkgName == null) {
3661                return mServices.queryIntent(intent, resolvedType, flags, userId);
3662            }
3663            final PackageParser.Package pkg = mPackages.get(pkgName);
3664            if (pkg != null) {
3665                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3666                        userId);
3667            }
3668            return null;
3669        }
3670    }
3671
3672    @Override
3673    public List<ResolveInfo> queryIntentContentProviders(
3674            Intent intent, String resolvedType, int flags, int userId) {
3675        if (!sUserManager.exists(userId)) return Collections.emptyList();
3676        ComponentName comp = intent.getComponent();
3677        if (comp == null) {
3678            if (intent.getSelector() != null) {
3679                intent = intent.getSelector();
3680                comp = intent.getComponent();
3681            }
3682        }
3683        if (comp != null) {
3684            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3685            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3686            if (pi != null) {
3687                final ResolveInfo ri = new ResolveInfo();
3688                ri.providerInfo = pi;
3689                list.add(ri);
3690            }
3691            return list;
3692        }
3693
3694        // reader
3695        synchronized (mPackages) {
3696            String pkgName = intent.getPackage();
3697            if (pkgName == null) {
3698                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3699            }
3700            final PackageParser.Package pkg = mPackages.get(pkgName);
3701            if (pkg != null) {
3702                return mProviders.queryIntentForPackage(
3703                        intent, resolvedType, flags, pkg.providers, userId);
3704            }
3705            return null;
3706        }
3707    }
3708
3709    @Override
3710    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3711        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3712
3713        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3714
3715        // writer
3716        synchronized (mPackages) {
3717            ArrayList<PackageInfo> list;
3718            if (listUninstalled) {
3719                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3720                for (PackageSetting ps : mSettings.mPackages.values()) {
3721                    PackageInfo pi;
3722                    if (ps.pkg != null) {
3723                        pi = generatePackageInfo(ps.pkg, flags, userId);
3724                    } else {
3725                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3726                    }
3727                    if (pi != null) {
3728                        list.add(pi);
3729                    }
3730                }
3731            } else {
3732                list = new ArrayList<PackageInfo>(mPackages.size());
3733                for (PackageParser.Package p : mPackages.values()) {
3734                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3735                    if (pi != null) {
3736                        list.add(pi);
3737                    }
3738                }
3739            }
3740
3741            return new ParceledListSlice<PackageInfo>(list);
3742        }
3743    }
3744
3745    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3746            String[] permissions, boolean[] tmp, int flags, int userId) {
3747        int numMatch = 0;
3748        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3749        for (int i=0; i<permissions.length; i++) {
3750            if (gp.grantedPermissions.contains(permissions[i])) {
3751                tmp[i] = true;
3752                numMatch++;
3753            } else {
3754                tmp[i] = false;
3755            }
3756        }
3757        if (numMatch == 0) {
3758            return;
3759        }
3760        PackageInfo pi;
3761        if (ps.pkg != null) {
3762            pi = generatePackageInfo(ps.pkg, flags, userId);
3763        } else {
3764            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3765        }
3766        // The above might return null in cases of uninstalled apps or install-state
3767        // skew across users/profiles.
3768        if (pi != null) {
3769            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3770                if (numMatch == permissions.length) {
3771                    pi.requestedPermissions = permissions;
3772                } else {
3773                    pi.requestedPermissions = new String[numMatch];
3774                    numMatch = 0;
3775                    for (int i=0; i<permissions.length; i++) {
3776                        if (tmp[i]) {
3777                            pi.requestedPermissions[numMatch] = permissions[i];
3778                            numMatch++;
3779                        }
3780                    }
3781                }
3782            }
3783            list.add(pi);
3784        }
3785    }
3786
3787    @Override
3788    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3789            String[] permissions, int flags, int userId) {
3790        if (!sUserManager.exists(userId)) return null;
3791        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3792
3793        // writer
3794        synchronized (mPackages) {
3795            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3796            boolean[] tmpBools = new boolean[permissions.length];
3797            if (listUninstalled) {
3798                for (PackageSetting ps : mSettings.mPackages.values()) {
3799                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3800                }
3801            } else {
3802                for (PackageParser.Package pkg : mPackages.values()) {
3803                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3804                    if (ps != null) {
3805                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3806                                userId);
3807                    }
3808                }
3809            }
3810
3811            return new ParceledListSlice<PackageInfo>(list);
3812        }
3813    }
3814
3815    @Override
3816    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3817        if (!sUserManager.exists(userId)) return null;
3818        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3819
3820        // writer
3821        synchronized (mPackages) {
3822            ArrayList<ApplicationInfo> list;
3823            if (listUninstalled) {
3824                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3825                for (PackageSetting ps : mSettings.mPackages.values()) {
3826                    ApplicationInfo ai;
3827                    if (ps.pkg != null) {
3828                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3829                                ps.readUserState(userId), userId);
3830                    } else {
3831                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3832                    }
3833                    if (ai != null) {
3834                        list.add(ai);
3835                    }
3836                }
3837            } else {
3838                list = new ArrayList<ApplicationInfo>(mPackages.size());
3839                for (PackageParser.Package p : mPackages.values()) {
3840                    if (p.mExtras != null) {
3841                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3842                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3843                        if (ai != null) {
3844                            list.add(ai);
3845                        }
3846                    }
3847                }
3848            }
3849
3850            return new ParceledListSlice<ApplicationInfo>(list);
3851        }
3852    }
3853
3854    public List<ApplicationInfo> getPersistentApplications(int flags) {
3855        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3856
3857        // reader
3858        synchronized (mPackages) {
3859            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3860            final int userId = UserHandle.getCallingUserId();
3861            while (i.hasNext()) {
3862                final PackageParser.Package p = i.next();
3863                if (p.applicationInfo != null
3864                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3865                        && (!mSafeMode || isSystemApp(p))) {
3866                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3867                    if (ps != null) {
3868                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3869                                ps.readUserState(userId), userId);
3870                        if (ai != null) {
3871                            finalList.add(ai);
3872                        }
3873                    }
3874                }
3875            }
3876        }
3877
3878        return finalList;
3879    }
3880
3881    @Override
3882    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3883        if (!sUserManager.exists(userId)) return null;
3884        // reader
3885        synchronized (mPackages) {
3886            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3887            PackageSetting ps = provider != null
3888                    ? mSettings.mPackages.get(provider.owner.packageName)
3889                    : null;
3890            return ps != null
3891                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3892                    && (!mSafeMode || (provider.info.applicationInfo.flags
3893                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3894                    ? PackageParser.generateProviderInfo(provider, flags,
3895                            ps.readUserState(userId), userId)
3896                    : null;
3897        }
3898    }
3899
3900    /**
3901     * @deprecated
3902     */
3903    @Deprecated
3904    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3905        // reader
3906        synchronized (mPackages) {
3907            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3908                    .entrySet().iterator();
3909            final int userId = UserHandle.getCallingUserId();
3910            while (i.hasNext()) {
3911                Map.Entry<String, PackageParser.Provider> entry = i.next();
3912                PackageParser.Provider p = entry.getValue();
3913                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3914
3915                if (ps != null && p.syncable
3916                        && (!mSafeMode || (p.info.applicationInfo.flags
3917                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3918                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3919                            ps.readUserState(userId), userId);
3920                    if (info != null) {
3921                        outNames.add(entry.getKey());
3922                        outInfo.add(info);
3923                    }
3924                }
3925            }
3926        }
3927    }
3928
3929    @Override
3930    public List<ProviderInfo> queryContentProviders(String processName,
3931            int uid, int flags) {
3932        ArrayList<ProviderInfo> finalList = null;
3933        // reader
3934        synchronized (mPackages) {
3935            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3936            final int userId = processName != null ?
3937                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3938            while (i.hasNext()) {
3939                final PackageParser.Provider p = i.next();
3940                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3941                if (ps != null && p.info.authority != null
3942                        && (processName == null
3943                                || (p.info.processName.equals(processName)
3944                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3945                        && mSettings.isEnabledLPr(p.info, flags, userId)
3946                        && (!mSafeMode
3947                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3948                    if (finalList == null) {
3949                        finalList = new ArrayList<ProviderInfo>(3);
3950                    }
3951                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3952                            ps.readUserState(userId), userId);
3953                    if (info != null) {
3954                        finalList.add(info);
3955                    }
3956                }
3957            }
3958        }
3959
3960        if (finalList != null) {
3961            Collections.sort(finalList, mProviderInitOrderSorter);
3962        }
3963
3964        return finalList;
3965    }
3966
3967    @Override
3968    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3969            int flags) {
3970        // reader
3971        synchronized (mPackages) {
3972            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3973            return PackageParser.generateInstrumentationInfo(i, flags);
3974        }
3975    }
3976
3977    @Override
3978    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3979            int flags) {
3980        ArrayList<InstrumentationInfo> finalList =
3981            new ArrayList<InstrumentationInfo>();
3982
3983        // reader
3984        synchronized (mPackages) {
3985            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3986            while (i.hasNext()) {
3987                final PackageParser.Instrumentation p = i.next();
3988                if (targetPackage == null
3989                        || targetPackage.equals(p.info.targetPackage)) {
3990                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3991                            flags);
3992                    if (ii != null) {
3993                        finalList.add(ii);
3994                    }
3995                }
3996            }
3997        }
3998
3999        return finalList;
4000    }
4001
4002    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4003        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4004        if (overlays == null) {
4005            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4006            return;
4007        }
4008        for (PackageParser.Package opkg : overlays.values()) {
4009            // Not much to do if idmap fails: we already logged the error
4010            // and we certainly don't want to abort installation of pkg simply
4011            // because an overlay didn't fit properly. For these reasons,
4012            // ignore the return value of createIdmapForPackagePairLI.
4013            createIdmapForPackagePairLI(pkg, opkg);
4014        }
4015    }
4016
4017    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4018            PackageParser.Package opkg) {
4019        if (!opkg.mTrustedOverlay) {
4020            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4021                    opkg.baseCodePath + ": overlay not trusted");
4022            return false;
4023        }
4024        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4025        if (overlaySet == null) {
4026            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4027                    opkg.baseCodePath + " but target package has no known overlays");
4028            return false;
4029        }
4030        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4031        // TODO: generate idmap for split APKs
4032        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4033            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4034                    + opkg.baseCodePath);
4035            return false;
4036        }
4037        PackageParser.Package[] overlayArray =
4038            overlaySet.values().toArray(new PackageParser.Package[0]);
4039        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4040            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4041                return p1.mOverlayPriority - p2.mOverlayPriority;
4042            }
4043        };
4044        Arrays.sort(overlayArray, cmp);
4045
4046        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4047        int i = 0;
4048        for (PackageParser.Package p : overlayArray) {
4049            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4050        }
4051        return true;
4052    }
4053
4054    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4055        final File[] files = dir.listFiles();
4056        if (ArrayUtils.isEmpty(files)) {
4057            Log.d(TAG, "No files in app dir " + dir);
4058            return;
4059        }
4060
4061        if (DEBUG_PACKAGE_SCANNING) {
4062            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4063                    + " flags=0x" + Integer.toHexString(parseFlags));
4064        }
4065
4066        for (File file : files) {
4067            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4068                    && !PackageInstallerService.isStageName(file.getName());
4069            if (!isPackage) {
4070                // Ignore entries which are not packages
4071                continue;
4072            }
4073            try {
4074                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4075                        scanFlags, currentTime, null);
4076            } catch (PackageManagerException e) {
4077                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4078
4079                // Delete invalid userdata apps
4080                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4081                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4082                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4083                    if (file.isDirectory()) {
4084                        FileUtils.deleteContents(file);
4085                    }
4086                    file.delete();
4087                }
4088            }
4089        }
4090    }
4091
4092    private static File getSettingsProblemFile() {
4093        File dataDir = Environment.getDataDirectory();
4094        File systemDir = new File(dataDir, "system");
4095        File fname = new File(systemDir, "uiderrors.txt");
4096        return fname;
4097    }
4098
4099    static void reportSettingsProblem(int priority, String msg) {
4100        logCriticalInfo(priority, msg);
4101    }
4102
4103    static void logCriticalInfo(int priority, String msg) {
4104        Slog.println(priority, TAG, msg);
4105        EventLogTags.writePmCriticalInfo(msg);
4106        try {
4107            File fname = getSettingsProblemFile();
4108            FileOutputStream out = new FileOutputStream(fname, true);
4109            PrintWriter pw = new FastPrintWriter(out);
4110            SimpleDateFormat formatter = new SimpleDateFormat();
4111            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4112            pw.println(dateString + ": " + msg);
4113            pw.close();
4114            FileUtils.setPermissions(
4115                    fname.toString(),
4116                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4117                    -1, -1);
4118        } catch (java.io.IOException e) {
4119        }
4120    }
4121
4122    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4123            PackageParser.Package pkg, File srcFile, int parseFlags)
4124            throws PackageManagerException {
4125        if (ps != null
4126                && ps.codePath.equals(srcFile)
4127                && ps.timeStamp == srcFile.lastModified()
4128                && !isCompatSignatureUpdateNeeded(pkg)) {
4129            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4130            if (ps.signatures.mSignatures != null
4131                    && ps.signatures.mSignatures.length != 0
4132                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4133                // Optimization: reuse the existing cached certificates
4134                // if the package appears to be unchanged.
4135                pkg.mSignatures = ps.signatures.mSignatures;
4136                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4137                synchronized (mPackages) {
4138                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4139                }
4140                return;
4141            }
4142
4143            Slog.w(TAG, "PackageSetting for " + ps.name
4144                    + " is missing signatures.  Collecting certs again to recover them.");
4145        } else {
4146            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4147        }
4148
4149        try {
4150            pp.collectCertificates(pkg, parseFlags);
4151            pp.collectManifestDigest(pkg);
4152        } catch (PackageParserException e) {
4153            throw PackageManagerException.from(e);
4154        }
4155    }
4156
4157    /*
4158     *  Scan a package and return the newly parsed package.
4159     *  Returns null in case of errors and the error code is stored in mLastScanError
4160     */
4161    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4162            long currentTime, UserHandle user) throws PackageManagerException {
4163        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4164        parseFlags |= mDefParseFlags;
4165        PackageParser pp = new PackageParser();
4166        pp.setSeparateProcesses(mSeparateProcesses);
4167        pp.setOnlyCoreApps(mOnlyCore);
4168        pp.setDisplayMetrics(mMetrics);
4169
4170        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4171            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4172        }
4173
4174        final PackageParser.Package pkg;
4175        try {
4176            pkg = pp.parsePackage(scanFile, parseFlags);
4177        } catch (PackageParserException e) {
4178            throw PackageManagerException.from(e);
4179        }
4180
4181        PackageSetting ps = null;
4182        PackageSetting updatedPkg;
4183        // reader
4184        synchronized (mPackages) {
4185            // Look to see if we already know about this package.
4186            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4187            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4188                // This package has been renamed to its original name.  Let's
4189                // use that.
4190                ps = mSettings.peekPackageLPr(oldName);
4191            }
4192            // If there was no original package, see one for the real package name.
4193            if (ps == null) {
4194                ps = mSettings.peekPackageLPr(pkg.packageName);
4195            }
4196            // Check to see if this package could be hiding/updating a system
4197            // package.  Must look for it either under the original or real
4198            // package name depending on our state.
4199            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4200            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4201        }
4202        boolean updatedPkgBetter = false;
4203        // First check if this is a system package that may involve an update
4204        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4205            if (ps != null && !ps.codePath.equals(scanFile)) {
4206                // The path has changed from what was last scanned...  check the
4207                // version of the new path against what we have stored to determine
4208                // what to do.
4209                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4210                if (pkg.mVersionCode < ps.versionCode) {
4211                    // The system package has been updated and the code path does not match
4212                    // Ignore entry. Skip it.
4213                    logCriticalInfo(Log.INFO, "Package " + ps.name + " at " + scanFile
4214                            + " ignored: updated version " + ps.versionCode
4215                            + " better than this " + pkg.mVersionCode);
4216                    if (!updatedPkg.codePath.equals(scanFile)) {
4217                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4218                                + ps.name + " changing from " + updatedPkg.codePathString
4219                                + " to " + scanFile);
4220                        updatedPkg.codePath = scanFile;
4221                        updatedPkg.codePathString = scanFile.toString();
4222                        // This is the point at which we know that the system-disk APK
4223                        // for this package has moved during a reboot (e.g. due to an OTA),
4224                        // so we need to reevaluate it for privilege policy.
4225                        if (locationIsPrivileged(scanFile)) {
4226                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4227                        }
4228                    }
4229                    updatedPkg.pkg = pkg;
4230                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4231                } else {
4232                    // The current app on the system partition is better than
4233                    // what we have updated to on the data partition; switch
4234                    // back to the system partition version.
4235                    // At this point, its safely assumed that package installation for
4236                    // apps in system partition will go through. If not there won't be a working
4237                    // version of the app
4238                    // writer
4239                    synchronized (mPackages) {
4240                        // Just remove the loaded entries from package lists.
4241                        mPackages.remove(ps.name);
4242                    }
4243
4244                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4245                            + " reverting from " + ps.codePathString
4246                            + ": new version " + pkg.mVersionCode
4247                            + " better than installed " + ps.versionCode);
4248
4249                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4250                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4251                            getAppDexInstructionSets(ps));
4252                    synchronized (mInstallLock) {
4253                        args.cleanUpResourcesLI();
4254                    }
4255                    synchronized (mPackages) {
4256                        mSettings.enableSystemPackageLPw(ps.name);
4257                    }
4258                    updatedPkgBetter = true;
4259                }
4260            }
4261        }
4262
4263        if (updatedPkg != null) {
4264            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4265            // initially
4266            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4267
4268            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4269            // flag set initially
4270            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4271                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4272            }
4273        }
4274
4275        // Verify certificates against what was last scanned
4276        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4277
4278        /*
4279         * A new system app appeared, but we already had a non-system one of the
4280         * same name installed earlier.
4281         */
4282        boolean shouldHideSystemApp = false;
4283        if (updatedPkg == null && ps != null
4284                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4285            /*
4286             * Check to make sure the signatures match first. If they don't,
4287             * wipe the installed application and its data.
4288             */
4289            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4290                    != PackageManager.SIGNATURE_MATCH) {
4291                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
4292                        + " signatures don't match existing userdata copy; removing");
4293                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4294                ps = null;
4295            } else {
4296                /*
4297                 * If the newly-added system app is an older version than the
4298                 * already installed version, hide it. It will be scanned later
4299                 * and re-added like an update.
4300                 */
4301                if (pkg.mVersionCode < ps.versionCode) {
4302                    shouldHideSystemApp = true;
4303                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
4304                            + " but new version " + pkg.mVersionCode + " better than installed "
4305                            + ps.versionCode + "; hiding system");
4306                } else {
4307                    /*
4308                     * The newly found system app is a newer version that the
4309                     * one previously installed. Simply remove the
4310                     * already-installed application and replace it with our own
4311                     * while keeping the application data.
4312                     */
4313                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4314                            + " reverting from " + ps.codePathString + ": new version "
4315                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
4316                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4317                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4318                            getAppDexInstructionSets(ps));
4319                    synchronized (mInstallLock) {
4320                        args.cleanUpResourcesLI();
4321                    }
4322                }
4323            }
4324        }
4325
4326        // The apk is forward locked (not public) if its code and resources
4327        // are kept in different files. (except for app in either system or
4328        // vendor path).
4329        // TODO grab this value from PackageSettings
4330        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4331            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4332                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4333            }
4334        }
4335
4336        // TODO: extend to support forward-locked splits
4337        String resourcePath = null;
4338        String baseResourcePath = null;
4339        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4340            if (ps != null && ps.resourcePathString != null) {
4341                resourcePath = ps.resourcePathString;
4342                baseResourcePath = ps.resourcePathString;
4343            } else {
4344                // Should not happen at all. Just log an error.
4345                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4346            }
4347        } else {
4348            resourcePath = pkg.codePath;
4349            baseResourcePath = pkg.baseCodePath;
4350        }
4351
4352        // Set application objects path explicitly.
4353        pkg.applicationInfo.setCodePath(pkg.codePath);
4354        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4355        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4356        pkg.applicationInfo.setResourcePath(resourcePath);
4357        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4358        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4359
4360        // Note that we invoke the following method only if we are about to unpack an application
4361        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4362                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4363
4364        /*
4365         * If the system app should be overridden by a previously installed
4366         * data, hide the system app now and let the /data/app scan pick it up
4367         * again.
4368         */
4369        if (shouldHideSystemApp) {
4370            synchronized (mPackages) {
4371                /*
4372                 * We have to grant systems permissions before we hide, because
4373                 * grantPermissions will assume the package update is trying to
4374                 * expand its permissions.
4375                 */
4376                grantPermissionsLPw(pkg, true, pkg.packageName);
4377                mSettings.disableSystemPackageLPw(pkg.packageName);
4378            }
4379        }
4380
4381        return scannedPkg;
4382    }
4383
4384    private static String fixProcessName(String defProcessName,
4385            String processName, int uid) {
4386        if (processName == null) {
4387            return defProcessName;
4388        }
4389        return processName;
4390    }
4391
4392    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4393            throws PackageManagerException {
4394        if (pkgSetting.signatures.mSignatures != null) {
4395            // Already existing package. Make sure signatures match
4396            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4397                    == PackageManager.SIGNATURE_MATCH;
4398            if (!match) {
4399                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4400                        == PackageManager.SIGNATURE_MATCH;
4401            }
4402            if (!match) {
4403                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4404                        + pkg.packageName + " signatures do not match the "
4405                        + "previously installed version; ignoring!");
4406            }
4407        }
4408
4409        // Check for shared user signatures
4410        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4411            // Already existing package. Make sure signatures match
4412            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4413                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4414            if (!match) {
4415                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4416                        == PackageManager.SIGNATURE_MATCH;
4417            }
4418            if (!match) {
4419                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4420                        "Package " + pkg.packageName
4421                        + " has no signatures that match those in shared user "
4422                        + pkgSetting.sharedUser.name + "; ignoring!");
4423            }
4424        }
4425    }
4426
4427    /**
4428     * Enforces that only the system UID or root's UID can call a method exposed
4429     * via Binder.
4430     *
4431     * @param message used as message if SecurityException is thrown
4432     * @throws SecurityException if the caller is not system or root
4433     */
4434    private static final void enforceSystemOrRoot(String message) {
4435        final int uid = Binder.getCallingUid();
4436        if (uid != Process.SYSTEM_UID && uid != 0) {
4437            throw new SecurityException(message);
4438        }
4439    }
4440
4441    @Override
4442    public void performBootDexOpt() {
4443        enforceSystemOrRoot("Only the system can request dexopt be performed");
4444
4445        final HashSet<PackageParser.Package> pkgs;
4446        synchronized (mPackages) {
4447            pkgs = mDeferredDexOpt;
4448            mDeferredDexOpt = null;
4449        }
4450
4451        if (pkgs != null) {
4452            // Filter out packages that aren't recently used.
4453            //
4454            // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4455            // should do a full dexopt.
4456            if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4457                // TODO: add a property to control this?
4458                long dexOptLRUThresholdInMinutes;
4459                if (mLazyDexOpt) {
4460                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4461                } else {
4462                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4463                }
4464                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4465
4466                int total = pkgs.size();
4467                int skipped = 0;
4468                long now = System.currentTimeMillis();
4469                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4470                    PackageParser.Package pkg = i.next();
4471                    long then = pkg.mLastPackageUsageTimeInMills;
4472                    if (then + dexOptLRUThresholdInMills < now) {
4473                        if (DEBUG_DEXOPT) {
4474                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4475                                  ((then == 0) ? "never" : new Date(then)));
4476                        }
4477                        i.remove();
4478                        skipped++;
4479                    }
4480                }
4481                if (DEBUG_DEXOPT) {
4482                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4483                }
4484            }
4485
4486            int i = 0;
4487            for (PackageParser.Package pkg : pkgs) {
4488                i++;
4489                if (DEBUG_DEXOPT) {
4490                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4491                          + ": " + pkg.packageName);
4492                }
4493                if (!isFirstBoot()) {
4494                    try {
4495                        ActivityManagerNative.getDefault().showBootMessage(
4496                                mContext.getResources().getString(
4497                                        R.string.android_upgrading_apk,
4498                                        i, pkgs.size()), true);
4499                    } catch (RemoteException e) {
4500                    }
4501                }
4502                PackageParser.Package p = pkg;
4503                synchronized (mInstallLock) {
4504                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4505                            true /* include dependencies */);
4506                }
4507            }
4508        }
4509    }
4510
4511    @Override
4512    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4513        return performDexOpt(packageName, instructionSet, false);
4514    }
4515
4516    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4517        if (info.primaryCpuAbi == null) {
4518            return getPreferredInstructionSet();
4519        }
4520
4521        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4522    }
4523
4524    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4525        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4526        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4527        if (!dexopt && !updateUsage) {
4528            // We aren't going to dexopt or update usage, so bail early.
4529            return false;
4530        }
4531        PackageParser.Package p;
4532        final String targetInstructionSet;
4533        synchronized (mPackages) {
4534            p = mPackages.get(packageName);
4535            if (p == null) {
4536                return false;
4537            }
4538            if (updateUsage) {
4539                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4540            }
4541            mPackageUsage.write(false);
4542            if (!dexopt) {
4543                // We aren't going to dexopt, so bail early.
4544                return false;
4545            }
4546
4547            targetInstructionSet = instructionSet != null ? instructionSet :
4548                    getPrimaryInstructionSet(p.applicationInfo);
4549            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4550                return false;
4551            }
4552        }
4553
4554        synchronized (mInstallLock) {
4555            final String[] instructionSets = new String[] { targetInstructionSet };
4556            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4557                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4558        }
4559    }
4560
4561    public HashSet<String> getPackagesThatNeedDexOpt() {
4562        HashSet<String> pkgs = null;
4563        synchronized (mPackages) {
4564            for (PackageParser.Package p : mPackages.values()) {
4565                if (DEBUG_DEXOPT) {
4566                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4567                }
4568                if (!p.mDexOptPerformed.isEmpty()) {
4569                    continue;
4570                }
4571                if (pkgs == null) {
4572                    pkgs = new HashSet<String>();
4573                }
4574                pkgs.add(p.packageName);
4575            }
4576        }
4577        return pkgs;
4578    }
4579
4580    public void shutdown() {
4581        mPackageUsage.write(true);
4582    }
4583
4584    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4585             boolean forceDex, boolean defer, HashSet<String> done) {
4586        for (int i=0; i<libs.size(); i++) {
4587            PackageParser.Package libPkg;
4588            String libName;
4589            synchronized (mPackages) {
4590                libName = libs.get(i);
4591                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4592                if (lib != null && lib.apk != null) {
4593                    libPkg = mPackages.get(lib.apk);
4594                } else {
4595                    libPkg = null;
4596                }
4597            }
4598            if (libPkg != null && !done.contains(libName)) {
4599                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4600            }
4601        }
4602    }
4603
4604    static final int DEX_OPT_SKIPPED = 0;
4605    static final int DEX_OPT_PERFORMED = 1;
4606    static final int DEX_OPT_DEFERRED = 2;
4607    static final int DEX_OPT_FAILED = -1;
4608
4609    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4610            boolean forceDex, boolean defer, HashSet<String> done) {
4611        final String[] instructionSets = targetInstructionSets != null ?
4612                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4613
4614        if (done != null) {
4615            done.add(pkg.packageName);
4616            if (pkg.usesLibraries != null) {
4617                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4618            }
4619            if (pkg.usesOptionalLibraries != null) {
4620                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4621            }
4622        }
4623
4624        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4625            return DEX_OPT_SKIPPED;
4626        }
4627
4628        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4629
4630        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4631        boolean performedDexOpt = false;
4632        // There are three basic cases here:
4633        // 1.) we need to dexopt, either because we are forced or it is needed
4634        // 2.) we are defering a needed dexopt
4635        // 3.) we are skipping an unneeded dexopt
4636        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4637        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4638            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4639                continue;
4640            }
4641
4642            for (String path : paths) {
4643                try {
4644                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4645                    // patckage or the one we find does not match the image checksum (i.e. it was
4646                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4647                    // odex file and it matches the checksum of the image but not its base address,
4648                    // meaning we need to move it.
4649                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4650                            pkg.packageName, dexCodeInstructionSet, defer);
4651                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4652                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4653                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4654                                + " vmSafeMode=" + vmSafeMode);
4655                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4656                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4657                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4658
4659                        if (ret < 0) {
4660                            // Don't bother running dexopt again if we failed, it will probably
4661                            // just result in an error again. Also, don't bother dexopting for other
4662                            // paths & ISAs.
4663                            return DEX_OPT_FAILED;
4664                        }
4665
4666                        performedDexOpt = true;
4667                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4668                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4669                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4670                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4671                                pkg.packageName, dexCodeInstructionSet);
4672
4673                        if (ret < 0) {
4674                            // Don't bother running patchoat again if we failed, it will probably
4675                            // just result in an error again. Also, don't bother dexopting for other
4676                            // paths & ISAs.
4677                            return DEX_OPT_FAILED;
4678                        }
4679
4680                        performedDexOpt = true;
4681                    }
4682
4683                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4684                    // paths and instruction sets. We'll deal with them all together when we process
4685                    // our list of deferred dexopts.
4686                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4687                        if (mDeferredDexOpt == null) {
4688                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4689                        }
4690                        mDeferredDexOpt.add(pkg);
4691                        return DEX_OPT_DEFERRED;
4692                    }
4693                } catch (FileNotFoundException e) {
4694                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4695                    return DEX_OPT_FAILED;
4696                } catch (IOException e) {
4697                    Slog.w(TAG, "IOException reading apk: " + path, e);
4698                    return DEX_OPT_FAILED;
4699                } catch (StaleDexCacheError e) {
4700                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4701                    return DEX_OPT_FAILED;
4702                } catch (Exception e) {
4703                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4704                    return DEX_OPT_FAILED;
4705                }
4706            }
4707
4708            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4709            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4710            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4711            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4712            // it.
4713            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4714        }
4715
4716        // If we've gotten here, we're sure that no error occurred and that we haven't
4717        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4718        // we've skipped all of them because they are up to date. In both cases this
4719        // package doesn't need dexopt any longer.
4720        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4721    }
4722
4723    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4724        if (info.primaryCpuAbi != null) {
4725            if (info.secondaryCpuAbi != null) {
4726                return new String[] {
4727                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4728                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4729            } else {
4730                return new String[] {
4731                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4732            }
4733        }
4734
4735        return new String[] { getPreferredInstructionSet() };
4736    }
4737
4738    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4739        if (ps.primaryCpuAbiString != null) {
4740            if (ps.secondaryCpuAbiString != null) {
4741                return new String[] {
4742                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4743                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4744            } else {
4745                return new String[] {
4746                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4747            }
4748        }
4749
4750        return new String[] { getPreferredInstructionSet() };
4751    }
4752
4753    private static String getPreferredInstructionSet() {
4754        if (sPreferredInstructionSet == null) {
4755            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4756        }
4757
4758        return sPreferredInstructionSet;
4759    }
4760
4761    private static List<String> getAllInstructionSets() {
4762        final String[] allAbis = Build.SUPPORTED_ABIS;
4763        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4764
4765        for (String abi : allAbis) {
4766            final String instructionSet = VMRuntime.getInstructionSet(abi);
4767            if (!allInstructionSets.contains(instructionSet)) {
4768                allInstructionSets.add(instructionSet);
4769            }
4770        }
4771
4772        return allInstructionSets;
4773    }
4774
4775    /**
4776     * Returns the instruction set that should be used to compile dex code. In the presence of
4777     * a native bridge this might be different than the one shared libraries use.
4778     */
4779    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4780        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4781        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4782    }
4783
4784    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4785        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4786        for (String instructionSet : instructionSets) {
4787            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4788        }
4789        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4790    }
4791
4792    @Override
4793    public void forceDexOpt(String packageName) {
4794        enforceSystemOrRoot("forceDexOpt");
4795
4796        PackageParser.Package pkg;
4797        synchronized (mPackages) {
4798            pkg = mPackages.get(packageName);
4799            if (pkg == null) {
4800                throw new IllegalArgumentException("Missing package: " + packageName);
4801            }
4802        }
4803
4804        synchronized (mInstallLock) {
4805            final String[] instructionSets = new String[] {
4806                    getPrimaryInstructionSet(pkg.applicationInfo) };
4807            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4808            if (res != DEX_OPT_PERFORMED) {
4809                throw new IllegalStateException("Failed to dexopt: " + res);
4810            }
4811        }
4812    }
4813
4814    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4815                                boolean forceDex, boolean defer, boolean inclDependencies) {
4816        HashSet<String> done;
4817        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4818            done = new HashSet<String>();
4819            done.add(pkg.packageName);
4820        } else {
4821            done = null;
4822        }
4823        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4824    }
4825
4826    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4827        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4828            Slog.w(TAG, "Unable to update from " + oldPkg.name
4829                    + " to " + newPkg.packageName
4830                    + ": old package not in system partition");
4831            return false;
4832        } else if (mPackages.get(oldPkg.name) != null) {
4833            Slog.w(TAG, "Unable to update from " + oldPkg.name
4834                    + " to " + newPkg.packageName
4835                    + ": old package still exists");
4836            return false;
4837        }
4838        return true;
4839    }
4840
4841    File getDataPathForUser(int userId) {
4842        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4843    }
4844
4845    private File getDataPathForPackage(String packageName, int userId) {
4846        /*
4847         * Until we fully support multiple users, return the directory we
4848         * previously would have. The PackageManagerTests will need to be
4849         * revised when this is changed back..
4850         */
4851        if (userId == 0) {
4852            return new File(mAppDataDir, packageName);
4853        } else {
4854            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4855                + File.separator + packageName);
4856        }
4857    }
4858
4859    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4860        int[] users = sUserManager.getUserIds();
4861        int res = mInstaller.install(packageName, uid, uid, seinfo);
4862        if (res < 0) {
4863            return res;
4864        }
4865        for (int user : users) {
4866            if (user != 0) {
4867                res = mInstaller.createUserData(packageName,
4868                        UserHandle.getUid(user, uid), user, seinfo);
4869                if (res < 0) {
4870                    return res;
4871                }
4872            }
4873        }
4874        return res;
4875    }
4876
4877    private int removeDataDirsLI(String packageName) {
4878        int[] users = sUserManager.getUserIds();
4879        int res = 0;
4880        for (int user : users) {
4881            int resInner = mInstaller.remove(packageName, user);
4882            if (resInner < 0) {
4883                res = resInner;
4884            }
4885        }
4886
4887        return res;
4888    }
4889
4890    private int deleteCodeCacheDirsLI(String packageName) {
4891        int[] users = sUserManager.getUserIds();
4892        int res = 0;
4893        for (int user : users) {
4894            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4895            if (resInner < 0) {
4896                res = resInner;
4897            }
4898        }
4899        return res;
4900    }
4901
4902    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4903            PackageParser.Package changingLib) {
4904        if (file.path != null) {
4905            usesLibraryFiles.add(file.path);
4906            return;
4907        }
4908        PackageParser.Package p = mPackages.get(file.apk);
4909        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4910            // If we are doing this while in the middle of updating a library apk,
4911            // then we need to make sure to use that new apk for determining the
4912            // dependencies here.  (We haven't yet finished committing the new apk
4913            // to the package manager state.)
4914            if (p == null || p.packageName.equals(changingLib.packageName)) {
4915                p = changingLib;
4916            }
4917        }
4918        if (p != null) {
4919            usesLibraryFiles.addAll(p.getAllCodePaths());
4920        }
4921    }
4922
4923    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4924            PackageParser.Package changingLib) throws PackageManagerException {
4925        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4926            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4927            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4928            for (int i=0; i<N; i++) {
4929                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4930                if (file == null) {
4931                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4932                            "Package " + pkg.packageName + " requires unavailable shared library "
4933                            + pkg.usesLibraries.get(i) + "; failing!");
4934                }
4935                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4936            }
4937            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4938            for (int i=0; i<N; i++) {
4939                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4940                if (file == null) {
4941                    Slog.w(TAG, "Package " + pkg.packageName
4942                            + " desires unavailable shared library "
4943                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4944                } else {
4945                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4946                }
4947            }
4948            N = usesLibraryFiles.size();
4949            if (N > 0) {
4950                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4951            } else {
4952                pkg.usesLibraryFiles = null;
4953            }
4954        }
4955    }
4956
4957    private static boolean hasString(List<String> list, List<String> which) {
4958        if (list == null) {
4959            return false;
4960        }
4961        for (int i=list.size()-1; i>=0; i--) {
4962            for (int j=which.size()-1; j>=0; j--) {
4963                if (which.get(j).equals(list.get(i))) {
4964                    return true;
4965                }
4966            }
4967        }
4968        return false;
4969    }
4970
4971    private void updateAllSharedLibrariesLPw() {
4972        for (PackageParser.Package pkg : mPackages.values()) {
4973            try {
4974                updateSharedLibrariesLPw(pkg, null);
4975            } catch (PackageManagerException e) {
4976                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4977            }
4978        }
4979    }
4980
4981    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4982            PackageParser.Package changingPkg) {
4983        ArrayList<PackageParser.Package> res = null;
4984        for (PackageParser.Package pkg : mPackages.values()) {
4985            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4986                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4987                if (res == null) {
4988                    res = new ArrayList<PackageParser.Package>();
4989                }
4990                res.add(pkg);
4991                try {
4992                    updateSharedLibrariesLPw(pkg, changingPkg);
4993                } catch (PackageManagerException e) {
4994                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4995                }
4996            }
4997        }
4998        return res;
4999    }
5000
5001    /**
5002     * Derive the value of the {@code cpuAbiOverride} based on the provided
5003     * value and an optional stored value from the package settings.
5004     */
5005    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5006        String cpuAbiOverride = null;
5007
5008        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5009            cpuAbiOverride = null;
5010        } else if (abiOverride != null) {
5011            cpuAbiOverride = abiOverride;
5012        } else if (settings != null) {
5013            cpuAbiOverride = settings.cpuAbiOverrideString;
5014        }
5015
5016        return cpuAbiOverride;
5017    }
5018
5019    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5020            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5021        boolean success = false;
5022        try {
5023            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5024                    currentTime, user);
5025            success = true;
5026            return res;
5027        } finally {
5028            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5029                removeDataDirsLI(pkg.packageName);
5030            }
5031        }
5032    }
5033
5034    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5035            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5036        final File scanFile = new File(pkg.codePath);
5037        if (pkg.applicationInfo.getCodePath() == null ||
5038                pkg.applicationInfo.getResourcePath() == null) {
5039            // Bail out. The resource and code paths haven't been set.
5040            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5041                    "Code and resource paths haven't been set correctly");
5042        }
5043
5044        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5045            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5046        }
5047
5048        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5049            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5050        }
5051
5052        if (mCustomResolverComponentName != null &&
5053                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5054            setUpCustomResolverActivity(pkg);
5055        }
5056
5057        if (pkg.packageName.equals("android")) {
5058            synchronized (mPackages) {
5059                if (mAndroidApplication != null) {
5060                    Slog.w(TAG, "*************************************************");
5061                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5062                    Slog.w(TAG, " file=" + scanFile);
5063                    Slog.w(TAG, "*************************************************");
5064                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5065                            "Core android package being redefined.  Skipping.");
5066                }
5067
5068                // Set up information for our fall-back user intent resolution activity.
5069                mPlatformPackage = pkg;
5070                pkg.mVersionCode = mSdkVersion;
5071                mAndroidApplication = pkg.applicationInfo;
5072
5073                if (!mResolverReplaced) {
5074                    mResolveActivity.applicationInfo = mAndroidApplication;
5075                    mResolveActivity.name = ResolverActivity.class.getName();
5076                    mResolveActivity.packageName = mAndroidApplication.packageName;
5077                    mResolveActivity.processName = "system:ui";
5078                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5079                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5080                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5081                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5082                    mResolveActivity.exported = true;
5083                    mResolveActivity.enabled = true;
5084                    mResolveInfo.activityInfo = mResolveActivity;
5085                    mResolveInfo.priority = 0;
5086                    mResolveInfo.preferredOrder = 0;
5087                    mResolveInfo.match = 0;
5088                    mResolveComponentName = new ComponentName(
5089                            mAndroidApplication.packageName, mResolveActivity.name);
5090                }
5091            }
5092        }
5093
5094        if (DEBUG_PACKAGE_SCANNING) {
5095            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5096                Log.d(TAG, "Scanning package " + pkg.packageName);
5097        }
5098
5099        if (mPackages.containsKey(pkg.packageName)
5100                || mSharedLibraries.containsKey(pkg.packageName)) {
5101            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5102                    "Application package " + pkg.packageName
5103                    + " already installed.  Skipping duplicate.");
5104        }
5105
5106        // Initialize package source and resource directories
5107        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5108        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5109
5110        SharedUserSetting suid = null;
5111        PackageSetting pkgSetting = null;
5112
5113        if (!isSystemApp(pkg)) {
5114            // Only system apps can use these features.
5115            pkg.mOriginalPackages = null;
5116            pkg.mRealPackage = null;
5117            pkg.mAdoptPermissions = null;
5118        }
5119
5120        // writer
5121        synchronized (mPackages) {
5122            if (pkg.mSharedUserId != null) {
5123                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5124                if (suid == null) {
5125                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5126                            "Creating application package " + pkg.packageName
5127                            + " for shared user failed");
5128                }
5129                if (DEBUG_PACKAGE_SCANNING) {
5130                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5131                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5132                                + "): packages=" + suid.packages);
5133                }
5134            }
5135
5136            // Check if we are renaming from an original package name.
5137            PackageSetting origPackage = null;
5138            String realName = null;
5139            if (pkg.mOriginalPackages != null) {
5140                // This package may need to be renamed to a previously
5141                // installed name.  Let's check on that...
5142                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5143                if (pkg.mOriginalPackages.contains(renamed)) {
5144                    // This package had originally been installed as the
5145                    // original name, and we have already taken care of
5146                    // transitioning to the new one.  Just update the new
5147                    // one to continue using the old name.
5148                    realName = pkg.mRealPackage;
5149                    if (!pkg.packageName.equals(renamed)) {
5150                        // Callers into this function may have already taken
5151                        // care of renaming the package; only do it here if
5152                        // it is not already done.
5153                        pkg.setPackageName(renamed);
5154                    }
5155
5156                } else {
5157                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5158                        if ((origPackage = mSettings.peekPackageLPr(
5159                                pkg.mOriginalPackages.get(i))) != null) {
5160                            // We do have the package already installed under its
5161                            // original name...  should we use it?
5162                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5163                                // New package is not compatible with original.
5164                                origPackage = null;
5165                                continue;
5166                            } else if (origPackage.sharedUser != null) {
5167                                // Make sure uid is compatible between packages.
5168                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5169                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5170                                            + " to " + pkg.packageName + ": old uid "
5171                                            + origPackage.sharedUser.name
5172                                            + " differs from " + pkg.mSharedUserId);
5173                                    origPackage = null;
5174                                    continue;
5175                                }
5176                            } else {
5177                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5178                                        + pkg.packageName + " to old name " + origPackage.name);
5179                            }
5180                            break;
5181                        }
5182                    }
5183                }
5184            }
5185
5186            if (mTransferedPackages.contains(pkg.packageName)) {
5187                Slog.w(TAG, "Package " + pkg.packageName
5188                        + " was transferred to another, but its .apk remains");
5189            }
5190
5191            // Just create the setting, don't add it yet. For already existing packages
5192            // the PkgSetting exists already and doesn't have to be created.
5193            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5194                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5195                    pkg.applicationInfo.primaryCpuAbi,
5196                    pkg.applicationInfo.secondaryCpuAbi,
5197                    pkg.applicationInfo.flags, user, false);
5198            if (pkgSetting == null) {
5199                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5200                        "Creating application package " + pkg.packageName + " failed");
5201            }
5202
5203            if (pkgSetting.origPackage != null) {
5204                // If we are first transitioning from an original package,
5205                // fix up the new package's name now.  We need to do this after
5206                // looking up the package under its new name, so getPackageLP
5207                // can take care of fiddling things correctly.
5208                pkg.setPackageName(origPackage.name);
5209
5210                // File a report about this.
5211                String msg = "New package " + pkgSetting.realName
5212                        + " renamed to replace old package " + pkgSetting.name;
5213                reportSettingsProblem(Log.WARN, msg);
5214
5215                // Make a note of it.
5216                mTransferedPackages.add(origPackage.name);
5217
5218                // No longer need to retain this.
5219                pkgSetting.origPackage = null;
5220            }
5221
5222            if (realName != null) {
5223                // Make a note of it.
5224                mTransferedPackages.add(pkg.packageName);
5225            }
5226
5227            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5228                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5229            }
5230
5231            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5232                // Check all shared libraries and map to their actual file path.
5233                // We only do this here for apps not on a system dir, because those
5234                // are the only ones that can fail an install due to this.  We
5235                // will take care of the system apps by updating all of their
5236                // library paths after the scan is done.
5237                updateSharedLibrariesLPw(pkg, null);
5238            }
5239
5240            if (mFoundPolicyFile) {
5241                SELinuxMMAC.assignSeinfoValue(pkg);
5242            }
5243
5244            pkg.applicationInfo.uid = pkgSetting.appId;
5245            pkg.mExtras = pkgSetting;
5246            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5247                try {
5248                    verifySignaturesLP(pkgSetting, pkg);
5249                } catch (PackageManagerException e) {
5250                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5251                        throw e;
5252                    }
5253                    // The signature has changed, but this package is in the system
5254                    // image...  let's recover!
5255                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5256                    // However...  if this package is part of a shared user, but it
5257                    // doesn't match the signature of the shared user, let's fail.
5258                    // What this means is that you can't change the signatures
5259                    // associated with an overall shared user, which doesn't seem all
5260                    // that unreasonable.
5261                    if (pkgSetting.sharedUser != null) {
5262                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5263                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5264                            throw new PackageManagerException(
5265                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5266                                            "Signature mismatch for shared user : "
5267                                            + pkgSetting.sharedUser);
5268                        }
5269                    }
5270                    // File a report about this.
5271                    String msg = "System package " + pkg.packageName
5272                        + " signature changed; retaining data.";
5273                    reportSettingsProblem(Log.WARN, msg);
5274                }
5275            } else {
5276                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5277                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5278                            + pkg.packageName + " upgrade keys do not match the "
5279                            + "previously installed version");
5280                } else {
5281                    // signatures may have changed as result of upgrade
5282                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5283                }
5284            }
5285            // Verify that this new package doesn't have any content providers
5286            // that conflict with existing packages.  Only do this if the
5287            // package isn't already installed, since we don't want to break
5288            // things that are installed.
5289            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5290                final int N = pkg.providers.size();
5291                int i;
5292                for (i=0; i<N; i++) {
5293                    PackageParser.Provider p = pkg.providers.get(i);
5294                    if (p.info.authority != null) {
5295                        String names[] = p.info.authority.split(";");
5296                        for (int j = 0; j < names.length; j++) {
5297                            if (mProvidersByAuthority.containsKey(names[j])) {
5298                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5299                                final String otherPackageName =
5300                                        ((other != null && other.getComponentName() != null) ?
5301                                                other.getComponentName().getPackageName() : "?");
5302                                throw new PackageManagerException(
5303                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5304                                                "Can't install because provider name " + names[j]
5305                                                + " (in package " + pkg.applicationInfo.packageName
5306                                                + ") is already used by " + otherPackageName);
5307                            }
5308                        }
5309                    }
5310                }
5311            }
5312
5313            if (pkg.mAdoptPermissions != null) {
5314                // This package wants to adopt ownership of permissions from
5315                // another package.
5316                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5317                    final String origName = pkg.mAdoptPermissions.get(i);
5318                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5319                    if (orig != null) {
5320                        if (verifyPackageUpdateLPr(orig, pkg)) {
5321                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5322                                    + pkg.packageName);
5323                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5324                        }
5325                    }
5326                }
5327            }
5328        }
5329
5330        final String pkgName = pkg.packageName;
5331
5332        final long scanFileTime = scanFile.lastModified();
5333        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5334        pkg.applicationInfo.processName = fixProcessName(
5335                pkg.applicationInfo.packageName,
5336                pkg.applicationInfo.processName,
5337                pkg.applicationInfo.uid);
5338
5339        File dataPath;
5340        if (mPlatformPackage == pkg) {
5341            // The system package is special.
5342            dataPath = new File(Environment.getDataDirectory(), "system");
5343
5344            pkg.applicationInfo.dataDir = dataPath.getPath();
5345
5346        } else {
5347            // This is a normal package, need to make its data directory.
5348            dataPath = getDataPathForPackage(pkg.packageName, 0);
5349
5350            boolean uidError = false;
5351            if (dataPath.exists()) {
5352                int currentUid = 0;
5353                try {
5354                    StructStat stat = Os.stat(dataPath.getPath());
5355                    currentUid = stat.st_uid;
5356                } catch (ErrnoException e) {
5357                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5358                }
5359
5360                // If we have mismatched owners for the data path, we have a problem.
5361                if (currentUid != pkg.applicationInfo.uid) {
5362                    boolean recovered = false;
5363                    if (currentUid == 0) {
5364                        // The directory somehow became owned by root.  Wow.
5365                        // This is probably because the system was stopped while
5366                        // installd was in the middle of messing with its libs
5367                        // directory.  Ask installd to fix that.
5368                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5369                                pkg.applicationInfo.uid);
5370                        if (ret >= 0) {
5371                            recovered = true;
5372                            String msg = "Package " + pkg.packageName
5373                                    + " unexpectedly changed to uid 0; recovered to " +
5374                                    + pkg.applicationInfo.uid;
5375                            reportSettingsProblem(Log.WARN, msg);
5376                        }
5377                    }
5378                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5379                            || (scanFlags&SCAN_BOOTING) != 0)) {
5380                        // If this is a system app, we can at least delete its
5381                        // current data so the application will still work.
5382                        int ret = removeDataDirsLI(pkgName);
5383                        if (ret >= 0) {
5384                            // TODO: Kill the processes first
5385                            // Old data gone!
5386                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5387                                    ? "System package " : "Third party package ";
5388                            String msg = prefix + pkg.packageName
5389                                    + " has changed from uid: "
5390                                    + currentUid + " to "
5391                                    + pkg.applicationInfo.uid + "; old data erased";
5392                            reportSettingsProblem(Log.WARN, msg);
5393                            recovered = true;
5394
5395                            // And now re-install the app.
5396                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5397                                                   pkg.applicationInfo.seinfo);
5398                            if (ret == -1) {
5399                                // Ack should not happen!
5400                                msg = prefix + pkg.packageName
5401                                        + " could not have data directory re-created after delete.";
5402                                reportSettingsProblem(Log.WARN, msg);
5403                                throw new PackageManagerException(
5404                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5405                            }
5406                        }
5407                        if (!recovered) {
5408                            mHasSystemUidErrors = true;
5409                        }
5410                    } else if (!recovered) {
5411                        // If we allow this install to proceed, we will be broken.
5412                        // Abort, abort!
5413                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5414                                "scanPackageLI");
5415                    }
5416                    if (!recovered) {
5417                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5418                            + pkg.applicationInfo.uid + "/fs_"
5419                            + currentUid;
5420                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5421                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5422                        String msg = "Package " + pkg.packageName
5423                                + " has mismatched uid: "
5424                                + currentUid + " on disk, "
5425                                + pkg.applicationInfo.uid + " in settings";
5426                        // writer
5427                        synchronized (mPackages) {
5428                            mSettings.mReadMessages.append(msg);
5429                            mSettings.mReadMessages.append('\n');
5430                            uidError = true;
5431                            if (!pkgSetting.uidError) {
5432                                reportSettingsProblem(Log.ERROR, msg);
5433                            }
5434                        }
5435                    }
5436                }
5437                pkg.applicationInfo.dataDir = dataPath.getPath();
5438                if (mShouldRestoreconData) {
5439                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5440                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5441                                pkg.applicationInfo.uid);
5442                }
5443            } else {
5444                if (DEBUG_PACKAGE_SCANNING) {
5445                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5446                        Log.v(TAG, "Want this data dir: " + dataPath);
5447                }
5448                //invoke installer to do the actual installation
5449                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5450                                           pkg.applicationInfo.seinfo);
5451                if (ret < 0) {
5452                    // Error from installer
5453                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5454                            "Unable to create data dirs [errorCode=" + ret + "]");
5455                }
5456
5457                if (dataPath.exists()) {
5458                    pkg.applicationInfo.dataDir = dataPath.getPath();
5459                } else {
5460                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5461                    pkg.applicationInfo.dataDir = null;
5462                }
5463            }
5464
5465            pkgSetting.uidError = uidError;
5466        }
5467
5468        final String path = scanFile.getPath();
5469        final String codePath = pkg.applicationInfo.getCodePath();
5470        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5471        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5472            setBundledAppAbisAndRoots(pkg, pkgSetting);
5473
5474            // If we haven't found any native libraries for the app, check if it has
5475            // renderscript code. We'll need to force the app to 32 bit if it has
5476            // renderscript bitcode.
5477            if (pkg.applicationInfo.primaryCpuAbi == null
5478                    && pkg.applicationInfo.secondaryCpuAbi == null
5479                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5480                NativeLibraryHelper.Handle handle = null;
5481                try {
5482                    handle = NativeLibraryHelper.Handle.create(scanFile);
5483                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5484                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5485                    }
5486                } catch (IOException ioe) {
5487                    Slog.w(TAG, "Error scanning system app : " + ioe);
5488                } finally {
5489                    IoUtils.closeQuietly(handle);
5490                }
5491            }
5492
5493            setNativeLibraryPaths(pkg);
5494        } else {
5495            // TODO: We can probably be smarter about this stuff. For installed apps,
5496            // we can calculate this information at install time once and for all. For
5497            // system apps, we can probably assume that this information doesn't change
5498            // after the first boot scan. As things stand, we do lots of unnecessary work.
5499
5500            // Give ourselves some initial paths; we'll come back for another
5501            // pass once we've determined ABI below.
5502            setNativeLibraryPaths(pkg);
5503
5504            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5505            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5506            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5507
5508            NativeLibraryHelper.Handle handle = null;
5509            try {
5510                handle = NativeLibraryHelper.Handle.create(scanFile);
5511                // TODO(multiArch): This can be null for apps that didn't go through the
5512                // usual installation process. We can calculate it again, like we
5513                // do during install time.
5514                //
5515                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5516                // unnecessary.
5517                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5518
5519                // Null out the abis so that they can be recalculated.
5520                pkg.applicationInfo.primaryCpuAbi = null;
5521                pkg.applicationInfo.secondaryCpuAbi = null;
5522                if (isMultiArch(pkg.applicationInfo)) {
5523                    // Warn if we've set an abiOverride for multi-lib packages..
5524                    // By definition, we need to copy both 32 and 64 bit libraries for
5525                    // such packages.
5526                    if (pkg.cpuAbiOverride != null
5527                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5528                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5529                    }
5530
5531                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5532                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5533                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5534                        if (isAsec) {
5535                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5536                        } else {
5537                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5538                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5539                                    useIsaSpecificSubdirs);
5540                        }
5541                    }
5542
5543                    maybeThrowExceptionForMultiArchCopy(
5544                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5545
5546                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5547                        if (isAsec) {
5548                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5549                        } else {
5550                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5551                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5552                                    useIsaSpecificSubdirs);
5553                        }
5554                    }
5555
5556                    maybeThrowExceptionForMultiArchCopy(
5557                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5558
5559                    if (abi64 >= 0) {
5560                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5561                    }
5562
5563                    if (abi32 >= 0) {
5564                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5565                        if (abi64 >= 0) {
5566                            pkg.applicationInfo.secondaryCpuAbi = abi;
5567                        } else {
5568                            pkg.applicationInfo.primaryCpuAbi = abi;
5569                        }
5570                    }
5571                } else {
5572                    String[] abiList = (cpuAbiOverride != null) ?
5573                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5574
5575                    // Enable gross and lame hacks for apps that are built with old
5576                    // SDK tools. We must scan their APKs for renderscript bitcode and
5577                    // not launch them if it's present. Don't bother checking on devices
5578                    // that don't have 64 bit support.
5579                    boolean needsRenderScriptOverride = false;
5580                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5581                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5582                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5583                        needsRenderScriptOverride = true;
5584                    }
5585
5586                    final int copyRet;
5587                    if (isAsec) {
5588                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5589                    } else {
5590                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5591                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5592                    }
5593
5594                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5595                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5596                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5597                    }
5598
5599                    if (copyRet >= 0) {
5600                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5601                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5602                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5603                    } else if (needsRenderScriptOverride) {
5604                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5605                    }
5606                }
5607            } catch (IOException ioe) {
5608                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5609            } finally {
5610                IoUtils.closeQuietly(handle);
5611            }
5612
5613            // Now that we've calculated the ABIs and determined if it's an internal app,
5614            // we will go ahead and populate the nativeLibraryPath.
5615            setNativeLibraryPaths(pkg);
5616
5617            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5618            final int[] userIds = sUserManager.getUserIds();
5619            synchronized (mInstallLock) {
5620                // Create a native library symlink only if we have native libraries
5621                // and if the native libraries are 32 bit libraries. We do not provide
5622                // this symlink for 64 bit libraries.
5623                if (pkg.applicationInfo.primaryCpuAbi != null &&
5624                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5625                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5626                    for (int userId : userIds) {
5627                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5628                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5629                                    "Failed linking native library dir (user=" + userId + ")");
5630                        }
5631                    }
5632                }
5633            }
5634        }
5635
5636        // This is a special case for the "system" package, where the ABI is
5637        // dictated by the zygote configuration (and init.rc). We should keep track
5638        // of this ABI so that we can deal with "normal" applications that run under
5639        // the same UID correctly.
5640        if (mPlatformPackage == pkg) {
5641            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5642                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5643        }
5644
5645        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5646        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5647        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5648        // Copy the derived override back to the parsed package, so that we can
5649        // update the package settings accordingly.
5650        pkg.cpuAbiOverride = cpuAbiOverride;
5651
5652        if (DEBUG_ABI_SELECTION) {
5653            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5654                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5655                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5656        }
5657
5658        // Push the derived path down into PackageSettings so we know what to
5659        // clean up at uninstall time.
5660        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5661
5662        if (DEBUG_ABI_SELECTION) {
5663            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5664                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5665                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5666        }
5667
5668        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5669            // We don't do this here during boot because we can do it all
5670            // at once after scanning all existing packages.
5671            //
5672            // We also do this *before* we perform dexopt on this package, so that
5673            // we can avoid redundant dexopts, and also to make sure we've got the
5674            // code and package path correct.
5675            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5676                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5677        }
5678
5679        if ((scanFlags & SCAN_NO_DEX) == 0) {
5680            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5681                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5682                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5683            }
5684        }
5685
5686        if (mFactoryTest && pkg.requestedPermissions.contains(
5687                android.Manifest.permission.FACTORY_TEST)) {
5688            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5689        }
5690
5691        ArrayList<PackageParser.Package> clientLibPkgs = null;
5692
5693        // writer
5694        synchronized (mPackages) {
5695            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5696                // Only system apps can add new shared libraries.
5697                if (pkg.libraryNames != null) {
5698                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5699                        String name = pkg.libraryNames.get(i);
5700                        boolean allowed = false;
5701                        if (isUpdatedSystemApp(pkg)) {
5702                            // New library entries can only be added through the
5703                            // system image.  This is important to get rid of a lot
5704                            // of nasty edge cases: for example if we allowed a non-
5705                            // system update of the app to add a library, then uninstalling
5706                            // the update would make the library go away, and assumptions
5707                            // we made such as through app install filtering would now
5708                            // have allowed apps on the device which aren't compatible
5709                            // with it.  Better to just have the restriction here, be
5710                            // conservative, and create many fewer cases that can negatively
5711                            // impact the user experience.
5712                            final PackageSetting sysPs = mSettings
5713                                    .getDisabledSystemPkgLPr(pkg.packageName);
5714                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5715                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5716                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5717                                        allowed = true;
5718                                        allowed = true;
5719                                        break;
5720                                    }
5721                                }
5722                            }
5723                        } else {
5724                            allowed = true;
5725                        }
5726                        if (allowed) {
5727                            if (!mSharedLibraries.containsKey(name)) {
5728                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5729                            } else if (!name.equals(pkg.packageName)) {
5730                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5731                                        + name + " already exists; skipping");
5732                            }
5733                        } else {
5734                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5735                                    + name + " that is not declared on system image; skipping");
5736                        }
5737                    }
5738                    if ((scanFlags&SCAN_BOOTING) == 0) {
5739                        // If we are not booting, we need to update any applications
5740                        // that are clients of our shared library.  If we are booting,
5741                        // this will all be done once the scan is complete.
5742                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5743                    }
5744                }
5745            }
5746        }
5747
5748        // We also need to dexopt any apps that are dependent on this library.  Note that
5749        // if these fail, we should abort the install since installing the library will
5750        // result in some apps being broken.
5751        if (clientLibPkgs != null) {
5752            if ((scanFlags & SCAN_NO_DEX) == 0) {
5753                for (int i = 0; i < clientLibPkgs.size(); i++) {
5754                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5755                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
5756                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5757                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5758                                "scanPackageLI failed to dexopt clientLibPkgs");
5759                    }
5760                }
5761            }
5762        }
5763
5764        // Request the ActivityManager to kill the process(only for existing packages)
5765        // so that we do not end up in a confused state while the user is still using the older
5766        // version of the application while the new one gets installed.
5767        if ((scanFlags & SCAN_REPLACING) != 0) {
5768            killApplication(pkg.applicationInfo.packageName,
5769                        pkg.applicationInfo.uid, "update pkg");
5770        }
5771
5772        // Also need to kill any apps that are dependent on the library.
5773        if (clientLibPkgs != null) {
5774            for (int i=0; i<clientLibPkgs.size(); i++) {
5775                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5776                killApplication(clientPkg.applicationInfo.packageName,
5777                        clientPkg.applicationInfo.uid, "update lib");
5778            }
5779        }
5780
5781        // writer
5782        synchronized (mPackages) {
5783            // We don't expect installation to fail beyond this point
5784
5785            // Add the new setting to mSettings
5786            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5787            // Add the new setting to mPackages
5788            mPackages.put(pkg.applicationInfo.packageName, pkg);
5789            // Make sure we don't accidentally delete its data.
5790            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5791            while (iter.hasNext()) {
5792                PackageCleanItem item = iter.next();
5793                if (pkgName.equals(item.packageName)) {
5794                    iter.remove();
5795                }
5796            }
5797
5798            // Take care of first install / last update times.
5799            if (currentTime != 0) {
5800                if (pkgSetting.firstInstallTime == 0) {
5801                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5802                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5803                    pkgSetting.lastUpdateTime = currentTime;
5804                }
5805            } else if (pkgSetting.firstInstallTime == 0) {
5806                // We need *something*.  Take time time stamp of the file.
5807                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5808            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5809                if (scanFileTime != pkgSetting.timeStamp) {
5810                    // A package on the system image has changed; consider this
5811                    // to be an update.
5812                    pkgSetting.lastUpdateTime = scanFileTime;
5813                }
5814            }
5815
5816            // Add the package's KeySets to the global KeySetManagerService
5817            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5818            try {
5819                // Old KeySetData no longer valid.
5820                ksms.removeAppKeySetDataLPw(pkg.packageName);
5821                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5822                if (pkg.mKeySetMapping != null) {
5823                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5824                            pkg.mKeySetMapping.entrySet()) {
5825                        if (entry.getValue() != null) {
5826                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5827                                                          entry.getValue(), entry.getKey());
5828                        }
5829                    }
5830                    if (pkg.mUpgradeKeySets != null) {
5831                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5832                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5833                        }
5834                    }
5835                }
5836            } catch (NullPointerException e) {
5837                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5838            } catch (IllegalArgumentException e) {
5839                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5840            }
5841
5842            int N = pkg.providers.size();
5843            StringBuilder r = null;
5844            int i;
5845            for (i=0; i<N; i++) {
5846                PackageParser.Provider p = pkg.providers.get(i);
5847                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5848                        p.info.processName, pkg.applicationInfo.uid);
5849                mProviders.addProvider(p);
5850                p.syncable = p.info.isSyncable;
5851                if (p.info.authority != null) {
5852                    String names[] = p.info.authority.split(";");
5853                    p.info.authority = null;
5854                    for (int j = 0; j < names.length; j++) {
5855                        if (j == 1 && p.syncable) {
5856                            // We only want the first authority for a provider to possibly be
5857                            // syncable, so if we already added this provider using a different
5858                            // authority clear the syncable flag. We copy the provider before
5859                            // changing it because the mProviders object contains a reference
5860                            // to a provider that we don't want to change.
5861                            // Only do this for the second authority since the resulting provider
5862                            // object can be the same for all future authorities for this provider.
5863                            p = new PackageParser.Provider(p);
5864                            p.syncable = false;
5865                        }
5866                        if (!mProvidersByAuthority.containsKey(names[j])) {
5867                            mProvidersByAuthority.put(names[j], p);
5868                            if (p.info.authority == null) {
5869                                p.info.authority = names[j];
5870                            } else {
5871                                p.info.authority = p.info.authority + ";" + names[j];
5872                            }
5873                            if (DEBUG_PACKAGE_SCANNING) {
5874                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5875                                    Log.d(TAG, "Registered content provider: " + names[j]
5876                                            + ", className = " + p.info.name + ", isSyncable = "
5877                                            + p.info.isSyncable);
5878                            }
5879                        } else {
5880                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5881                            Slog.w(TAG, "Skipping provider name " + names[j] +
5882                                    " (in package " + pkg.applicationInfo.packageName +
5883                                    "): name already used by "
5884                                    + ((other != null && other.getComponentName() != null)
5885                                            ? other.getComponentName().getPackageName() : "?"));
5886                        }
5887                    }
5888                }
5889                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5890                    if (r == null) {
5891                        r = new StringBuilder(256);
5892                    } else {
5893                        r.append(' ');
5894                    }
5895                    r.append(p.info.name);
5896                }
5897            }
5898            if (r != null) {
5899                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5900            }
5901
5902            N = pkg.services.size();
5903            r = null;
5904            for (i=0; i<N; i++) {
5905                PackageParser.Service s = pkg.services.get(i);
5906                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5907                        s.info.processName, pkg.applicationInfo.uid);
5908                mServices.addService(s);
5909                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5910                    if (r == null) {
5911                        r = new StringBuilder(256);
5912                    } else {
5913                        r.append(' ');
5914                    }
5915                    r.append(s.info.name);
5916                }
5917            }
5918            if (r != null) {
5919                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5920            }
5921
5922            N = pkg.receivers.size();
5923            r = null;
5924            for (i=0; i<N; i++) {
5925                PackageParser.Activity a = pkg.receivers.get(i);
5926                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5927                        a.info.processName, pkg.applicationInfo.uid);
5928                mReceivers.addActivity(a, "receiver");
5929                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5930                    if (r == null) {
5931                        r = new StringBuilder(256);
5932                    } else {
5933                        r.append(' ');
5934                    }
5935                    r.append(a.info.name);
5936                }
5937            }
5938            if (r != null) {
5939                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5940            }
5941
5942            N = pkg.activities.size();
5943            r = null;
5944            for (i=0; i<N; i++) {
5945                PackageParser.Activity a = pkg.activities.get(i);
5946                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5947                        a.info.processName, pkg.applicationInfo.uid);
5948                mActivities.addActivity(a, "activity");
5949                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5950                    if (r == null) {
5951                        r = new StringBuilder(256);
5952                    } else {
5953                        r.append(' ');
5954                    }
5955                    r.append(a.info.name);
5956                }
5957            }
5958            if (r != null) {
5959                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5960            }
5961
5962            N = pkg.permissionGroups.size();
5963            r = null;
5964            for (i=0; i<N; i++) {
5965                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5966                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5967                if (cur == null) {
5968                    mPermissionGroups.put(pg.info.name, pg);
5969                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5970                        if (r == null) {
5971                            r = new StringBuilder(256);
5972                        } else {
5973                            r.append(' ');
5974                        }
5975                        r.append(pg.info.name);
5976                    }
5977                } else {
5978                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5979                            + pg.info.packageName + " ignored: original from "
5980                            + cur.info.packageName);
5981                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5982                        if (r == null) {
5983                            r = new StringBuilder(256);
5984                        } else {
5985                            r.append(' ');
5986                        }
5987                        r.append("DUP:");
5988                        r.append(pg.info.name);
5989                    }
5990                }
5991            }
5992            if (r != null) {
5993                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5994            }
5995
5996            N = pkg.permissions.size();
5997            r = null;
5998            for (i=0; i<N; i++) {
5999                PackageParser.Permission p = pkg.permissions.get(i);
6000                HashMap<String, BasePermission> permissionMap =
6001                        p.tree ? mSettings.mPermissionTrees
6002                        : mSettings.mPermissions;
6003                p.group = mPermissionGroups.get(p.info.group);
6004                if (p.info.group == null || p.group != null) {
6005                    BasePermission bp = permissionMap.get(p.info.name);
6006
6007                    // Allow system apps to redefine non-system permissions
6008                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6009                        final boolean currentOwnerIsSystem = (bp.perm != null
6010                                && isSystemApp(bp.perm.owner));
6011                        if (isSystemApp(p.owner) && !currentOwnerIsSystem) {
6012                            String msg = "New decl " + p.owner + " of permission  "
6013                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6014                            reportSettingsProblem(Log.WARN, msg);
6015                            bp = null;
6016                        }
6017                    }
6018
6019                    if (bp == null) {
6020                        bp = new BasePermission(p.info.name, p.info.packageName,
6021                                BasePermission.TYPE_NORMAL);
6022                        permissionMap.put(p.info.name, bp);
6023                    }
6024
6025                    if (bp.perm == null) {
6026                        if (bp.sourcePackage == null
6027                                || bp.sourcePackage.equals(p.info.packageName)) {
6028                            BasePermission tree = findPermissionTreeLP(p.info.name);
6029                            if (tree == null
6030                                    || tree.sourcePackage.equals(p.info.packageName)) {
6031                                bp.packageSetting = pkgSetting;
6032                                bp.perm = p;
6033                                bp.uid = pkg.applicationInfo.uid;
6034                                bp.sourcePackage = p.info.packageName;
6035                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6036                                    if (r == null) {
6037                                        r = new StringBuilder(256);
6038                                    } else {
6039                                        r.append(' ');
6040                                    }
6041                                    r.append(p.info.name);
6042                                }
6043                            } else {
6044                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6045                                        + p.info.packageName + " ignored: base tree "
6046                                        + tree.name + " is from package "
6047                                        + tree.sourcePackage);
6048                            }
6049                        } else {
6050                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6051                                    + p.info.packageName + " ignored: original from "
6052                                    + bp.sourcePackage);
6053                        }
6054                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6055                        if (r == null) {
6056                            r = new StringBuilder(256);
6057                        } else {
6058                            r.append(' ');
6059                        }
6060                        r.append("DUP:");
6061                        r.append(p.info.name);
6062                    }
6063                    if (bp.perm == p) {
6064                        bp.protectionLevel = p.info.protectionLevel;
6065                    }
6066                } else {
6067                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6068                            + p.info.packageName + " ignored: no group "
6069                            + p.group);
6070                }
6071            }
6072            if (r != null) {
6073                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6074            }
6075
6076            N = pkg.instrumentation.size();
6077            r = null;
6078            for (i=0; i<N; i++) {
6079                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6080                a.info.packageName = pkg.applicationInfo.packageName;
6081                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6082                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6083                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6084                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6085                a.info.dataDir = pkg.applicationInfo.dataDir;
6086
6087                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6088                // need other information about the application, like the ABI and what not ?
6089                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6090                mInstrumentation.put(a.getComponentName(), a);
6091                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6092                    if (r == null) {
6093                        r = new StringBuilder(256);
6094                    } else {
6095                        r.append(' ');
6096                    }
6097                    r.append(a.info.name);
6098                }
6099            }
6100            if (r != null) {
6101                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6102            }
6103
6104            if (pkg.protectedBroadcasts != null) {
6105                N = pkg.protectedBroadcasts.size();
6106                for (i=0; i<N; i++) {
6107                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6108                }
6109            }
6110
6111            pkgSetting.setTimeStamp(scanFileTime);
6112
6113            // Create idmap files for pairs of (packages, overlay packages).
6114            // Note: "android", ie framework-res.apk, is handled by native layers.
6115            if (pkg.mOverlayTarget != null) {
6116                // This is an overlay package.
6117                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6118                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6119                        mOverlays.put(pkg.mOverlayTarget,
6120                                new HashMap<String, PackageParser.Package>());
6121                    }
6122                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6123                    map.put(pkg.packageName, pkg);
6124                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6125                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6126                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6127                                "scanPackageLI failed to createIdmap");
6128                    }
6129                }
6130            } else if (mOverlays.containsKey(pkg.packageName) &&
6131                    !pkg.packageName.equals("android")) {
6132                // This is a regular package, with one or more known overlay packages.
6133                createIdmapsForPackageLI(pkg);
6134            }
6135        }
6136
6137        return pkg;
6138    }
6139
6140    /**
6141     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6142     * i.e, so that all packages can be run inside a single process if required.
6143     *
6144     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6145     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6146     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6147     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6148     * updating a package that belongs to a shared user.
6149     *
6150     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6151     * adds unnecessary complexity.
6152     */
6153    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6154            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6155        String requiredInstructionSet = null;
6156        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6157            requiredInstructionSet = VMRuntime.getInstructionSet(
6158                     scannedPackage.applicationInfo.primaryCpuAbi);
6159        }
6160
6161        PackageSetting requirer = null;
6162        for (PackageSetting ps : packagesForUser) {
6163            // If packagesForUser contains scannedPackage, we skip it. This will happen
6164            // when scannedPackage is an update of an existing package. Without this check,
6165            // we will never be able to change the ABI of any package belonging to a shared
6166            // user, even if it's compatible with other packages.
6167            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6168                if (ps.primaryCpuAbiString == null) {
6169                    continue;
6170                }
6171
6172                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6173                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6174                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6175                    // this but there's not much we can do.
6176                    String errorMessage = "Instruction set mismatch, "
6177                            + ((requirer == null) ? "[caller]" : requirer)
6178                            + " requires " + requiredInstructionSet + " whereas " + ps
6179                            + " requires " + instructionSet;
6180                    Slog.w(TAG, errorMessage);
6181                }
6182
6183                if (requiredInstructionSet == null) {
6184                    requiredInstructionSet = instructionSet;
6185                    requirer = ps;
6186                }
6187            }
6188        }
6189
6190        if (requiredInstructionSet != null) {
6191            String adjustedAbi;
6192            if (requirer != null) {
6193                // requirer != null implies that either scannedPackage was null or that scannedPackage
6194                // did not require an ABI, in which case we have to adjust scannedPackage to match
6195                // the ABI of the set (which is the same as requirer's ABI)
6196                adjustedAbi = requirer.primaryCpuAbiString;
6197                if (scannedPackage != null) {
6198                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6199                }
6200            } else {
6201                // requirer == null implies that we're updating all ABIs in the set to
6202                // match scannedPackage.
6203                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6204            }
6205
6206            for (PackageSetting ps : packagesForUser) {
6207                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6208                    if (ps.primaryCpuAbiString != null) {
6209                        continue;
6210                    }
6211
6212                    ps.primaryCpuAbiString = adjustedAbi;
6213                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6214                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6215                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6216
6217                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6218                                deferDexOpt, true) == DEX_OPT_FAILED) {
6219                            ps.primaryCpuAbiString = null;
6220                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6221                            return;
6222                        } else {
6223                            mInstaller.rmdex(ps.codePathString,
6224                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6225                        }
6226                    }
6227                }
6228            }
6229        }
6230    }
6231
6232    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6233        synchronized (mPackages) {
6234            mResolverReplaced = true;
6235            // Set up information for custom user intent resolution activity.
6236            mResolveActivity.applicationInfo = pkg.applicationInfo;
6237            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6238            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6239            mResolveActivity.processName = null;
6240            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6241            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6242                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6243            mResolveActivity.theme = 0;
6244            mResolveActivity.exported = true;
6245            mResolveActivity.enabled = true;
6246            mResolveInfo.activityInfo = mResolveActivity;
6247            mResolveInfo.priority = 0;
6248            mResolveInfo.preferredOrder = 0;
6249            mResolveInfo.match = 0;
6250            mResolveComponentName = mCustomResolverComponentName;
6251            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6252                    mResolveComponentName);
6253        }
6254    }
6255
6256    private static String calculateBundledApkRoot(final String codePathString) {
6257        final File codePath = new File(codePathString);
6258        final File codeRoot;
6259        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6260            codeRoot = Environment.getRootDirectory();
6261        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6262            codeRoot = Environment.getOemDirectory();
6263        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6264            codeRoot = Environment.getVendorDirectory();
6265        } else {
6266            // Unrecognized code path; take its top real segment as the apk root:
6267            // e.g. /something/app/blah.apk => /something
6268            try {
6269                File f = codePath.getCanonicalFile();
6270                File parent = f.getParentFile();    // non-null because codePath is a file
6271                File tmp;
6272                while ((tmp = parent.getParentFile()) != null) {
6273                    f = parent;
6274                    parent = tmp;
6275                }
6276                codeRoot = f;
6277                Slog.w(TAG, "Unrecognized code path "
6278                        + codePath + " - using " + codeRoot);
6279            } catch (IOException e) {
6280                // Can't canonicalize the code path -- shenanigans?
6281                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6282                return Environment.getRootDirectory().getPath();
6283            }
6284        }
6285        return codeRoot.getPath();
6286    }
6287
6288    /**
6289     * Derive and set the location of native libraries for the given package,
6290     * which varies depending on where and how the package was installed.
6291     */
6292    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6293        final ApplicationInfo info = pkg.applicationInfo;
6294        final String codePath = pkg.codePath;
6295        final File codeFile = new File(codePath);
6296        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6297        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6298
6299        info.nativeLibraryRootDir = null;
6300        info.nativeLibraryRootRequiresIsa = false;
6301        info.nativeLibraryDir = null;
6302        info.secondaryNativeLibraryDir = null;
6303
6304        if (isApkFile(codeFile)) {
6305            // Monolithic install
6306            if (bundledApp) {
6307                // If "/system/lib64/apkname" exists, assume that is the per-package
6308                // native library directory to use; otherwise use "/system/lib/apkname".
6309                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6310                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6311                        getPrimaryInstructionSet(info));
6312
6313                // This is a bundled system app so choose the path based on the ABI.
6314                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6315                // is just the default path.
6316                final String apkName = deriveCodePathName(codePath);
6317                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6318                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6319                        apkName).getAbsolutePath();
6320
6321                if (info.secondaryCpuAbi != null) {
6322                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6323                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6324                            secondaryLibDir, apkName).getAbsolutePath();
6325                }
6326            } else if (asecApp) {
6327                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6328                        .getAbsolutePath();
6329            } else {
6330                final String apkName = deriveCodePathName(codePath);
6331                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6332                        .getAbsolutePath();
6333            }
6334
6335            info.nativeLibraryRootRequiresIsa = false;
6336            info.nativeLibraryDir = info.nativeLibraryRootDir;
6337        } else {
6338            // Cluster install
6339            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6340            info.nativeLibraryRootRequiresIsa = true;
6341
6342            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6343                    getPrimaryInstructionSet(info)).getAbsolutePath();
6344
6345            if (info.secondaryCpuAbi != null) {
6346                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6347                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6348            }
6349        }
6350    }
6351
6352    /**
6353     * Calculate the abis and roots for a bundled app. These can uniquely
6354     * be determined from the contents of the system partition, i.e whether
6355     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6356     * of this information, and instead assume that the system was built
6357     * sensibly.
6358     */
6359    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6360                                           PackageSetting pkgSetting) {
6361        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6362
6363        // If "/system/lib64/apkname" exists, assume that is the per-package
6364        // native library directory to use; otherwise use "/system/lib/apkname".
6365        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6366        setBundledAppAbi(pkg, apkRoot, apkName);
6367        // pkgSetting might be null during rescan following uninstall of updates
6368        // to a bundled app, so accommodate that possibility.  The settings in
6369        // that case will be established later from the parsed package.
6370        //
6371        // If the settings aren't null, sync them up with what we've just derived.
6372        // note that apkRoot isn't stored in the package settings.
6373        if (pkgSetting != null) {
6374            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6375            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6376        }
6377    }
6378
6379    /**
6380     * Deduces the ABI of a bundled app and sets the relevant fields on the
6381     * parsed pkg object.
6382     *
6383     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6384     *        under which system libraries are installed.
6385     * @param apkName the name of the installed package.
6386     */
6387    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6388        final File codeFile = new File(pkg.codePath);
6389
6390        final boolean has64BitLibs;
6391        final boolean has32BitLibs;
6392        if (isApkFile(codeFile)) {
6393            // Monolithic install
6394            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6395            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6396        } else {
6397            // Cluster install
6398            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6399            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6400                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6401                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6402                has64BitLibs = (new File(rootDir, isa)).exists();
6403            } else {
6404                has64BitLibs = false;
6405            }
6406            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6407                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6408                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6409                has32BitLibs = (new File(rootDir, isa)).exists();
6410            } else {
6411                has32BitLibs = false;
6412            }
6413        }
6414
6415        if (has64BitLibs && !has32BitLibs) {
6416            // The package has 64 bit libs, but not 32 bit libs. Its primary
6417            // ABI should be 64 bit. We can safely assume here that the bundled
6418            // native libraries correspond to the most preferred ABI in the list.
6419
6420            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6421            pkg.applicationInfo.secondaryCpuAbi = null;
6422        } else if (has32BitLibs && !has64BitLibs) {
6423            // The package has 32 bit libs but not 64 bit libs. Its primary
6424            // ABI should be 32 bit.
6425
6426            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6427            pkg.applicationInfo.secondaryCpuAbi = null;
6428        } else if (has32BitLibs && has64BitLibs) {
6429            // The application has both 64 and 32 bit bundled libraries. We check
6430            // here that the app declares multiArch support, and warn if it doesn't.
6431            //
6432            // We will be lenient here and record both ABIs. The primary will be the
6433            // ABI that's higher on the list, i.e, a device that's configured to prefer
6434            // 64 bit apps will see a 64 bit primary ABI,
6435
6436            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6437                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6438            }
6439
6440            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6441                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6442                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6443            } else {
6444                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6445                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6446            }
6447        } else {
6448            pkg.applicationInfo.primaryCpuAbi = null;
6449            pkg.applicationInfo.secondaryCpuAbi = null;
6450        }
6451    }
6452
6453    private void killApplication(String pkgName, int appId, String reason) {
6454        // Request the ActivityManager to kill the process(only for existing packages)
6455        // so that we do not end up in a confused state while the user is still using the older
6456        // version of the application while the new one gets installed.
6457        IActivityManager am = ActivityManagerNative.getDefault();
6458        if (am != null) {
6459            try {
6460                am.killApplicationWithAppId(pkgName, appId, reason);
6461            } catch (RemoteException e) {
6462            }
6463        }
6464    }
6465
6466    void removePackageLI(PackageSetting ps, boolean chatty) {
6467        if (DEBUG_INSTALL) {
6468            if (chatty)
6469                Log.d(TAG, "Removing package " + ps.name);
6470        }
6471
6472        // writer
6473        synchronized (mPackages) {
6474            mPackages.remove(ps.name);
6475            final PackageParser.Package pkg = ps.pkg;
6476            if (pkg != null) {
6477                cleanPackageDataStructuresLILPw(pkg, chatty);
6478            }
6479        }
6480    }
6481
6482    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6483        if (DEBUG_INSTALL) {
6484            if (chatty)
6485                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6486        }
6487
6488        // writer
6489        synchronized (mPackages) {
6490            mPackages.remove(pkg.applicationInfo.packageName);
6491            cleanPackageDataStructuresLILPw(pkg, chatty);
6492        }
6493    }
6494
6495    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6496        int N = pkg.providers.size();
6497        StringBuilder r = null;
6498        int i;
6499        for (i=0; i<N; i++) {
6500            PackageParser.Provider p = pkg.providers.get(i);
6501            mProviders.removeProvider(p);
6502            if (p.info.authority == null) {
6503
6504                /* There was another ContentProvider with this authority when
6505                 * this app was installed so this authority is null,
6506                 * Ignore it as we don't have to unregister the provider.
6507                 */
6508                continue;
6509            }
6510            String names[] = p.info.authority.split(";");
6511            for (int j = 0; j < names.length; j++) {
6512                if (mProvidersByAuthority.get(names[j]) == p) {
6513                    mProvidersByAuthority.remove(names[j]);
6514                    if (DEBUG_REMOVE) {
6515                        if (chatty)
6516                            Log.d(TAG, "Unregistered content provider: " + names[j]
6517                                    + ", className = " + p.info.name + ", isSyncable = "
6518                                    + p.info.isSyncable);
6519                    }
6520                }
6521            }
6522            if (DEBUG_REMOVE && chatty) {
6523                if (r == null) {
6524                    r = new StringBuilder(256);
6525                } else {
6526                    r.append(' ');
6527                }
6528                r.append(p.info.name);
6529            }
6530        }
6531        if (r != null) {
6532            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6533        }
6534
6535        N = pkg.services.size();
6536        r = null;
6537        for (i=0; i<N; i++) {
6538            PackageParser.Service s = pkg.services.get(i);
6539            mServices.removeService(s);
6540            if (chatty) {
6541                if (r == null) {
6542                    r = new StringBuilder(256);
6543                } else {
6544                    r.append(' ');
6545                }
6546                r.append(s.info.name);
6547            }
6548        }
6549        if (r != null) {
6550            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6551        }
6552
6553        N = pkg.receivers.size();
6554        r = null;
6555        for (i=0; i<N; i++) {
6556            PackageParser.Activity a = pkg.receivers.get(i);
6557            mReceivers.removeActivity(a, "receiver");
6558            if (DEBUG_REMOVE && chatty) {
6559                if (r == null) {
6560                    r = new StringBuilder(256);
6561                } else {
6562                    r.append(' ');
6563                }
6564                r.append(a.info.name);
6565            }
6566        }
6567        if (r != null) {
6568            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6569        }
6570
6571        N = pkg.activities.size();
6572        r = null;
6573        for (i=0; i<N; i++) {
6574            PackageParser.Activity a = pkg.activities.get(i);
6575            mActivities.removeActivity(a, "activity");
6576            if (DEBUG_REMOVE && chatty) {
6577                if (r == null) {
6578                    r = new StringBuilder(256);
6579                } else {
6580                    r.append(' ');
6581                }
6582                r.append(a.info.name);
6583            }
6584        }
6585        if (r != null) {
6586            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6587        }
6588
6589        N = pkg.permissions.size();
6590        r = null;
6591        for (i=0; i<N; i++) {
6592            PackageParser.Permission p = pkg.permissions.get(i);
6593            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6594            if (bp == null) {
6595                bp = mSettings.mPermissionTrees.get(p.info.name);
6596            }
6597            if (bp != null && bp.perm == p) {
6598                bp.perm = null;
6599                if (DEBUG_REMOVE && chatty) {
6600                    if (r == null) {
6601                        r = new StringBuilder(256);
6602                    } else {
6603                        r.append(' ');
6604                    }
6605                    r.append(p.info.name);
6606                }
6607            }
6608            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6609                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6610                if (appOpPerms != null) {
6611                    appOpPerms.remove(pkg.packageName);
6612                }
6613            }
6614        }
6615        if (r != null) {
6616            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6617        }
6618
6619        N = pkg.requestedPermissions.size();
6620        r = null;
6621        for (i=0; i<N; i++) {
6622            String perm = pkg.requestedPermissions.get(i);
6623            BasePermission bp = mSettings.mPermissions.get(perm);
6624            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6625                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6626                if (appOpPerms != null) {
6627                    appOpPerms.remove(pkg.packageName);
6628                    if (appOpPerms.isEmpty()) {
6629                        mAppOpPermissionPackages.remove(perm);
6630                    }
6631                }
6632            }
6633        }
6634        if (r != null) {
6635            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6636        }
6637
6638        N = pkg.instrumentation.size();
6639        r = null;
6640        for (i=0; i<N; i++) {
6641            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6642            mInstrumentation.remove(a.getComponentName());
6643            if (DEBUG_REMOVE && chatty) {
6644                if (r == null) {
6645                    r = new StringBuilder(256);
6646                } else {
6647                    r.append(' ');
6648                }
6649                r.append(a.info.name);
6650            }
6651        }
6652        if (r != null) {
6653            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6654        }
6655
6656        r = null;
6657        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6658            // Only system apps can hold shared libraries.
6659            if (pkg.libraryNames != null) {
6660                for (i=0; i<pkg.libraryNames.size(); i++) {
6661                    String name = pkg.libraryNames.get(i);
6662                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6663                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6664                        mSharedLibraries.remove(name);
6665                        if (DEBUG_REMOVE && chatty) {
6666                            if (r == null) {
6667                                r = new StringBuilder(256);
6668                            } else {
6669                                r.append(' ');
6670                            }
6671                            r.append(name);
6672                        }
6673                    }
6674                }
6675            }
6676        }
6677        if (r != null) {
6678            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6679        }
6680    }
6681
6682    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6683        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6684            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6685                return true;
6686            }
6687        }
6688        return false;
6689    }
6690
6691    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6692    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6693    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6694
6695    private void updatePermissionsLPw(String changingPkg,
6696            PackageParser.Package pkgInfo, int flags) {
6697        // Make sure there are no dangling permission trees.
6698        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6699        while (it.hasNext()) {
6700            final BasePermission bp = it.next();
6701            if (bp.packageSetting == null) {
6702                // We may not yet have parsed the package, so just see if
6703                // we still know about its settings.
6704                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6705            }
6706            if (bp.packageSetting == null) {
6707                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6708                        + " from package " + bp.sourcePackage);
6709                it.remove();
6710            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6711                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6712                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6713                            + " from package " + bp.sourcePackage);
6714                    flags |= UPDATE_PERMISSIONS_ALL;
6715                    it.remove();
6716                }
6717            }
6718        }
6719
6720        // Make sure all dynamic permissions have been assigned to a package,
6721        // and make sure there are no dangling permissions.
6722        it = mSettings.mPermissions.values().iterator();
6723        while (it.hasNext()) {
6724            final BasePermission bp = it.next();
6725            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6726                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6727                        + bp.name + " pkg=" + bp.sourcePackage
6728                        + " info=" + bp.pendingInfo);
6729                if (bp.packageSetting == null && bp.pendingInfo != null) {
6730                    final BasePermission tree = findPermissionTreeLP(bp.name);
6731                    if (tree != null && tree.perm != null) {
6732                        bp.packageSetting = tree.packageSetting;
6733                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6734                                new PermissionInfo(bp.pendingInfo));
6735                        bp.perm.info.packageName = tree.perm.info.packageName;
6736                        bp.perm.info.name = bp.name;
6737                        bp.uid = tree.uid;
6738                    }
6739                }
6740            }
6741            if (bp.packageSetting == null) {
6742                // We may not yet have parsed the package, so just see if
6743                // we still know about its settings.
6744                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6745            }
6746            if (bp.packageSetting == null) {
6747                Slog.w(TAG, "Removing dangling permission: " + bp.name
6748                        + " from package " + bp.sourcePackage);
6749                it.remove();
6750            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6751                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6752                    Slog.i(TAG, "Removing old permission: " + bp.name
6753                            + " from package " + bp.sourcePackage);
6754                    flags |= UPDATE_PERMISSIONS_ALL;
6755                    it.remove();
6756                }
6757            }
6758        }
6759
6760        // Now update the permissions for all packages, in particular
6761        // replace the granted permissions of the system packages.
6762        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6763            for (PackageParser.Package pkg : mPackages.values()) {
6764                if (pkg != pkgInfo) {
6765                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6766                            changingPkg);
6767                }
6768            }
6769        }
6770
6771        if (pkgInfo != null) {
6772            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6773        }
6774    }
6775
6776    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6777            String packageOfInterest) {
6778        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6779        if (ps == null) {
6780            return;
6781        }
6782        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6783        HashSet<String> origPermissions = gp.grantedPermissions;
6784        boolean changedPermission = false;
6785
6786        if (replace) {
6787            ps.permissionsFixed = false;
6788            if (gp == ps) {
6789                origPermissions = new HashSet<String>(gp.grantedPermissions);
6790                gp.grantedPermissions.clear();
6791                gp.gids = mGlobalGids;
6792            }
6793        }
6794
6795        if (gp.gids == null) {
6796            gp.gids = mGlobalGids;
6797        }
6798
6799        final int N = pkg.requestedPermissions.size();
6800        for (int i=0; i<N; i++) {
6801            final String name = pkg.requestedPermissions.get(i);
6802            final boolean required = pkg.requestedPermissionsRequired.get(i);
6803            final BasePermission bp = mSettings.mPermissions.get(name);
6804            if (DEBUG_INSTALL) {
6805                if (gp != ps) {
6806                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6807                }
6808            }
6809
6810            if (bp == null || bp.packageSetting == null) {
6811                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6812                    Slog.w(TAG, "Unknown permission " + name
6813                            + " in package " + pkg.packageName);
6814                }
6815                continue;
6816            }
6817
6818            final String perm = bp.name;
6819            boolean allowed;
6820            boolean allowedSig = false;
6821            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6822                // Keep track of app op permissions.
6823                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6824                if (pkgs == null) {
6825                    pkgs = new ArraySet<>();
6826                    mAppOpPermissionPackages.put(bp.name, pkgs);
6827                }
6828                pkgs.add(pkg.packageName);
6829            }
6830            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6831            if (level == PermissionInfo.PROTECTION_NORMAL
6832                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6833                // We grant a normal or dangerous permission if any of the following
6834                // are true:
6835                // 1) The permission is required
6836                // 2) The permission is optional, but was granted in the past
6837                // 3) The permission is optional, but was requested by an
6838                //    app in /system (not /data)
6839                //
6840                // Otherwise, reject the permission.
6841                allowed = (required || origPermissions.contains(perm)
6842                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6843            } else if (bp.packageSetting == null) {
6844                // This permission is invalid; skip it.
6845                allowed = false;
6846            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6847                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6848                if (allowed) {
6849                    allowedSig = true;
6850                }
6851            } else {
6852                allowed = false;
6853            }
6854            if (DEBUG_INSTALL) {
6855                if (gp != ps) {
6856                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6857                }
6858            }
6859            if (allowed) {
6860                if (!isSystemApp(ps) && ps.permissionsFixed) {
6861                    // If this is an existing, non-system package, then
6862                    // we can't add any new permissions to it.
6863                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6864                        // Except...  if this is a permission that was added
6865                        // to the platform (note: need to only do this when
6866                        // updating the platform).
6867                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6868                    }
6869                }
6870                if (allowed) {
6871                    if (!gp.grantedPermissions.contains(perm)) {
6872                        changedPermission = true;
6873                        gp.grantedPermissions.add(perm);
6874                        gp.gids = appendInts(gp.gids, bp.gids);
6875                    } else if (!ps.haveGids) {
6876                        gp.gids = appendInts(gp.gids, bp.gids);
6877                    }
6878                } else {
6879                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6880                        Slog.w(TAG, "Not granting permission " + perm
6881                                + " to package " + pkg.packageName
6882                                + " because it was previously installed without");
6883                    }
6884                }
6885            } else {
6886                if (gp.grantedPermissions.remove(perm)) {
6887                    changedPermission = true;
6888                    gp.gids = removeInts(gp.gids, bp.gids);
6889                    Slog.i(TAG, "Un-granting permission " + perm
6890                            + " from package " + pkg.packageName
6891                            + " (protectionLevel=" + bp.protectionLevel
6892                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6893                            + ")");
6894                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6895                    // Don't print warning for app op permissions, since it is fine for them
6896                    // not to be granted, there is a UI for the user to decide.
6897                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6898                        Slog.w(TAG, "Not granting permission " + perm
6899                                + " to package " + pkg.packageName
6900                                + " (protectionLevel=" + bp.protectionLevel
6901                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6902                                + ")");
6903                    }
6904                }
6905            }
6906        }
6907
6908        if ((changedPermission || replace) && !ps.permissionsFixed &&
6909                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6910            // This is the first that we have heard about this package, so the
6911            // permissions we have now selected are fixed until explicitly
6912            // changed.
6913            ps.permissionsFixed = true;
6914        }
6915        ps.haveGids = true;
6916    }
6917
6918    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6919        boolean allowed = false;
6920        final int NP = PackageParser.NEW_PERMISSIONS.length;
6921        for (int ip=0; ip<NP; ip++) {
6922            final PackageParser.NewPermissionInfo npi
6923                    = PackageParser.NEW_PERMISSIONS[ip];
6924            if (npi.name.equals(perm)
6925                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6926                allowed = true;
6927                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6928                        + pkg.packageName);
6929                break;
6930            }
6931        }
6932        return allowed;
6933    }
6934
6935    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6936                                          BasePermission bp, HashSet<String> origPermissions) {
6937        boolean allowed;
6938        allowed = (compareSignatures(
6939                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6940                        == PackageManager.SIGNATURE_MATCH)
6941                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6942                        == PackageManager.SIGNATURE_MATCH);
6943        if (!allowed && (bp.protectionLevel
6944                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6945            if (isSystemApp(pkg)) {
6946                // For updated system applications, a system permission
6947                // is granted only if it had been defined by the original application.
6948                if (isUpdatedSystemApp(pkg)) {
6949                    final PackageSetting sysPs = mSettings
6950                            .getDisabledSystemPkgLPr(pkg.packageName);
6951                    final GrantedPermissions origGp = sysPs.sharedUser != null
6952                            ? sysPs.sharedUser : sysPs;
6953
6954                    if (origGp.grantedPermissions.contains(perm)) {
6955                        // If the original was granted this permission, we take
6956                        // that grant decision as read and propagate it to the
6957                        // update.
6958                        allowed = true;
6959                    } else {
6960                        // The system apk may have been updated with an older
6961                        // version of the one on the data partition, but which
6962                        // granted a new system permission that it didn't have
6963                        // before.  In this case we do want to allow the app to
6964                        // now get the new permission if the ancestral apk is
6965                        // privileged to get it.
6966                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6967                            for (int j=0;
6968                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6969                                if (perm.equals(
6970                                        sysPs.pkg.requestedPermissions.get(j))) {
6971                                    allowed = true;
6972                                    break;
6973                                }
6974                            }
6975                        }
6976                    }
6977                } else {
6978                    allowed = isPrivilegedApp(pkg);
6979                }
6980            }
6981        }
6982        if (!allowed && (bp.protectionLevel
6983                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6984            // For development permissions, a development permission
6985            // is granted only if it was already granted.
6986            allowed = origPermissions.contains(perm);
6987        }
6988        return allowed;
6989    }
6990
6991    final class ActivityIntentResolver
6992            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6993        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6994                boolean defaultOnly, int userId) {
6995            if (!sUserManager.exists(userId)) return null;
6996            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6997            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6998        }
6999
7000        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7001                int userId) {
7002            if (!sUserManager.exists(userId)) return null;
7003            mFlags = flags;
7004            return super.queryIntent(intent, resolvedType,
7005                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7006        }
7007
7008        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7009                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7010            if (!sUserManager.exists(userId)) return null;
7011            if (packageActivities == null) {
7012                return null;
7013            }
7014            mFlags = flags;
7015            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7016            final int N = packageActivities.size();
7017            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7018                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7019
7020            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7021            for (int i = 0; i < N; ++i) {
7022                intentFilters = packageActivities.get(i).intents;
7023                if (intentFilters != null && intentFilters.size() > 0) {
7024                    PackageParser.ActivityIntentInfo[] array =
7025                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7026                    intentFilters.toArray(array);
7027                    listCut.add(array);
7028                }
7029            }
7030            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7031        }
7032
7033        public final void addActivity(PackageParser.Activity a, String type) {
7034            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7035            mActivities.put(a.getComponentName(), a);
7036            if (DEBUG_SHOW_INFO)
7037                Log.v(
7038                TAG, "  " + type + " " +
7039                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7040            if (DEBUG_SHOW_INFO)
7041                Log.v(TAG, "    Class=" + a.info.name);
7042            final int NI = a.intents.size();
7043            for (int j=0; j<NI; j++) {
7044                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7045                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7046                    intent.setPriority(0);
7047                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7048                            + a.className + " with priority > 0, forcing to 0");
7049                }
7050                if (DEBUG_SHOW_INFO) {
7051                    Log.v(TAG, "    IntentFilter:");
7052                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7053                }
7054                if (!intent.debugCheck()) {
7055                    Log.w(TAG, "==> For Activity " + a.info.name);
7056                }
7057                addFilter(intent);
7058            }
7059        }
7060
7061        public final void removeActivity(PackageParser.Activity a, String type) {
7062            mActivities.remove(a.getComponentName());
7063            if (DEBUG_SHOW_INFO) {
7064                Log.v(TAG, "  " + type + " "
7065                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7066                                : a.info.name) + ":");
7067                Log.v(TAG, "    Class=" + a.info.name);
7068            }
7069            final int NI = a.intents.size();
7070            for (int j=0; j<NI; j++) {
7071                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7072                if (DEBUG_SHOW_INFO) {
7073                    Log.v(TAG, "    IntentFilter:");
7074                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7075                }
7076                removeFilter(intent);
7077            }
7078        }
7079
7080        @Override
7081        protected boolean allowFilterResult(
7082                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7083            ActivityInfo filterAi = filter.activity.info;
7084            for (int i=dest.size()-1; i>=0; i--) {
7085                ActivityInfo destAi = dest.get(i).activityInfo;
7086                if (destAi.name == filterAi.name
7087                        && destAi.packageName == filterAi.packageName) {
7088                    return false;
7089                }
7090            }
7091            return true;
7092        }
7093
7094        @Override
7095        protected ActivityIntentInfo[] newArray(int size) {
7096            return new ActivityIntentInfo[size];
7097        }
7098
7099        @Override
7100        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7101            if (!sUserManager.exists(userId)) return true;
7102            PackageParser.Package p = filter.activity.owner;
7103            if (p != null) {
7104                PackageSetting ps = (PackageSetting)p.mExtras;
7105                if (ps != null) {
7106                    // System apps are never considered stopped for purposes of
7107                    // filtering, because there may be no way for the user to
7108                    // actually re-launch them.
7109                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7110                            && ps.getStopped(userId);
7111                }
7112            }
7113            return false;
7114        }
7115
7116        @Override
7117        protected boolean isPackageForFilter(String packageName,
7118                PackageParser.ActivityIntentInfo info) {
7119            return packageName.equals(info.activity.owner.packageName);
7120        }
7121
7122        @Override
7123        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7124                int match, int userId) {
7125            if (!sUserManager.exists(userId)) return null;
7126            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7127                return null;
7128            }
7129            final PackageParser.Activity activity = info.activity;
7130            if (mSafeMode && (activity.info.applicationInfo.flags
7131                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7132                return null;
7133            }
7134            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7135            if (ps == null) {
7136                return null;
7137            }
7138            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7139                    ps.readUserState(userId), userId);
7140            if (ai == null) {
7141                return null;
7142            }
7143            final ResolveInfo res = new ResolveInfo();
7144            res.activityInfo = ai;
7145            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7146                res.filter = info;
7147            }
7148            res.priority = info.getPriority();
7149            res.preferredOrder = activity.owner.mPreferredOrder;
7150            //System.out.println("Result: " + res.activityInfo.className +
7151            //                   " = " + res.priority);
7152            res.match = match;
7153            res.isDefault = info.hasDefault;
7154            res.labelRes = info.labelRes;
7155            res.nonLocalizedLabel = info.nonLocalizedLabel;
7156            if (userNeedsBadging(userId)) {
7157                res.noResourceId = true;
7158            } else {
7159                res.icon = info.icon;
7160            }
7161            res.system = isSystemApp(res.activityInfo.applicationInfo);
7162            return res;
7163        }
7164
7165        @Override
7166        protected void sortResults(List<ResolveInfo> results) {
7167            Collections.sort(results, mResolvePrioritySorter);
7168        }
7169
7170        @Override
7171        protected void dumpFilter(PrintWriter out, String prefix,
7172                PackageParser.ActivityIntentInfo filter) {
7173            out.print(prefix); out.print(
7174                    Integer.toHexString(System.identityHashCode(filter.activity)));
7175                    out.print(' ');
7176                    filter.activity.printComponentShortName(out);
7177                    out.print(" filter ");
7178                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7179        }
7180
7181//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7182//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7183//            final List<ResolveInfo> retList = Lists.newArrayList();
7184//            while (i.hasNext()) {
7185//                final ResolveInfo resolveInfo = i.next();
7186//                if (isEnabledLP(resolveInfo.activityInfo)) {
7187//                    retList.add(resolveInfo);
7188//                }
7189//            }
7190//            return retList;
7191//        }
7192
7193        // Keys are String (activity class name), values are Activity.
7194        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7195                = new HashMap<ComponentName, PackageParser.Activity>();
7196        private int mFlags;
7197    }
7198
7199    private final class ServiceIntentResolver
7200            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7201        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7202                boolean defaultOnly, int userId) {
7203            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7204            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7205        }
7206
7207        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7208                int userId) {
7209            if (!sUserManager.exists(userId)) return null;
7210            mFlags = flags;
7211            return super.queryIntent(intent, resolvedType,
7212                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7213        }
7214
7215        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7216                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7217            if (!sUserManager.exists(userId)) return null;
7218            if (packageServices == null) {
7219                return null;
7220            }
7221            mFlags = flags;
7222            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7223            final int N = packageServices.size();
7224            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7225                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7226
7227            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7228            for (int i = 0; i < N; ++i) {
7229                intentFilters = packageServices.get(i).intents;
7230                if (intentFilters != null && intentFilters.size() > 0) {
7231                    PackageParser.ServiceIntentInfo[] array =
7232                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7233                    intentFilters.toArray(array);
7234                    listCut.add(array);
7235                }
7236            }
7237            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7238        }
7239
7240        public final void addService(PackageParser.Service s) {
7241            mServices.put(s.getComponentName(), s);
7242            if (DEBUG_SHOW_INFO) {
7243                Log.v(TAG, "  "
7244                        + (s.info.nonLocalizedLabel != null
7245                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7246                Log.v(TAG, "    Class=" + s.info.name);
7247            }
7248            final int NI = s.intents.size();
7249            int j;
7250            for (j=0; j<NI; j++) {
7251                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7252                if (DEBUG_SHOW_INFO) {
7253                    Log.v(TAG, "    IntentFilter:");
7254                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7255                }
7256                if (!intent.debugCheck()) {
7257                    Log.w(TAG, "==> For Service " + s.info.name);
7258                }
7259                addFilter(intent);
7260            }
7261        }
7262
7263        public final void removeService(PackageParser.Service s) {
7264            mServices.remove(s.getComponentName());
7265            if (DEBUG_SHOW_INFO) {
7266                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7267                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7268                Log.v(TAG, "    Class=" + s.info.name);
7269            }
7270            final int NI = s.intents.size();
7271            int j;
7272            for (j=0; j<NI; j++) {
7273                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7274                if (DEBUG_SHOW_INFO) {
7275                    Log.v(TAG, "    IntentFilter:");
7276                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7277                }
7278                removeFilter(intent);
7279            }
7280        }
7281
7282        @Override
7283        protected boolean allowFilterResult(
7284                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7285            ServiceInfo filterSi = filter.service.info;
7286            for (int i=dest.size()-1; i>=0; i--) {
7287                ServiceInfo destAi = dest.get(i).serviceInfo;
7288                if (destAi.name == filterSi.name
7289                        && destAi.packageName == filterSi.packageName) {
7290                    return false;
7291                }
7292            }
7293            return true;
7294        }
7295
7296        @Override
7297        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7298            return new PackageParser.ServiceIntentInfo[size];
7299        }
7300
7301        @Override
7302        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7303            if (!sUserManager.exists(userId)) return true;
7304            PackageParser.Package p = filter.service.owner;
7305            if (p != null) {
7306                PackageSetting ps = (PackageSetting)p.mExtras;
7307                if (ps != null) {
7308                    // System apps are never considered stopped for purposes of
7309                    // filtering, because there may be no way for the user to
7310                    // actually re-launch them.
7311                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7312                            && ps.getStopped(userId);
7313                }
7314            }
7315            return false;
7316        }
7317
7318        @Override
7319        protected boolean isPackageForFilter(String packageName,
7320                PackageParser.ServiceIntentInfo info) {
7321            return packageName.equals(info.service.owner.packageName);
7322        }
7323
7324        @Override
7325        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7326                int match, int userId) {
7327            if (!sUserManager.exists(userId)) return null;
7328            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7329            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7330                return null;
7331            }
7332            final PackageParser.Service service = info.service;
7333            if (mSafeMode && (service.info.applicationInfo.flags
7334                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7335                return null;
7336            }
7337            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7338            if (ps == null) {
7339                return null;
7340            }
7341            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7342                    ps.readUserState(userId), userId);
7343            if (si == null) {
7344                return null;
7345            }
7346            final ResolveInfo res = new ResolveInfo();
7347            res.serviceInfo = si;
7348            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7349                res.filter = filter;
7350            }
7351            res.priority = info.getPriority();
7352            res.preferredOrder = service.owner.mPreferredOrder;
7353            //System.out.println("Result: " + res.activityInfo.className +
7354            //                   " = " + res.priority);
7355            res.match = match;
7356            res.isDefault = info.hasDefault;
7357            res.labelRes = info.labelRes;
7358            res.nonLocalizedLabel = info.nonLocalizedLabel;
7359            res.icon = info.icon;
7360            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7361            return res;
7362        }
7363
7364        @Override
7365        protected void sortResults(List<ResolveInfo> results) {
7366            Collections.sort(results, mResolvePrioritySorter);
7367        }
7368
7369        @Override
7370        protected void dumpFilter(PrintWriter out, String prefix,
7371                PackageParser.ServiceIntentInfo filter) {
7372            out.print(prefix); out.print(
7373                    Integer.toHexString(System.identityHashCode(filter.service)));
7374                    out.print(' ');
7375                    filter.service.printComponentShortName(out);
7376                    out.print(" filter ");
7377                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7378        }
7379
7380//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7381//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7382//            final List<ResolveInfo> retList = Lists.newArrayList();
7383//            while (i.hasNext()) {
7384//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7385//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7386//                    retList.add(resolveInfo);
7387//                }
7388//            }
7389//            return retList;
7390//        }
7391
7392        // Keys are String (activity class name), values are Activity.
7393        private final HashMap<ComponentName, PackageParser.Service> mServices
7394                = new HashMap<ComponentName, PackageParser.Service>();
7395        private int mFlags;
7396    };
7397
7398    private final class ProviderIntentResolver
7399            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7400        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7401                boolean defaultOnly, int userId) {
7402            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7403            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7404        }
7405
7406        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7407                int userId) {
7408            if (!sUserManager.exists(userId))
7409                return null;
7410            mFlags = flags;
7411            return super.queryIntent(intent, resolvedType,
7412                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7413        }
7414
7415        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7416                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7417            if (!sUserManager.exists(userId))
7418                return null;
7419            if (packageProviders == null) {
7420                return null;
7421            }
7422            mFlags = flags;
7423            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7424            final int N = packageProviders.size();
7425            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7426                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7427
7428            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7429            for (int i = 0; i < N; ++i) {
7430                intentFilters = packageProviders.get(i).intents;
7431                if (intentFilters != null && intentFilters.size() > 0) {
7432                    PackageParser.ProviderIntentInfo[] array =
7433                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7434                    intentFilters.toArray(array);
7435                    listCut.add(array);
7436                }
7437            }
7438            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7439        }
7440
7441        public final void addProvider(PackageParser.Provider p) {
7442            if (mProviders.containsKey(p.getComponentName())) {
7443                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7444                return;
7445            }
7446
7447            mProviders.put(p.getComponentName(), p);
7448            if (DEBUG_SHOW_INFO) {
7449                Log.v(TAG, "  "
7450                        + (p.info.nonLocalizedLabel != null
7451                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7452                Log.v(TAG, "    Class=" + p.info.name);
7453            }
7454            final int NI = p.intents.size();
7455            int j;
7456            for (j = 0; j < NI; j++) {
7457                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7458                if (DEBUG_SHOW_INFO) {
7459                    Log.v(TAG, "    IntentFilter:");
7460                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7461                }
7462                if (!intent.debugCheck()) {
7463                    Log.w(TAG, "==> For Provider " + p.info.name);
7464                }
7465                addFilter(intent);
7466            }
7467        }
7468
7469        public final void removeProvider(PackageParser.Provider p) {
7470            mProviders.remove(p.getComponentName());
7471            if (DEBUG_SHOW_INFO) {
7472                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7473                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7474                Log.v(TAG, "    Class=" + p.info.name);
7475            }
7476            final int NI = p.intents.size();
7477            int j;
7478            for (j = 0; j < NI; j++) {
7479                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7480                if (DEBUG_SHOW_INFO) {
7481                    Log.v(TAG, "    IntentFilter:");
7482                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7483                }
7484                removeFilter(intent);
7485            }
7486        }
7487
7488        @Override
7489        protected boolean allowFilterResult(
7490                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7491            ProviderInfo filterPi = filter.provider.info;
7492            for (int i = dest.size() - 1; i >= 0; i--) {
7493                ProviderInfo destPi = dest.get(i).providerInfo;
7494                if (destPi.name == filterPi.name
7495                        && destPi.packageName == filterPi.packageName) {
7496                    return false;
7497                }
7498            }
7499            return true;
7500        }
7501
7502        @Override
7503        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7504            return new PackageParser.ProviderIntentInfo[size];
7505        }
7506
7507        @Override
7508        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7509            if (!sUserManager.exists(userId))
7510                return true;
7511            PackageParser.Package p = filter.provider.owner;
7512            if (p != null) {
7513                PackageSetting ps = (PackageSetting) p.mExtras;
7514                if (ps != null) {
7515                    // System apps are never considered stopped for purposes of
7516                    // filtering, because there may be no way for the user to
7517                    // actually re-launch them.
7518                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7519                            && ps.getStopped(userId);
7520                }
7521            }
7522            return false;
7523        }
7524
7525        @Override
7526        protected boolean isPackageForFilter(String packageName,
7527                PackageParser.ProviderIntentInfo info) {
7528            return packageName.equals(info.provider.owner.packageName);
7529        }
7530
7531        @Override
7532        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7533                int match, int userId) {
7534            if (!sUserManager.exists(userId))
7535                return null;
7536            final PackageParser.ProviderIntentInfo info = filter;
7537            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7538                return null;
7539            }
7540            final PackageParser.Provider provider = info.provider;
7541            if (mSafeMode && (provider.info.applicationInfo.flags
7542                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7543                return null;
7544            }
7545            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7546            if (ps == null) {
7547                return null;
7548            }
7549            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7550                    ps.readUserState(userId), userId);
7551            if (pi == null) {
7552                return null;
7553            }
7554            final ResolveInfo res = new ResolveInfo();
7555            res.providerInfo = pi;
7556            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7557                res.filter = filter;
7558            }
7559            res.priority = info.getPriority();
7560            res.preferredOrder = provider.owner.mPreferredOrder;
7561            res.match = match;
7562            res.isDefault = info.hasDefault;
7563            res.labelRes = info.labelRes;
7564            res.nonLocalizedLabel = info.nonLocalizedLabel;
7565            res.icon = info.icon;
7566            res.system = isSystemApp(res.providerInfo.applicationInfo);
7567            return res;
7568        }
7569
7570        @Override
7571        protected void sortResults(List<ResolveInfo> results) {
7572            Collections.sort(results, mResolvePrioritySorter);
7573        }
7574
7575        @Override
7576        protected void dumpFilter(PrintWriter out, String prefix,
7577                PackageParser.ProviderIntentInfo filter) {
7578            out.print(prefix);
7579            out.print(
7580                    Integer.toHexString(System.identityHashCode(filter.provider)));
7581            out.print(' ');
7582            filter.provider.printComponentShortName(out);
7583            out.print(" filter ");
7584            out.println(Integer.toHexString(System.identityHashCode(filter)));
7585        }
7586
7587        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7588                = new HashMap<ComponentName, PackageParser.Provider>();
7589        private int mFlags;
7590    };
7591
7592    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7593            new Comparator<ResolveInfo>() {
7594        public int compare(ResolveInfo r1, ResolveInfo r2) {
7595            int v1 = r1.priority;
7596            int v2 = r2.priority;
7597            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7598            if (v1 != v2) {
7599                return (v1 > v2) ? -1 : 1;
7600            }
7601            v1 = r1.preferredOrder;
7602            v2 = r2.preferredOrder;
7603            if (v1 != v2) {
7604                return (v1 > v2) ? -1 : 1;
7605            }
7606            if (r1.isDefault != r2.isDefault) {
7607                return r1.isDefault ? -1 : 1;
7608            }
7609            v1 = r1.match;
7610            v2 = r2.match;
7611            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7612            if (v1 != v2) {
7613                return (v1 > v2) ? -1 : 1;
7614            }
7615            if (r1.system != r2.system) {
7616                return r1.system ? -1 : 1;
7617            }
7618            return 0;
7619        }
7620    };
7621
7622    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7623            new Comparator<ProviderInfo>() {
7624        public int compare(ProviderInfo p1, ProviderInfo p2) {
7625            final int v1 = p1.initOrder;
7626            final int v2 = p2.initOrder;
7627            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7628        }
7629    };
7630
7631    static final void sendPackageBroadcast(String action, String pkg,
7632            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7633            int[] userIds) {
7634        IActivityManager am = ActivityManagerNative.getDefault();
7635        if (am != null) {
7636            try {
7637                if (userIds == null) {
7638                    userIds = am.getRunningUserIds();
7639                }
7640                for (int id : userIds) {
7641                    final Intent intent = new Intent(action,
7642                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7643                    if (extras != null) {
7644                        intent.putExtras(extras);
7645                    }
7646                    if (targetPkg != null) {
7647                        intent.setPackage(targetPkg);
7648                    }
7649                    // Modify the UID when posting to other users
7650                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7651                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7652                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7653                        intent.putExtra(Intent.EXTRA_UID, uid);
7654                    }
7655                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7656                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7657                    if (DEBUG_BROADCASTS) {
7658                        RuntimeException here = new RuntimeException("here");
7659                        here.fillInStackTrace();
7660                        Slog.d(TAG, "Sending to user " + id + ": "
7661                                + intent.toShortString(false, true, false, false)
7662                                + " " + intent.getExtras(), here);
7663                    }
7664                    am.broadcastIntent(null, intent, null, finishedReceiver,
7665                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7666                            finishedReceiver != null, false, id);
7667                }
7668            } catch (RemoteException ex) {
7669            }
7670        }
7671    }
7672
7673    /**
7674     * Check if the external storage media is available. This is true if there
7675     * is a mounted external storage medium or if the external storage is
7676     * emulated.
7677     */
7678    private boolean isExternalMediaAvailable() {
7679        return mMediaMounted || Environment.isExternalStorageEmulated();
7680    }
7681
7682    @Override
7683    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7684        // writer
7685        synchronized (mPackages) {
7686            if (!isExternalMediaAvailable()) {
7687                // If the external storage is no longer mounted at this point,
7688                // the caller may not have been able to delete all of this
7689                // packages files and can not delete any more.  Bail.
7690                return null;
7691            }
7692            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7693            if (lastPackage != null) {
7694                pkgs.remove(lastPackage);
7695            }
7696            if (pkgs.size() > 0) {
7697                return pkgs.get(0);
7698            }
7699        }
7700        return null;
7701    }
7702
7703    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7704        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7705                userId, andCode ? 1 : 0, packageName);
7706        if (mSystemReady) {
7707            msg.sendToTarget();
7708        } else {
7709            if (mPostSystemReadyMessages == null) {
7710                mPostSystemReadyMessages = new ArrayList<>();
7711            }
7712            mPostSystemReadyMessages.add(msg);
7713        }
7714    }
7715
7716    void startCleaningPackages() {
7717        // reader
7718        synchronized (mPackages) {
7719            if (!isExternalMediaAvailable()) {
7720                return;
7721            }
7722            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7723                return;
7724            }
7725        }
7726        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7727        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7728        IActivityManager am = ActivityManagerNative.getDefault();
7729        if (am != null) {
7730            try {
7731                am.startService(null, intent, null, UserHandle.USER_OWNER);
7732            } catch (RemoteException e) {
7733            }
7734        }
7735    }
7736
7737    @Override
7738    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7739            int installFlags, String installerPackageName, VerificationParams verificationParams,
7740            String packageAbiOverride) {
7741        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7742                packageAbiOverride, UserHandle.getCallingUserId());
7743    }
7744
7745    @Override
7746    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7747            int installFlags, String installerPackageName, VerificationParams verificationParams,
7748            String packageAbiOverride, int userId) {
7749        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
7750
7751        final int callingUid = Binder.getCallingUid();
7752        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
7753
7754        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7755            try {
7756                if (observer != null) {
7757                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7758                }
7759            } catch (RemoteException re) {
7760            }
7761            return;
7762        }
7763
7764        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
7765            installFlags |= PackageManager.INSTALL_FROM_ADB;
7766
7767        } else {
7768            // Caller holds INSTALL_PACKAGES permission, so we're less strict
7769            // about installerPackageName.
7770
7771            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
7772            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
7773        }
7774
7775        UserHandle user;
7776        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7777            user = UserHandle.ALL;
7778        } else {
7779            user = new UserHandle(userId);
7780        }
7781
7782        verificationParams.setInstallerUid(callingUid);
7783
7784        final File originFile = new File(originPath);
7785        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7786
7787        final Message msg = mHandler.obtainMessage(INIT_COPY);
7788        msg.obj = new InstallParams(origin, observer, installFlags,
7789                installerPackageName, verificationParams, user, packageAbiOverride);
7790        mHandler.sendMessage(msg);
7791    }
7792
7793    void installStage(String packageName, File stagedDir, String stagedCid,
7794            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7795            String installerPackageName, int installerUid, UserHandle user) {
7796        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7797                params.referrerUri, installerUid, null);
7798
7799        final OriginInfo origin;
7800        if (stagedDir != null) {
7801            origin = OriginInfo.fromStagedFile(stagedDir);
7802        } else {
7803            origin = OriginInfo.fromStagedContainer(stagedCid);
7804        }
7805
7806        final Message msg = mHandler.obtainMessage(INIT_COPY);
7807        msg.obj = new InstallParams(origin, observer, params.installFlags,
7808                installerPackageName, verifParams, user, params.abiOverride);
7809        mHandler.sendMessage(msg);
7810    }
7811
7812    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7813        Bundle extras = new Bundle(1);
7814        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7815
7816        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7817                packageName, extras, null, null, new int[] {userId});
7818        try {
7819            IActivityManager am = ActivityManagerNative.getDefault();
7820            final boolean isSystem =
7821                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7822            if (isSystem && am.isUserRunning(userId, false)) {
7823                // The just-installed/enabled app is bundled on the system, so presumed
7824                // to be able to run automatically without needing an explicit launch.
7825                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7826                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7827                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7828                        .setPackage(packageName);
7829                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7830                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7831            }
7832        } catch (RemoteException e) {
7833            // shouldn't happen
7834            Slog.w(TAG, "Unable to bootstrap installed package", e);
7835        }
7836    }
7837
7838    @Override
7839    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7840            int userId) {
7841        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7842        PackageSetting pkgSetting;
7843        final int uid = Binder.getCallingUid();
7844        enforceCrossUserPermission(uid, userId, true, true,
7845                "setApplicationHiddenSetting for user " + userId);
7846
7847        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7848            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7849            return false;
7850        }
7851
7852        long callingId = Binder.clearCallingIdentity();
7853        try {
7854            boolean sendAdded = false;
7855            boolean sendRemoved = false;
7856            // writer
7857            synchronized (mPackages) {
7858                pkgSetting = mSettings.mPackages.get(packageName);
7859                if (pkgSetting == null) {
7860                    return false;
7861                }
7862                if (pkgSetting.getHidden(userId) != hidden) {
7863                    pkgSetting.setHidden(hidden, userId);
7864                    mSettings.writePackageRestrictionsLPr(userId);
7865                    if (hidden) {
7866                        sendRemoved = true;
7867                    } else {
7868                        sendAdded = true;
7869                    }
7870                }
7871            }
7872            if (sendAdded) {
7873                sendPackageAddedForUser(packageName, pkgSetting, userId);
7874                return true;
7875            }
7876            if (sendRemoved) {
7877                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7878                        "hiding pkg");
7879                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7880            }
7881        } finally {
7882            Binder.restoreCallingIdentity(callingId);
7883        }
7884        return false;
7885    }
7886
7887    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7888            int userId) {
7889        final PackageRemovedInfo info = new PackageRemovedInfo();
7890        info.removedPackage = packageName;
7891        info.removedUsers = new int[] {userId};
7892        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7893        info.sendBroadcast(false, false, false);
7894    }
7895
7896    /**
7897     * Returns true if application is not found or there was an error. Otherwise it returns
7898     * the hidden state of the package for the given user.
7899     */
7900    @Override
7901    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7902        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7903        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7904                false, "getApplicationHidden for user " + userId);
7905        PackageSetting pkgSetting;
7906        long callingId = Binder.clearCallingIdentity();
7907        try {
7908            // writer
7909            synchronized (mPackages) {
7910                pkgSetting = mSettings.mPackages.get(packageName);
7911                if (pkgSetting == null) {
7912                    return true;
7913                }
7914                return pkgSetting.getHidden(userId);
7915            }
7916        } finally {
7917            Binder.restoreCallingIdentity(callingId);
7918        }
7919    }
7920
7921    /**
7922     * @hide
7923     */
7924    @Override
7925    public int installExistingPackageAsUser(String packageName, int userId) {
7926        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7927                null);
7928        PackageSetting pkgSetting;
7929        final int uid = Binder.getCallingUid();
7930        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
7931                + userId);
7932        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7933            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7934        }
7935
7936        long callingId = Binder.clearCallingIdentity();
7937        try {
7938            boolean sendAdded = false;
7939            Bundle extras = new Bundle(1);
7940
7941            // writer
7942            synchronized (mPackages) {
7943                pkgSetting = mSettings.mPackages.get(packageName);
7944                if (pkgSetting == null) {
7945                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7946                }
7947                if (!pkgSetting.getInstalled(userId)) {
7948                    pkgSetting.setInstalled(true, userId);
7949                    pkgSetting.setHidden(false, userId);
7950                    mSettings.writePackageRestrictionsLPr(userId);
7951                    sendAdded = true;
7952                }
7953            }
7954
7955            if (sendAdded) {
7956                sendPackageAddedForUser(packageName, pkgSetting, userId);
7957            }
7958        } finally {
7959            Binder.restoreCallingIdentity(callingId);
7960        }
7961
7962        return PackageManager.INSTALL_SUCCEEDED;
7963    }
7964
7965    boolean isUserRestricted(int userId, String restrictionKey) {
7966        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7967        if (restrictions.getBoolean(restrictionKey, false)) {
7968            Log.w(TAG, "User is restricted: " + restrictionKey);
7969            return true;
7970        }
7971        return false;
7972    }
7973
7974    @Override
7975    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7976        mContext.enforceCallingOrSelfPermission(
7977                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7978                "Only package verification agents can verify applications");
7979
7980        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7981        final PackageVerificationResponse response = new PackageVerificationResponse(
7982                verificationCode, Binder.getCallingUid());
7983        msg.arg1 = id;
7984        msg.obj = response;
7985        mHandler.sendMessage(msg);
7986    }
7987
7988    @Override
7989    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7990            long millisecondsToDelay) {
7991        mContext.enforceCallingOrSelfPermission(
7992                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7993                "Only package verification agents can extend verification timeouts");
7994
7995        final PackageVerificationState state = mPendingVerification.get(id);
7996        final PackageVerificationResponse response = new PackageVerificationResponse(
7997                verificationCodeAtTimeout, Binder.getCallingUid());
7998
7999        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8000            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8001        }
8002        if (millisecondsToDelay < 0) {
8003            millisecondsToDelay = 0;
8004        }
8005        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8006                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8007            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8008        }
8009
8010        if ((state != null) && !state.timeoutExtended()) {
8011            state.extendTimeout();
8012
8013            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8014            msg.arg1 = id;
8015            msg.obj = response;
8016            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8017        }
8018    }
8019
8020    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8021            int verificationCode, UserHandle user) {
8022        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8023        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8024        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8025        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8026        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8027
8028        mContext.sendBroadcastAsUser(intent, user,
8029                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8030    }
8031
8032    private ComponentName matchComponentForVerifier(String packageName,
8033            List<ResolveInfo> receivers) {
8034        ActivityInfo targetReceiver = null;
8035
8036        final int NR = receivers.size();
8037        for (int i = 0; i < NR; i++) {
8038            final ResolveInfo info = receivers.get(i);
8039            if (info.activityInfo == null) {
8040                continue;
8041            }
8042
8043            if (packageName.equals(info.activityInfo.packageName)) {
8044                targetReceiver = info.activityInfo;
8045                break;
8046            }
8047        }
8048
8049        if (targetReceiver == null) {
8050            return null;
8051        }
8052
8053        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8054    }
8055
8056    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8057            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8058        if (pkgInfo.verifiers.length == 0) {
8059            return null;
8060        }
8061
8062        final int N = pkgInfo.verifiers.length;
8063        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8064        for (int i = 0; i < N; i++) {
8065            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8066
8067            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8068                    receivers);
8069            if (comp == null) {
8070                continue;
8071            }
8072
8073            final int verifierUid = getUidForVerifier(verifierInfo);
8074            if (verifierUid == -1) {
8075                continue;
8076            }
8077
8078            if (DEBUG_VERIFY) {
8079                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8080                        + " with the correct signature");
8081            }
8082            sufficientVerifiers.add(comp);
8083            verificationState.addSufficientVerifier(verifierUid);
8084        }
8085
8086        return sufficientVerifiers;
8087    }
8088
8089    private int getUidForVerifier(VerifierInfo verifierInfo) {
8090        synchronized (mPackages) {
8091            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8092            if (pkg == null) {
8093                return -1;
8094            } else if (pkg.mSignatures.length != 1) {
8095                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8096                        + " has more than one signature; ignoring");
8097                return -1;
8098            }
8099
8100            /*
8101             * If the public key of the package's signature does not match
8102             * our expected public key, then this is a different package and
8103             * we should skip.
8104             */
8105
8106            final byte[] expectedPublicKey;
8107            try {
8108                final Signature verifierSig = pkg.mSignatures[0];
8109                final PublicKey publicKey = verifierSig.getPublicKey();
8110                expectedPublicKey = publicKey.getEncoded();
8111            } catch (CertificateException e) {
8112                return -1;
8113            }
8114
8115            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8116
8117            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8118                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8119                        + " does not have the expected public key; ignoring");
8120                return -1;
8121            }
8122
8123            return pkg.applicationInfo.uid;
8124        }
8125    }
8126
8127    @Override
8128    public void finishPackageInstall(int token) {
8129        enforceSystemOrRoot("Only the system is allowed to finish installs");
8130
8131        if (DEBUG_INSTALL) {
8132            Slog.v(TAG, "BM finishing package install for " + token);
8133        }
8134
8135        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8136        mHandler.sendMessage(msg);
8137    }
8138
8139    /**
8140     * Get the verification agent timeout.
8141     *
8142     * @return verification timeout in milliseconds
8143     */
8144    private long getVerificationTimeout() {
8145        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8146                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8147                DEFAULT_VERIFICATION_TIMEOUT);
8148    }
8149
8150    /**
8151     * Get the default verification agent response code.
8152     *
8153     * @return default verification response code
8154     */
8155    private int getDefaultVerificationResponse() {
8156        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8157                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8158                DEFAULT_VERIFICATION_RESPONSE);
8159    }
8160
8161    /**
8162     * Check whether or not package verification has been enabled.
8163     *
8164     * @return true if verification should be performed
8165     */
8166    private boolean isVerificationEnabled(int userId, int installFlags) {
8167        if (!DEFAULT_VERIFY_ENABLE) {
8168            return false;
8169        }
8170
8171        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8172
8173        // Check if installing from ADB
8174        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8175            // Do not run verification in a test harness environment
8176            if (ActivityManager.isRunningInTestHarness()) {
8177                return false;
8178            }
8179            if (ensureVerifyAppsEnabled) {
8180                return true;
8181            }
8182            // Check if the developer does not want package verification for ADB installs
8183            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8184                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8185                return false;
8186            }
8187        }
8188
8189        if (ensureVerifyAppsEnabled) {
8190            return true;
8191        }
8192
8193        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8194                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8195    }
8196
8197    /**
8198     * Get the "allow unknown sources" setting.
8199     *
8200     * @return the current "allow unknown sources" setting
8201     */
8202    private int getUnknownSourcesSettings() {
8203        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8204                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8205                -1);
8206    }
8207
8208    @Override
8209    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8210        final int uid = Binder.getCallingUid();
8211        // writer
8212        synchronized (mPackages) {
8213            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8214            if (targetPackageSetting == null) {
8215                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8216            }
8217
8218            PackageSetting installerPackageSetting;
8219            if (installerPackageName != null) {
8220                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8221                if (installerPackageSetting == null) {
8222                    throw new IllegalArgumentException("Unknown installer package: "
8223                            + installerPackageName);
8224                }
8225            } else {
8226                installerPackageSetting = null;
8227            }
8228
8229            Signature[] callerSignature;
8230            Object obj = mSettings.getUserIdLPr(uid);
8231            if (obj != null) {
8232                if (obj instanceof SharedUserSetting) {
8233                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8234                } else if (obj instanceof PackageSetting) {
8235                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8236                } else {
8237                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8238                }
8239            } else {
8240                throw new SecurityException("Unknown calling uid " + uid);
8241            }
8242
8243            // Verify: can't set installerPackageName to a package that is
8244            // not signed with the same cert as the caller.
8245            if (installerPackageSetting != null) {
8246                if (compareSignatures(callerSignature,
8247                        installerPackageSetting.signatures.mSignatures)
8248                        != PackageManager.SIGNATURE_MATCH) {
8249                    throw new SecurityException(
8250                            "Caller does not have same cert as new installer package "
8251                            + installerPackageName);
8252                }
8253            }
8254
8255            // Verify: if target already has an installer package, it must
8256            // be signed with the same cert as the caller.
8257            if (targetPackageSetting.installerPackageName != null) {
8258                PackageSetting setting = mSettings.mPackages.get(
8259                        targetPackageSetting.installerPackageName);
8260                // If the currently set package isn't valid, then it's always
8261                // okay to change it.
8262                if (setting != null) {
8263                    if (compareSignatures(callerSignature,
8264                            setting.signatures.mSignatures)
8265                            != PackageManager.SIGNATURE_MATCH) {
8266                        throw new SecurityException(
8267                                "Caller does not have same cert as old installer package "
8268                                + targetPackageSetting.installerPackageName);
8269                    }
8270                }
8271            }
8272
8273            // Okay!
8274            targetPackageSetting.installerPackageName = installerPackageName;
8275            scheduleWriteSettingsLocked();
8276        }
8277    }
8278
8279    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8280        // Queue up an async operation since the package installation may take a little while.
8281        mHandler.post(new Runnable() {
8282            public void run() {
8283                mHandler.removeCallbacks(this);
8284                 // Result object to be returned
8285                PackageInstalledInfo res = new PackageInstalledInfo();
8286                res.returnCode = currentStatus;
8287                res.uid = -1;
8288                res.pkg = null;
8289                res.removedInfo = new PackageRemovedInfo();
8290                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8291                    args.doPreInstall(res.returnCode);
8292                    synchronized (mInstallLock) {
8293                        installPackageLI(args, res);
8294                    }
8295                    args.doPostInstall(res.returnCode, res.uid);
8296                }
8297
8298                // A restore should be performed at this point if (a) the install
8299                // succeeded, (b) the operation is not an update, and (c) the new
8300                // package has not opted out of backup participation.
8301                final boolean update = res.removedInfo.removedPackage != null;
8302                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8303                boolean doRestore = !update
8304                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8305
8306                // Set up the post-install work request bookkeeping.  This will be used
8307                // and cleaned up by the post-install event handling regardless of whether
8308                // there's a restore pass performed.  Token values are >= 1.
8309                int token;
8310                if (mNextInstallToken < 0) mNextInstallToken = 1;
8311                token = mNextInstallToken++;
8312
8313                PostInstallData data = new PostInstallData(args, res);
8314                mRunningInstalls.put(token, data);
8315                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8316
8317                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8318                    // Pass responsibility to the Backup Manager.  It will perform a
8319                    // restore if appropriate, then pass responsibility back to the
8320                    // Package Manager to run the post-install observer callbacks
8321                    // and broadcasts.
8322                    IBackupManager bm = IBackupManager.Stub.asInterface(
8323                            ServiceManager.getService(Context.BACKUP_SERVICE));
8324                    if (bm != null) {
8325                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8326                                + " to BM for possible restore");
8327                        try {
8328                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8329                        } catch (RemoteException e) {
8330                            // can't happen; the backup manager is local
8331                        } catch (Exception e) {
8332                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8333                            doRestore = false;
8334                        }
8335                    } else {
8336                        Slog.e(TAG, "Backup Manager not found!");
8337                        doRestore = false;
8338                    }
8339                }
8340
8341                if (!doRestore) {
8342                    // No restore possible, or the Backup Manager was mysteriously not
8343                    // available -- just fire the post-install work request directly.
8344                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8345                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8346                    mHandler.sendMessage(msg);
8347                }
8348            }
8349        });
8350    }
8351
8352    private abstract class HandlerParams {
8353        private static final int MAX_RETRIES = 4;
8354
8355        /**
8356         * Number of times startCopy() has been attempted and had a non-fatal
8357         * error.
8358         */
8359        private int mRetries = 0;
8360
8361        /** User handle for the user requesting the information or installation. */
8362        private final UserHandle mUser;
8363
8364        HandlerParams(UserHandle user) {
8365            mUser = user;
8366        }
8367
8368        UserHandle getUser() {
8369            return mUser;
8370        }
8371
8372        final boolean startCopy() {
8373            boolean res;
8374            try {
8375                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8376
8377                if (++mRetries > MAX_RETRIES) {
8378                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8379                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8380                    handleServiceError();
8381                    return false;
8382                } else {
8383                    handleStartCopy();
8384                    res = true;
8385                }
8386            } catch (RemoteException e) {
8387                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8388                mHandler.sendEmptyMessage(MCS_RECONNECT);
8389                res = false;
8390            }
8391            handleReturnCode();
8392            return res;
8393        }
8394
8395        final void serviceError() {
8396            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8397            handleServiceError();
8398            handleReturnCode();
8399        }
8400
8401        abstract void handleStartCopy() throws RemoteException;
8402        abstract void handleServiceError();
8403        abstract void handleReturnCode();
8404    }
8405
8406    class MeasureParams extends HandlerParams {
8407        private final PackageStats mStats;
8408        private boolean mSuccess;
8409
8410        private final IPackageStatsObserver mObserver;
8411
8412        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8413            super(new UserHandle(stats.userHandle));
8414            mObserver = observer;
8415            mStats = stats;
8416        }
8417
8418        @Override
8419        public String toString() {
8420            return "MeasureParams{"
8421                + Integer.toHexString(System.identityHashCode(this))
8422                + " " + mStats.packageName + "}";
8423        }
8424
8425        @Override
8426        void handleStartCopy() throws RemoteException {
8427            synchronized (mInstallLock) {
8428                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8429            }
8430
8431            if (mSuccess) {
8432                final boolean mounted;
8433                if (Environment.isExternalStorageEmulated()) {
8434                    mounted = true;
8435                } else {
8436                    final String status = Environment.getExternalStorageState();
8437                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8438                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8439                }
8440
8441                if (mounted) {
8442                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8443
8444                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8445                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8446
8447                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8448                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8449
8450                    // Always subtract cache size, since it's a subdirectory
8451                    mStats.externalDataSize -= mStats.externalCacheSize;
8452
8453                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8454                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8455
8456                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8457                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8458                }
8459            }
8460        }
8461
8462        @Override
8463        void handleReturnCode() {
8464            if (mObserver != null) {
8465                try {
8466                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8467                } catch (RemoteException e) {
8468                    Slog.i(TAG, "Observer no longer exists.");
8469                }
8470            }
8471        }
8472
8473        @Override
8474        void handleServiceError() {
8475            Slog.e(TAG, "Could not measure application " + mStats.packageName
8476                            + " external storage");
8477        }
8478    }
8479
8480    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8481            throws RemoteException {
8482        long result = 0;
8483        for (File path : paths) {
8484            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8485        }
8486        return result;
8487    }
8488
8489    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8490        for (File path : paths) {
8491            try {
8492                mcs.clearDirectory(path.getAbsolutePath());
8493            } catch (RemoteException e) {
8494            }
8495        }
8496    }
8497
8498    static class OriginInfo {
8499        /**
8500         * Location where install is coming from, before it has been
8501         * copied/renamed into place. This could be a single monolithic APK
8502         * file, or a cluster directory. This location may be untrusted.
8503         */
8504        final File file;
8505        final String cid;
8506
8507        /**
8508         * Flag indicating that {@link #file} or {@link #cid} has already been
8509         * staged, meaning downstream users don't need to defensively copy the
8510         * contents.
8511         */
8512        final boolean staged;
8513
8514        /**
8515         * Flag indicating that {@link #file} or {@link #cid} is an already
8516         * installed app that is being moved.
8517         */
8518        final boolean existing;
8519
8520        final String resolvedPath;
8521        final File resolvedFile;
8522
8523        static OriginInfo fromNothing() {
8524            return new OriginInfo(null, null, false, false);
8525        }
8526
8527        static OriginInfo fromUntrustedFile(File file) {
8528            return new OriginInfo(file, null, false, false);
8529        }
8530
8531        static OriginInfo fromExistingFile(File file) {
8532            return new OriginInfo(file, null, false, true);
8533        }
8534
8535        static OriginInfo fromStagedFile(File file) {
8536            return new OriginInfo(file, null, true, false);
8537        }
8538
8539        static OriginInfo fromStagedContainer(String cid) {
8540            return new OriginInfo(null, cid, true, false);
8541        }
8542
8543        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8544            this.file = file;
8545            this.cid = cid;
8546            this.staged = staged;
8547            this.existing = existing;
8548
8549            if (cid != null) {
8550                resolvedPath = PackageHelper.getSdDir(cid);
8551                resolvedFile = new File(resolvedPath);
8552            } else if (file != null) {
8553                resolvedPath = file.getAbsolutePath();
8554                resolvedFile = file;
8555            } else {
8556                resolvedPath = null;
8557                resolvedFile = null;
8558            }
8559        }
8560    }
8561
8562    class InstallParams extends HandlerParams {
8563        final OriginInfo origin;
8564        final IPackageInstallObserver2 observer;
8565        int installFlags;
8566        final String installerPackageName;
8567        final VerificationParams verificationParams;
8568        private InstallArgs mArgs;
8569        private int mRet;
8570        final String packageAbiOverride;
8571
8572        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8573                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8574                String packageAbiOverride) {
8575            super(user);
8576            this.origin = origin;
8577            this.observer = observer;
8578            this.installFlags = installFlags;
8579            this.installerPackageName = installerPackageName;
8580            this.verificationParams = verificationParams;
8581            this.packageAbiOverride = packageAbiOverride;
8582        }
8583
8584        @Override
8585        public String toString() {
8586            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8587                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8588        }
8589
8590        public ManifestDigest getManifestDigest() {
8591            if (verificationParams == null) {
8592                return null;
8593            }
8594            return verificationParams.getManifestDigest();
8595        }
8596
8597        private int installLocationPolicy(PackageInfoLite pkgLite) {
8598            String packageName = pkgLite.packageName;
8599            int installLocation = pkgLite.installLocation;
8600            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8601            // reader
8602            synchronized (mPackages) {
8603                PackageParser.Package pkg = mPackages.get(packageName);
8604                if (pkg != null) {
8605                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8606                        // Check for downgrading.
8607                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8608                            if (pkgLite.versionCode < pkg.mVersionCode) {
8609                                Slog.w(TAG, "Can't install update of " + packageName
8610                                        + " update version " + pkgLite.versionCode
8611                                        + " is older than installed version "
8612                                        + pkg.mVersionCode);
8613                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8614                            }
8615                        }
8616                        // Check for updated system application.
8617                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8618                            if (onSd) {
8619                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8620                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8621                            }
8622                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8623                        } else {
8624                            if (onSd) {
8625                                // Install flag overrides everything.
8626                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8627                            }
8628                            // If current upgrade specifies particular preference
8629                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8630                                // Application explicitly specified internal.
8631                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8632                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8633                                // App explictly prefers external. Let policy decide
8634                            } else {
8635                                // Prefer previous location
8636                                if (isExternal(pkg)) {
8637                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8638                                }
8639                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8640                            }
8641                        }
8642                    } else {
8643                        // Invalid install. Return error code
8644                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8645                    }
8646                }
8647            }
8648            // All the special cases have been taken care of.
8649            // Return result based on recommended install location.
8650            if (onSd) {
8651                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8652            }
8653            return pkgLite.recommendedInstallLocation;
8654        }
8655
8656        /*
8657         * Invoke remote method to get package information and install
8658         * location values. Override install location based on default
8659         * policy if needed and then create install arguments based
8660         * on the install location.
8661         */
8662        public void handleStartCopy() throws RemoteException {
8663            int ret = PackageManager.INSTALL_SUCCEEDED;
8664
8665            // If we're already staged, we've firmly committed to an install location
8666            if (origin.staged) {
8667                if (origin.file != null) {
8668                    installFlags |= PackageManager.INSTALL_INTERNAL;
8669                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8670                } else if (origin.cid != null) {
8671                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8672                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8673                } else {
8674                    throw new IllegalStateException("Invalid stage location");
8675                }
8676            }
8677
8678            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8679            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8680
8681            PackageInfoLite pkgLite = null;
8682
8683            if (onInt && onSd) {
8684                // Check if both bits are set.
8685                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8686                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8687            } else {
8688                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8689                        packageAbiOverride);
8690
8691                /*
8692                 * If we have too little free space, try to free cache
8693                 * before giving up.
8694                 */
8695                if (!origin.staged && pkgLite.recommendedInstallLocation
8696                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8697                    // TODO: focus freeing disk space on the target device
8698                    final StorageManager storage = StorageManager.from(mContext);
8699                    final long lowThreshold = storage.getStorageLowBytes(
8700                            Environment.getDataDirectory());
8701
8702                    final long sizeBytes = mContainerService.calculateInstalledSize(
8703                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8704
8705                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8706                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8707                                installFlags, packageAbiOverride);
8708                    }
8709
8710                    /*
8711                     * The cache free must have deleted the file we
8712                     * downloaded to install.
8713                     *
8714                     * TODO: fix the "freeCache" call to not delete
8715                     *       the file we care about.
8716                     */
8717                    if (pkgLite.recommendedInstallLocation
8718                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8719                        pkgLite.recommendedInstallLocation
8720                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8721                    }
8722                }
8723            }
8724
8725            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8726                int loc = pkgLite.recommendedInstallLocation;
8727                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8728                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8729                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8730                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8731                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8732                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8733                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8734                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8735                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8736                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8737                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8738                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8739                } else {
8740                    // Override with defaults if needed.
8741                    loc = installLocationPolicy(pkgLite);
8742                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8743                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8744                    } else if (!onSd && !onInt) {
8745                        // Override install location with flags
8746                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8747                            // Set the flag to install on external media.
8748                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8749                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8750                        } else {
8751                            // Make sure the flag for installing on external
8752                            // media is unset
8753                            installFlags |= PackageManager.INSTALL_INTERNAL;
8754                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8755                        }
8756                    }
8757                }
8758            }
8759
8760            final InstallArgs args = createInstallArgs(this);
8761            mArgs = args;
8762
8763            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8764                 /*
8765                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8766                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8767                 */
8768                int userIdentifier = getUser().getIdentifier();
8769                if (userIdentifier == UserHandle.USER_ALL
8770                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8771                    userIdentifier = UserHandle.USER_OWNER;
8772                }
8773
8774                /*
8775                 * Determine if we have any installed package verifiers. If we
8776                 * do, then we'll defer to them to verify the packages.
8777                 */
8778                final int requiredUid = mRequiredVerifierPackage == null ? -1
8779                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8780                if (!origin.existing && requiredUid != -1
8781                        && isVerificationEnabled(userIdentifier, installFlags)) {
8782                    final Intent verification = new Intent(
8783                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8784                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8785                            PACKAGE_MIME_TYPE);
8786                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8787
8788                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8789                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8790                            0 /* TODO: Which userId? */);
8791
8792                    if (DEBUG_VERIFY) {
8793                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8794                                + verification.toString() + " with " + pkgLite.verifiers.length
8795                                + " optional verifiers");
8796                    }
8797
8798                    final int verificationId = mPendingVerificationToken++;
8799
8800                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8801
8802                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8803                            installerPackageName);
8804
8805                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8806                            installFlags);
8807
8808                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8809                            pkgLite.packageName);
8810
8811                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8812                            pkgLite.versionCode);
8813
8814                    if (verificationParams != null) {
8815                        if (verificationParams.getVerificationURI() != null) {
8816                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8817                                 verificationParams.getVerificationURI());
8818                        }
8819                        if (verificationParams.getOriginatingURI() != null) {
8820                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8821                                  verificationParams.getOriginatingURI());
8822                        }
8823                        if (verificationParams.getReferrer() != null) {
8824                            verification.putExtra(Intent.EXTRA_REFERRER,
8825                                  verificationParams.getReferrer());
8826                        }
8827                        if (verificationParams.getOriginatingUid() >= 0) {
8828                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8829                                  verificationParams.getOriginatingUid());
8830                        }
8831                        if (verificationParams.getInstallerUid() >= 0) {
8832                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8833                                  verificationParams.getInstallerUid());
8834                        }
8835                    }
8836
8837                    final PackageVerificationState verificationState = new PackageVerificationState(
8838                            requiredUid, args);
8839
8840                    mPendingVerification.append(verificationId, verificationState);
8841
8842                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8843                            receivers, verificationState);
8844
8845                    /*
8846                     * If any sufficient verifiers were listed in the package
8847                     * manifest, attempt to ask them.
8848                     */
8849                    if (sufficientVerifiers != null) {
8850                        final int N = sufficientVerifiers.size();
8851                        if (N == 0) {
8852                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8853                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8854                        } else {
8855                            for (int i = 0; i < N; i++) {
8856                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8857
8858                                final Intent sufficientIntent = new Intent(verification);
8859                                sufficientIntent.setComponent(verifierComponent);
8860
8861                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8862                            }
8863                        }
8864                    }
8865
8866                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8867                            mRequiredVerifierPackage, receivers);
8868                    if (ret == PackageManager.INSTALL_SUCCEEDED
8869                            && mRequiredVerifierPackage != null) {
8870                        /*
8871                         * Send the intent to the required verification agent,
8872                         * but only start the verification timeout after the
8873                         * target BroadcastReceivers have run.
8874                         */
8875                        verification.setComponent(requiredVerifierComponent);
8876                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8877                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8878                                new BroadcastReceiver() {
8879                                    @Override
8880                                    public void onReceive(Context context, Intent intent) {
8881                                        final Message msg = mHandler
8882                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8883                                        msg.arg1 = verificationId;
8884                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8885                                    }
8886                                }, null, 0, null, null);
8887
8888                        /*
8889                         * We don't want the copy to proceed until verification
8890                         * succeeds, so null out this field.
8891                         */
8892                        mArgs = null;
8893                    }
8894                } else {
8895                    /*
8896                     * No package verification is enabled, so immediately start
8897                     * the remote call to initiate copy using temporary file.
8898                     */
8899                    ret = args.copyApk(mContainerService, true);
8900                }
8901            }
8902
8903            mRet = ret;
8904        }
8905
8906        @Override
8907        void handleReturnCode() {
8908            // If mArgs is null, then MCS couldn't be reached. When it
8909            // reconnects, it will try again to install. At that point, this
8910            // will succeed.
8911            if (mArgs != null) {
8912                processPendingInstall(mArgs, mRet);
8913            }
8914        }
8915
8916        @Override
8917        void handleServiceError() {
8918            mArgs = createInstallArgs(this);
8919            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8920        }
8921
8922        public boolean isForwardLocked() {
8923            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8924        }
8925    }
8926
8927    /**
8928     * Used during creation of InstallArgs
8929     *
8930     * @param installFlags package installation flags
8931     * @return true if should be installed on external storage
8932     */
8933    private static boolean installOnSd(int installFlags) {
8934        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
8935            return false;
8936        }
8937        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
8938            return true;
8939        }
8940        return false;
8941    }
8942
8943    /**
8944     * Used during creation of InstallArgs
8945     *
8946     * @param installFlags package installation flags
8947     * @return true if should be installed as forward locked
8948     */
8949    private static boolean installForwardLocked(int installFlags) {
8950        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8951    }
8952
8953    private InstallArgs createInstallArgs(InstallParams params) {
8954        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
8955            return new AsecInstallArgs(params);
8956        } else {
8957            return new FileInstallArgs(params);
8958        }
8959    }
8960
8961    /**
8962     * Create args that describe an existing installed package. Typically used
8963     * when cleaning up old installs, or used as a move source.
8964     */
8965    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
8966            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
8967        final boolean isInAsec;
8968        if (installOnSd(installFlags)) {
8969            /* Apps on SD card are always in ASEC containers. */
8970            isInAsec = true;
8971        } else if (installForwardLocked(installFlags)
8972                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8973            /*
8974             * Forward-locked apps are only in ASEC containers if they're the
8975             * new style
8976             */
8977            isInAsec = true;
8978        } else {
8979            isInAsec = false;
8980        }
8981
8982        if (isInAsec) {
8983            return new AsecInstallArgs(codePath, instructionSets,
8984                    installOnSd(installFlags), installForwardLocked(installFlags));
8985        } else {
8986            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
8987                    instructionSets);
8988        }
8989    }
8990
8991    static abstract class InstallArgs {
8992        /** @see InstallParams#origin */
8993        final OriginInfo origin;
8994
8995        final IPackageInstallObserver2 observer;
8996        // Always refers to PackageManager flags only
8997        final int installFlags;
8998        final String installerPackageName;
8999        final ManifestDigest manifestDigest;
9000        final UserHandle user;
9001        final String abiOverride;
9002
9003        // The list of instruction sets supported by this app. This is currently
9004        // only used during the rmdex() phase to clean up resources. We can get rid of this
9005        // if we move dex files under the common app path.
9006        /* nullable */ String[] instructionSets;
9007
9008        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9009                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9010                String[] instructionSets, String abiOverride) {
9011            this.origin = origin;
9012            this.installFlags = installFlags;
9013            this.observer = observer;
9014            this.installerPackageName = installerPackageName;
9015            this.manifestDigest = manifestDigest;
9016            this.user = user;
9017            this.instructionSets = instructionSets;
9018            this.abiOverride = abiOverride;
9019        }
9020
9021        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9022        abstract int doPreInstall(int status);
9023
9024        /**
9025         * Rename package into final resting place. All paths on the given
9026         * scanned package should be updated to reflect the rename.
9027         */
9028        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9029        abstract int doPostInstall(int status, int uid);
9030
9031        /** @see PackageSettingBase#codePathString */
9032        abstract String getCodePath();
9033        /** @see PackageSettingBase#resourcePathString */
9034        abstract String getResourcePath();
9035        abstract String getLegacyNativeLibraryPath();
9036
9037        // Need installer lock especially for dex file removal.
9038        abstract void cleanUpResourcesLI();
9039        abstract boolean doPostDeleteLI(boolean delete);
9040        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9041
9042        /**
9043         * Called before the source arguments are copied. This is used mostly
9044         * for MoveParams when it needs to read the source file to put it in the
9045         * destination.
9046         */
9047        int doPreCopy() {
9048            return PackageManager.INSTALL_SUCCEEDED;
9049        }
9050
9051        /**
9052         * Called after the source arguments are copied. This is used mostly for
9053         * MoveParams when it needs to read the source file to put it in the
9054         * destination.
9055         *
9056         * @return
9057         */
9058        int doPostCopy(int uid) {
9059            return PackageManager.INSTALL_SUCCEEDED;
9060        }
9061
9062        protected boolean isFwdLocked() {
9063            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9064        }
9065
9066        protected boolean isExternal() {
9067            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9068        }
9069
9070        UserHandle getUser() {
9071            return user;
9072        }
9073    }
9074
9075    /**
9076     * Logic to handle installation of non-ASEC applications, including copying
9077     * and renaming logic.
9078     */
9079    class FileInstallArgs extends InstallArgs {
9080        private File codeFile;
9081        private File resourceFile;
9082        private File legacyNativeLibraryPath;
9083
9084        // Example topology:
9085        // /data/app/com.example/base.apk
9086        // /data/app/com.example/split_foo.apk
9087        // /data/app/com.example/lib/arm/libfoo.so
9088        // /data/app/com.example/lib/arm64/libfoo.so
9089        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9090
9091        /** New install */
9092        FileInstallArgs(InstallParams params) {
9093            super(params.origin, params.observer, params.installFlags,
9094                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9095                    null /* instruction sets */, params.packageAbiOverride);
9096            if (isFwdLocked()) {
9097                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9098            }
9099        }
9100
9101        /** Existing install */
9102        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9103                String[] instructionSets) {
9104            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9105            this.codeFile = (codePath != null) ? new File(codePath) : null;
9106            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9107            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9108                    new File(legacyNativeLibraryPath) : null;
9109        }
9110
9111        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9112            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9113                    isFwdLocked(), abiOverride);
9114
9115            final StorageManager storage = StorageManager.from(mContext);
9116            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9117        }
9118
9119        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9120            if (origin.staged) {
9121                Slog.d(TAG, origin.file + " already staged; skipping copy");
9122                codeFile = origin.file;
9123                resourceFile = origin.file;
9124                return PackageManager.INSTALL_SUCCEEDED;
9125            }
9126
9127            try {
9128                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9129                codeFile = tempDir;
9130                resourceFile = tempDir;
9131            } catch (IOException e) {
9132                Slog.w(TAG, "Failed to create copy file: " + e);
9133                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9134            }
9135
9136            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9137                @Override
9138                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9139                    if (!FileUtils.isValidExtFilename(name)) {
9140                        throw new IllegalArgumentException("Invalid filename: " + name);
9141                    }
9142                    try {
9143                        final File file = new File(codeFile, name);
9144                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9145                                O_RDWR | O_CREAT, 0644);
9146                        Os.chmod(file.getAbsolutePath(), 0644);
9147                        return new ParcelFileDescriptor(fd);
9148                    } catch (ErrnoException e) {
9149                        throw new RemoteException("Failed to open: " + e.getMessage());
9150                    }
9151                }
9152            };
9153
9154            int ret = PackageManager.INSTALL_SUCCEEDED;
9155            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9156            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9157                Slog.e(TAG, "Failed to copy package");
9158                return ret;
9159            }
9160
9161            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9162            NativeLibraryHelper.Handle handle = null;
9163            try {
9164                handle = NativeLibraryHelper.Handle.create(codeFile);
9165                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9166                        abiOverride);
9167            } catch (IOException e) {
9168                Slog.e(TAG, "Copying native libraries failed", e);
9169                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9170            } finally {
9171                IoUtils.closeQuietly(handle);
9172            }
9173
9174            return ret;
9175        }
9176
9177        int doPreInstall(int status) {
9178            if (status != PackageManager.INSTALL_SUCCEEDED) {
9179                cleanUp();
9180            }
9181            return status;
9182        }
9183
9184        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9185            if (status != PackageManager.INSTALL_SUCCEEDED) {
9186                cleanUp();
9187                return false;
9188            } else {
9189                final File beforeCodeFile = codeFile;
9190                final File afterCodeFile = getNextCodePath(pkg.packageName);
9191
9192                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9193                try {
9194                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9195                } catch (ErrnoException e) {
9196                    Slog.d(TAG, "Failed to rename", e);
9197                    return false;
9198                }
9199
9200                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9201                    Slog.d(TAG, "Failed to restorecon");
9202                    return false;
9203                }
9204
9205                // Reflect the rename internally
9206                codeFile = afterCodeFile;
9207                resourceFile = afterCodeFile;
9208
9209                // Reflect the rename in scanned details
9210                pkg.codePath = afterCodeFile.getAbsolutePath();
9211                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9212                        pkg.baseCodePath);
9213                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9214                        pkg.splitCodePaths);
9215
9216                // Reflect the rename in app info
9217                pkg.applicationInfo.setCodePath(pkg.codePath);
9218                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9219                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9220                pkg.applicationInfo.setResourcePath(pkg.codePath);
9221                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9222                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9223
9224                return true;
9225            }
9226        }
9227
9228        int doPostInstall(int status, int uid) {
9229            if (status != PackageManager.INSTALL_SUCCEEDED) {
9230                cleanUp();
9231            }
9232            return status;
9233        }
9234
9235        @Override
9236        String getCodePath() {
9237            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9238        }
9239
9240        @Override
9241        String getResourcePath() {
9242            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9243        }
9244
9245        @Override
9246        String getLegacyNativeLibraryPath() {
9247            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9248        }
9249
9250        private boolean cleanUp() {
9251            if (codeFile == null || !codeFile.exists()) {
9252                return false;
9253            }
9254
9255            if (codeFile.isDirectory()) {
9256                FileUtils.deleteContents(codeFile);
9257            }
9258            codeFile.delete();
9259
9260            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9261                resourceFile.delete();
9262            }
9263
9264            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9265                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9266                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9267                }
9268                legacyNativeLibraryPath.delete();
9269            }
9270
9271            return true;
9272        }
9273
9274        void cleanUpResourcesLI() {
9275            // Try enumerating all code paths before deleting
9276            List<String> allCodePaths = Collections.EMPTY_LIST;
9277            if (codeFile != null && codeFile.exists()) {
9278                try {
9279                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9280                    allCodePaths = pkg.getAllCodePaths();
9281                } catch (PackageParserException e) {
9282                    // Ignored; we tried our best
9283                }
9284            }
9285
9286            cleanUp();
9287
9288            if (!allCodePaths.isEmpty()) {
9289                if (instructionSets == null) {
9290                    throw new IllegalStateException("instructionSet == null");
9291                }
9292                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9293                for (String codePath : allCodePaths) {
9294                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9295                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9296                        if (retCode < 0) {
9297                            Slog.w(TAG, "Couldn't remove dex file for package: "
9298                                    + " at location " + codePath + ", retcode=" + retCode);
9299                            // we don't consider this to be a failure of the core package deletion
9300                        }
9301                    }
9302                }
9303            }
9304        }
9305
9306        boolean doPostDeleteLI(boolean delete) {
9307            // XXX err, shouldn't we respect the delete flag?
9308            cleanUpResourcesLI();
9309            return true;
9310        }
9311    }
9312
9313    private boolean isAsecExternal(String cid) {
9314        final String asecPath = PackageHelper.getSdFilesystem(cid);
9315        return !asecPath.startsWith(mAsecInternalPath);
9316    }
9317
9318    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9319            PackageManagerException {
9320        if (copyRet < 0) {
9321            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9322                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9323                throw new PackageManagerException(copyRet, message);
9324            }
9325        }
9326    }
9327
9328    /**
9329     * Extract the MountService "container ID" from the full code path of an
9330     * .apk.
9331     */
9332    static String cidFromCodePath(String fullCodePath) {
9333        int eidx = fullCodePath.lastIndexOf("/");
9334        String subStr1 = fullCodePath.substring(0, eidx);
9335        int sidx = subStr1.lastIndexOf("/");
9336        return subStr1.substring(sidx+1, eidx);
9337    }
9338
9339    /**
9340     * Logic to handle installation of ASEC applications, including copying and
9341     * renaming logic.
9342     */
9343    class AsecInstallArgs extends InstallArgs {
9344        static final String RES_FILE_NAME = "pkg.apk";
9345        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9346
9347        String cid;
9348        String packagePath;
9349        String resourcePath;
9350        String legacyNativeLibraryDir;
9351
9352        /** New install */
9353        AsecInstallArgs(InstallParams params) {
9354            super(params.origin, params.observer, params.installFlags,
9355                    params.installerPackageName, params.getManifestDigest(),
9356                    params.getUser(), null /* instruction sets */,
9357                    params.packageAbiOverride);
9358        }
9359
9360        /** Existing install */
9361        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9362                        boolean isExternal, boolean isForwardLocked) {
9363            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9364                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9365                    instructionSets, null);
9366            // Hackily pretend we're still looking at a full code path
9367            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9368                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9369            }
9370
9371            // Extract cid from fullCodePath
9372            int eidx = fullCodePath.lastIndexOf("/");
9373            String subStr1 = fullCodePath.substring(0, eidx);
9374            int sidx = subStr1.lastIndexOf("/");
9375            cid = subStr1.substring(sidx+1, eidx);
9376            setMountPath(subStr1);
9377        }
9378
9379        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9380            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9381                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9382                    instructionSets, null);
9383            this.cid = cid;
9384            setMountPath(PackageHelper.getSdDir(cid));
9385        }
9386
9387        void createCopyFile() {
9388            cid = mInstallerService.allocateExternalStageCidLegacy();
9389        }
9390
9391        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9392            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9393                    abiOverride);
9394
9395            final File target;
9396            if (isExternal()) {
9397                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9398            } else {
9399                target = Environment.getDataDirectory();
9400            }
9401
9402            final StorageManager storage = StorageManager.from(mContext);
9403            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9404        }
9405
9406        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9407            if (origin.staged) {
9408                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9409                cid = origin.cid;
9410                setMountPath(PackageHelper.getSdDir(cid));
9411                return PackageManager.INSTALL_SUCCEEDED;
9412            }
9413
9414            if (temp) {
9415                createCopyFile();
9416            } else {
9417                /*
9418                 * Pre-emptively destroy the container since it's destroyed if
9419                 * copying fails due to it existing anyway.
9420                 */
9421                PackageHelper.destroySdDir(cid);
9422            }
9423
9424            final String newMountPath = imcs.copyPackageToContainer(
9425                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9426                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9427
9428            if (newMountPath != null) {
9429                setMountPath(newMountPath);
9430                return PackageManager.INSTALL_SUCCEEDED;
9431            } else {
9432                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9433            }
9434        }
9435
9436        @Override
9437        String getCodePath() {
9438            return packagePath;
9439        }
9440
9441        @Override
9442        String getResourcePath() {
9443            return resourcePath;
9444        }
9445
9446        @Override
9447        String getLegacyNativeLibraryPath() {
9448            return legacyNativeLibraryDir;
9449        }
9450
9451        int doPreInstall(int status) {
9452            if (status != PackageManager.INSTALL_SUCCEEDED) {
9453                // Destroy container
9454                PackageHelper.destroySdDir(cid);
9455            } else {
9456                boolean mounted = PackageHelper.isContainerMounted(cid);
9457                if (!mounted) {
9458                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9459                            Process.SYSTEM_UID);
9460                    if (newMountPath != null) {
9461                        setMountPath(newMountPath);
9462                    } else {
9463                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9464                    }
9465                }
9466            }
9467            return status;
9468        }
9469
9470        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9471            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9472            String newMountPath = null;
9473            if (PackageHelper.isContainerMounted(cid)) {
9474                // Unmount the container
9475                if (!PackageHelper.unMountSdDir(cid)) {
9476                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9477                    return false;
9478                }
9479            }
9480            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9481                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9482                        " which might be stale. Will try to clean up.");
9483                // Clean up the stale container and proceed to recreate.
9484                if (!PackageHelper.destroySdDir(newCacheId)) {
9485                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9486                    return false;
9487                }
9488                // Successfully cleaned up stale container. Try to rename again.
9489                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9490                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9491                            + " inspite of cleaning it up.");
9492                    return false;
9493                }
9494            }
9495            if (!PackageHelper.isContainerMounted(newCacheId)) {
9496                Slog.w(TAG, "Mounting container " + newCacheId);
9497                newMountPath = PackageHelper.mountSdDir(newCacheId,
9498                        getEncryptKey(), Process.SYSTEM_UID);
9499            } else {
9500                newMountPath = PackageHelper.getSdDir(newCacheId);
9501            }
9502            if (newMountPath == null) {
9503                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9504                return false;
9505            }
9506            Log.i(TAG, "Succesfully renamed " + cid +
9507                    " to " + newCacheId +
9508                    " at new path: " + newMountPath);
9509            cid = newCacheId;
9510
9511            final File beforeCodeFile = new File(packagePath);
9512            setMountPath(newMountPath);
9513            final File afterCodeFile = new File(packagePath);
9514
9515            // Reflect the rename in scanned details
9516            pkg.codePath = afterCodeFile.getAbsolutePath();
9517            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9518                    pkg.baseCodePath);
9519            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9520                    pkg.splitCodePaths);
9521
9522            // Reflect the rename in app info
9523            pkg.applicationInfo.setCodePath(pkg.codePath);
9524            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9525            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9526            pkg.applicationInfo.setResourcePath(pkg.codePath);
9527            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9528            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9529
9530            return true;
9531        }
9532
9533        private void setMountPath(String mountPath) {
9534            final File mountFile = new File(mountPath);
9535
9536            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9537            if (monolithicFile.exists()) {
9538                packagePath = monolithicFile.getAbsolutePath();
9539                if (isFwdLocked()) {
9540                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9541                } else {
9542                    resourcePath = packagePath;
9543                }
9544            } else {
9545                packagePath = mountFile.getAbsolutePath();
9546                resourcePath = packagePath;
9547            }
9548
9549            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9550        }
9551
9552        int doPostInstall(int status, int uid) {
9553            if (status != PackageManager.INSTALL_SUCCEEDED) {
9554                cleanUp();
9555            } else {
9556                final int groupOwner;
9557                final String protectedFile;
9558                if (isFwdLocked()) {
9559                    groupOwner = UserHandle.getSharedAppGid(uid);
9560                    protectedFile = RES_FILE_NAME;
9561                } else {
9562                    groupOwner = -1;
9563                    protectedFile = null;
9564                }
9565
9566                if (uid < Process.FIRST_APPLICATION_UID
9567                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9568                    Slog.e(TAG, "Failed to finalize " + cid);
9569                    PackageHelper.destroySdDir(cid);
9570                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9571                }
9572
9573                boolean mounted = PackageHelper.isContainerMounted(cid);
9574                if (!mounted) {
9575                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9576                }
9577            }
9578            return status;
9579        }
9580
9581        private void cleanUp() {
9582            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9583
9584            // Destroy secure container
9585            PackageHelper.destroySdDir(cid);
9586        }
9587
9588        private List<String> getAllCodePaths() {
9589            final File codeFile = new File(getCodePath());
9590            if (codeFile != null && codeFile.exists()) {
9591                try {
9592                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9593                    return pkg.getAllCodePaths();
9594                } catch (PackageParserException e) {
9595                    // Ignored; we tried our best
9596                }
9597            }
9598            return Collections.EMPTY_LIST;
9599        }
9600
9601        void cleanUpResourcesLI() {
9602            // Enumerate all code paths before deleting
9603            cleanUpResourcesLI(getAllCodePaths());
9604        }
9605
9606        private void cleanUpResourcesLI(List<String> allCodePaths) {
9607            cleanUp();
9608
9609            if (!allCodePaths.isEmpty()) {
9610                if (instructionSets == null) {
9611                    throw new IllegalStateException("instructionSet == null");
9612                }
9613                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9614                for (String codePath : allCodePaths) {
9615                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9616                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9617                        if (retCode < 0) {
9618                            Slog.w(TAG, "Couldn't remove dex file for package: "
9619                                    + " at location " + codePath + ", retcode=" + retCode);
9620                            // we don't consider this to be a failure of the core package deletion
9621                        }
9622                    }
9623                }
9624            }
9625        }
9626
9627        boolean matchContainer(String app) {
9628            if (cid.startsWith(app)) {
9629                return true;
9630            }
9631            return false;
9632        }
9633
9634        String getPackageName() {
9635            return getAsecPackageName(cid);
9636        }
9637
9638        boolean doPostDeleteLI(boolean delete) {
9639            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9640            final List<String> allCodePaths = getAllCodePaths();
9641            boolean mounted = PackageHelper.isContainerMounted(cid);
9642            if (mounted) {
9643                // Unmount first
9644                if (PackageHelper.unMountSdDir(cid)) {
9645                    mounted = false;
9646                }
9647            }
9648            if (!mounted && delete) {
9649                cleanUpResourcesLI(allCodePaths);
9650            }
9651            return !mounted;
9652        }
9653
9654        @Override
9655        int doPreCopy() {
9656            if (isFwdLocked()) {
9657                if (!PackageHelper.fixSdPermissions(cid,
9658                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9659                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9660                }
9661            }
9662
9663            return PackageManager.INSTALL_SUCCEEDED;
9664        }
9665
9666        @Override
9667        int doPostCopy(int uid) {
9668            if (isFwdLocked()) {
9669                if (uid < Process.FIRST_APPLICATION_UID
9670                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9671                                RES_FILE_NAME)) {
9672                    Slog.e(TAG, "Failed to finalize " + cid);
9673                    PackageHelper.destroySdDir(cid);
9674                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9675                }
9676            }
9677
9678            return PackageManager.INSTALL_SUCCEEDED;
9679        }
9680    }
9681
9682    static String getAsecPackageName(String packageCid) {
9683        int idx = packageCid.lastIndexOf("-");
9684        if (idx == -1) {
9685            return packageCid;
9686        }
9687        return packageCid.substring(0, idx);
9688    }
9689
9690    // Utility method used to create code paths based on package name and available index.
9691    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9692        String idxStr = "";
9693        int idx = 1;
9694        // Fall back to default value of idx=1 if prefix is not
9695        // part of oldCodePath
9696        if (oldCodePath != null) {
9697            String subStr = oldCodePath;
9698            // Drop the suffix right away
9699            if (suffix != null && subStr.endsWith(suffix)) {
9700                subStr = subStr.substring(0, subStr.length() - suffix.length());
9701            }
9702            // If oldCodePath already contains prefix find out the
9703            // ending index to either increment or decrement.
9704            int sidx = subStr.lastIndexOf(prefix);
9705            if (sidx != -1) {
9706                subStr = subStr.substring(sidx + prefix.length());
9707                if (subStr != null) {
9708                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9709                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9710                    }
9711                    try {
9712                        idx = Integer.parseInt(subStr);
9713                        if (idx <= 1) {
9714                            idx++;
9715                        } else {
9716                            idx--;
9717                        }
9718                    } catch(NumberFormatException e) {
9719                    }
9720                }
9721            }
9722        }
9723        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9724        return prefix + idxStr;
9725    }
9726
9727    private File getNextCodePath(String packageName) {
9728        int suffix = 1;
9729        File result;
9730        do {
9731            result = new File(mAppInstallDir, packageName + "-" + suffix);
9732            suffix++;
9733        } while (result.exists());
9734        return result;
9735    }
9736
9737    // Utility method used to ignore ADD/REMOVE events
9738    // by directory observer.
9739    private static boolean ignoreCodePath(String fullPathStr) {
9740        String apkName = deriveCodePathName(fullPathStr);
9741        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9742        if (idx != -1 && ((idx+1) < apkName.length())) {
9743            // Make sure the package ends with a numeral
9744            String version = apkName.substring(idx+1);
9745            try {
9746                Integer.parseInt(version);
9747                return true;
9748            } catch (NumberFormatException e) {}
9749        }
9750        return false;
9751    }
9752
9753    // Utility method that returns the relative package path with respect
9754    // to the installation directory. Like say for /data/data/com.test-1.apk
9755    // string com.test-1 is returned.
9756    static String deriveCodePathName(String codePath) {
9757        if (codePath == null) {
9758            return null;
9759        }
9760        final File codeFile = new File(codePath);
9761        final String name = codeFile.getName();
9762        if (codeFile.isDirectory()) {
9763            return name;
9764        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9765            final int lastDot = name.lastIndexOf('.');
9766            return name.substring(0, lastDot);
9767        } else {
9768            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9769            return null;
9770        }
9771    }
9772
9773    class PackageInstalledInfo {
9774        String name;
9775        int uid;
9776        // The set of users that originally had this package installed.
9777        int[] origUsers;
9778        // The set of users that now have this package installed.
9779        int[] newUsers;
9780        PackageParser.Package pkg;
9781        int returnCode;
9782        String returnMsg;
9783        PackageRemovedInfo removedInfo;
9784
9785        public void setError(int code, String msg) {
9786            returnCode = code;
9787            returnMsg = msg;
9788            Slog.w(TAG, msg);
9789        }
9790
9791        public void setError(String msg, PackageParserException e) {
9792            returnCode = e.error;
9793            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9794            Slog.w(TAG, msg, e);
9795        }
9796
9797        public void setError(String msg, PackageManagerException e) {
9798            returnCode = e.error;
9799            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9800            Slog.w(TAG, msg, e);
9801        }
9802
9803        // In some error cases we want to convey more info back to the observer
9804        String origPackage;
9805        String origPermission;
9806    }
9807
9808    /*
9809     * Install a non-existing package.
9810     */
9811    private void installNewPackageLI(PackageParser.Package pkg,
9812            int parseFlags, int scanFlags, UserHandle user,
9813            String installerPackageName, PackageInstalledInfo res) {
9814        // Remember this for later, in case we need to rollback this install
9815        String pkgName = pkg.packageName;
9816
9817        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9818        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9819        synchronized(mPackages) {
9820            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9821                // A package with the same name is already installed, though
9822                // it has been renamed to an older name.  The package we
9823                // are trying to install should be installed as an update to
9824                // the existing one, but that has not been requested, so bail.
9825                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9826                        + " without first uninstalling package running as "
9827                        + mSettings.mRenamedPackages.get(pkgName));
9828                return;
9829            }
9830            if (mPackages.containsKey(pkgName)) {
9831                // Don't allow installation over an existing package with the same name.
9832                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9833                        + " without first uninstalling.");
9834                return;
9835            }
9836        }
9837
9838        try {
9839            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9840                    System.currentTimeMillis(), user);
9841
9842            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9843            // delete the partially installed application. the data directory will have to be
9844            // restored if it was already existing
9845            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9846                // remove package from internal structures.  Note that we want deletePackageX to
9847                // delete the package data and cache directories that it created in
9848                // scanPackageLocked, unless those directories existed before we even tried to
9849                // install.
9850                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9851                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9852                                res.removedInfo, true);
9853            }
9854
9855        } catch (PackageManagerException e) {
9856            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9857        }
9858    }
9859
9860    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9861        // Upgrade keysets are being used.  Determine if new package has a superset of the
9862        // required keys.
9863        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9864        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9865        for (int i = 0; i < upgradeKeySets.length; i++) {
9866            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9867            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9868                return true;
9869            }
9870        }
9871        return false;
9872    }
9873
9874    private void replacePackageLI(PackageParser.Package pkg,
9875            int parseFlags, int scanFlags, UserHandle user,
9876            String installerPackageName, PackageInstalledInfo res) {
9877        PackageParser.Package oldPackage;
9878        String pkgName = pkg.packageName;
9879        int[] allUsers;
9880        boolean[] perUserInstalled;
9881
9882        // First find the old package info and check signatures
9883        synchronized(mPackages) {
9884            oldPackage = mPackages.get(pkgName);
9885            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9886            PackageSetting ps = mSettings.mPackages.get(pkgName);
9887            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9888                // default to original signature matching
9889                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9890                    != PackageManager.SIGNATURE_MATCH) {
9891                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9892                            "New package has a different signature: " + pkgName);
9893                    return;
9894                }
9895            } else {
9896                if(!checkUpgradeKeySetLP(ps, pkg)) {
9897                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9898                            "New package not signed by keys specified by upgrade-keysets: "
9899                            + pkgName);
9900                    return;
9901                }
9902            }
9903
9904            // In case of rollback, remember per-user/profile install state
9905            allUsers = sUserManager.getUserIds();
9906            perUserInstalled = new boolean[allUsers.length];
9907            for (int i = 0; i < allUsers.length; i++) {
9908                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9909            }
9910        }
9911
9912        boolean sysPkg = (isSystemApp(oldPackage));
9913        if (sysPkg) {
9914            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9915                    user, allUsers, perUserInstalled, installerPackageName, res);
9916        } else {
9917            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9918                    user, allUsers, perUserInstalled, installerPackageName, res);
9919        }
9920    }
9921
9922    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9923            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9924            int[] allUsers, boolean[] perUserInstalled,
9925            String installerPackageName, PackageInstalledInfo res) {
9926        String pkgName = deletedPackage.packageName;
9927        boolean deletedPkg = true;
9928        boolean updatedSettings = false;
9929
9930        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9931                + deletedPackage);
9932        long origUpdateTime;
9933        if (pkg.mExtras != null) {
9934            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9935        } else {
9936            origUpdateTime = 0;
9937        }
9938
9939        // First delete the existing package while retaining the data directory
9940        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9941                res.removedInfo, true)) {
9942            // If the existing package wasn't successfully deleted
9943            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
9944            deletedPkg = false;
9945        } else {
9946            // Successfully deleted the old package; proceed with replace.
9947
9948            // If deleted package lived in a container, give users a chance to
9949            // relinquish resources before killing.
9950            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
9951                if (DEBUG_INSTALL) {
9952                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
9953                }
9954                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
9955                final ArrayList<String> pkgList = new ArrayList<String>(1);
9956                pkgList.add(deletedPackage.applicationInfo.packageName);
9957                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
9958            }
9959
9960            deleteCodeCacheDirsLI(pkgName);
9961            try {
9962                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
9963                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
9964                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9965                updatedSettings = true;
9966            } catch (PackageManagerException e) {
9967                res.setError("Package couldn't be installed in " + pkg.codePath, e);
9968            }
9969        }
9970
9971        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9972            // remove package from internal structures.  Note that we want deletePackageX to
9973            // delete the package data and cache directories that it created in
9974            // scanPackageLocked, unless those directories existed before we even tried to
9975            // install.
9976            if(updatedSettings) {
9977                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9978                deletePackageLI(
9979                        pkgName, null, true, allUsers, perUserInstalled,
9980                        PackageManager.DELETE_KEEP_DATA,
9981                                res.removedInfo, true);
9982            }
9983            // Since we failed to install the new package we need to restore the old
9984            // package that we deleted.
9985            if (deletedPkg) {
9986                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9987                File restoreFile = new File(deletedPackage.codePath);
9988                // Parse old package
9989                boolean oldOnSd = isExternal(deletedPackage);
9990                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9991                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9992                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9993                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
9994                try {
9995                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
9996                } catch (PackageManagerException e) {
9997                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
9998                            + e.getMessage());
9999                    return;
10000                }
10001                // Restore of old package succeeded. Update permissions.
10002                // writer
10003                synchronized (mPackages) {
10004                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10005                            UPDATE_PERMISSIONS_ALL);
10006                    // can downgrade to reader
10007                    mSettings.writeLPr();
10008                }
10009                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10010            }
10011        }
10012    }
10013
10014    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10015            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10016            int[] allUsers, boolean[] perUserInstalled,
10017            String installerPackageName, PackageInstalledInfo res) {
10018        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10019                + ", old=" + deletedPackage);
10020        boolean disabledSystem = false;
10021        boolean updatedSettings = false;
10022        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10023        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10024            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10025        }
10026        String packageName = deletedPackage.packageName;
10027        if (packageName == null) {
10028            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10029                    "Attempt to delete null packageName.");
10030            return;
10031        }
10032        PackageParser.Package oldPkg;
10033        PackageSetting oldPkgSetting;
10034        // reader
10035        synchronized (mPackages) {
10036            oldPkg = mPackages.get(packageName);
10037            oldPkgSetting = mSettings.mPackages.get(packageName);
10038            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10039                    (oldPkgSetting == null)) {
10040                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10041                        "Couldn't find package:" + packageName + " information");
10042                return;
10043            }
10044        }
10045
10046        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10047
10048        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10049        res.removedInfo.removedPackage = packageName;
10050        // Remove existing system package
10051        removePackageLI(oldPkgSetting, true);
10052        // writer
10053        synchronized (mPackages) {
10054            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10055            if (!disabledSystem && deletedPackage != null) {
10056                // We didn't need to disable the .apk as a current system package,
10057                // which means we are replacing another update that is already
10058                // installed.  We need to make sure to delete the older one's .apk.
10059                res.removedInfo.args = createInstallArgsForExisting(0,
10060                        deletedPackage.applicationInfo.getCodePath(),
10061                        deletedPackage.applicationInfo.getResourcePath(),
10062                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10063                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10064            } else {
10065                res.removedInfo.args = null;
10066            }
10067        }
10068
10069        // Successfully disabled the old package. Now proceed with re-installation
10070        deleteCodeCacheDirsLI(packageName);
10071
10072        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10073        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10074
10075        PackageParser.Package newPackage = null;
10076        try {
10077            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10078            if (newPackage.mExtras != null) {
10079                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10080                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10081                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10082
10083                // is the update attempting to change shared user? that isn't going to work...
10084                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10085                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10086                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10087                            + " to " + newPkgSetting.sharedUser);
10088                    updatedSettings = true;
10089                }
10090            }
10091
10092            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10093                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10094                updatedSettings = true;
10095            }
10096
10097        } catch (PackageManagerException e) {
10098            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10099        }
10100
10101        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10102            // Re installation failed. Restore old information
10103            // Remove new pkg information
10104            if (newPackage != null) {
10105                removeInstalledPackageLI(newPackage, true);
10106            }
10107            // Add back the old system package
10108            try {
10109                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10110            } catch (PackageManagerException e) {
10111                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10112            }
10113            // Restore the old system information in Settings
10114            synchronized (mPackages) {
10115                if (disabledSystem) {
10116                    mSettings.enableSystemPackageLPw(packageName);
10117                }
10118                if (updatedSettings) {
10119                    mSettings.setInstallerPackageName(packageName,
10120                            oldPkgSetting.installerPackageName);
10121                }
10122                mSettings.writeLPr();
10123            }
10124        }
10125    }
10126
10127    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10128            int[] allUsers, boolean[] perUserInstalled,
10129            PackageInstalledInfo res) {
10130        String pkgName = newPackage.packageName;
10131        synchronized (mPackages) {
10132            //write settings. the installStatus will be incomplete at this stage.
10133            //note that the new package setting would have already been
10134            //added to mPackages. It hasn't been persisted yet.
10135            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10136            mSettings.writeLPr();
10137        }
10138
10139        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10140
10141        synchronized (mPackages) {
10142            updatePermissionsLPw(newPackage.packageName, newPackage,
10143                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10144                            ? UPDATE_PERMISSIONS_ALL : 0));
10145            // For system-bundled packages, we assume that installing an upgraded version
10146            // of the package implies that the user actually wants to run that new code,
10147            // so we enable the package.
10148            if (isSystemApp(newPackage)) {
10149                // NB: implicit assumption that system package upgrades apply to all users
10150                if (DEBUG_INSTALL) {
10151                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10152                }
10153                PackageSetting ps = mSettings.mPackages.get(pkgName);
10154                if (ps != null) {
10155                    if (res.origUsers != null) {
10156                        for (int userHandle : res.origUsers) {
10157                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10158                                    userHandle, installerPackageName);
10159                        }
10160                    }
10161                    // Also convey the prior install/uninstall state
10162                    if (allUsers != null && perUserInstalled != null) {
10163                        for (int i = 0; i < allUsers.length; i++) {
10164                            if (DEBUG_INSTALL) {
10165                                Slog.d(TAG, "    user " + allUsers[i]
10166                                        + " => " + perUserInstalled[i]);
10167                            }
10168                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10169                        }
10170                        // these install state changes will be persisted in the
10171                        // upcoming call to mSettings.writeLPr().
10172                    }
10173                }
10174            }
10175            res.name = pkgName;
10176            res.uid = newPackage.applicationInfo.uid;
10177            res.pkg = newPackage;
10178            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10179            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10180            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10181            //to update install status
10182            mSettings.writeLPr();
10183        }
10184    }
10185
10186    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10187        final int installFlags = args.installFlags;
10188        String installerPackageName = args.installerPackageName;
10189        File tmpPackageFile = new File(args.getCodePath());
10190        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10191        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10192        boolean replace = false;
10193        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10194        // Result object to be returned
10195        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10196
10197        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10198        // Retrieve PackageSettings and parse package
10199        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10200                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10201                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10202        PackageParser pp = new PackageParser();
10203        pp.setSeparateProcesses(mSeparateProcesses);
10204        pp.setDisplayMetrics(mMetrics);
10205
10206        final PackageParser.Package pkg;
10207        try {
10208            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10209        } catch (PackageParserException e) {
10210            res.setError("Failed parse during installPackageLI", e);
10211            return;
10212        }
10213
10214        // Mark that we have an install time CPU ABI override.
10215        pkg.cpuAbiOverride = args.abiOverride;
10216
10217        String pkgName = res.name = pkg.packageName;
10218        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10219            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10220                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10221                return;
10222            }
10223        }
10224
10225        try {
10226            pp.collectCertificates(pkg, parseFlags);
10227            pp.collectManifestDigest(pkg);
10228        } catch (PackageParserException e) {
10229            res.setError("Failed collect during installPackageLI", e);
10230            return;
10231        }
10232
10233        /* If the installer passed in a manifest digest, compare it now. */
10234        if (args.manifestDigest != null) {
10235            if (DEBUG_INSTALL) {
10236                final String parsedManifest = pkg.manifestDigest == null ? "null"
10237                        : pkg.manifestDigest.toString();
10238                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10239                        + parsedManifest);
10240            }
10241
10242            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10243                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10244                return;
10245            }
10246        } else if (DEBUG_INSTALL) {
10247            final String parsedManifest = pkg.manifestDigest == null
10248                    ? "null" : pkg.manifestDigest.toString();
10249            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10250        }
10251
10252        // Get rid of all references to package scan path via parser.
10253        pp = null;
10254        String oldCodePath = null;
10255        boolean systemApp = false;
10256        synchronized (mPackages) {
10257            // Check whether the newly-scanned package wants to define an already-defined perm
10258            int N = pkg.permissions.size();
10259            for (int i = N-1; i >= 0; i--) {
10260                PackageParser.Permission perm = pkg.permissions.get(i);
10261                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10262                if (bp != null) {
10263                    // If the defining package is signed with our cert, it's okay.  This
10264                    // also includes the "updating the same package" case, of course.
10265                    // "updating same package" could also involve key-rotation.
10266                    final boolean sigsOk;
10267                    if (!bp.sourcePackage.equals(pkg.packageName)
10268                            || !(bp.packageSetting instanceof PackageSetting)
10269                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10270                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10271                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10272                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10273                    } else {
10274                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10275                    }
10276                    if (!sigsOk) {
10277                        // If the owning package is the system itself, we log but allow
10278                        // install to proceed; we fail the install on all other permission
10279                        // redefinitions.
10280                        if (!bp.sourcePackage.equals("android")) {
10281                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10282                                    + pkg.packageName + " attempting to redeclare permission "
10283                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10284                            res.origPermission = perm.info.name;
10285                            res.origPackage = bp.sourcePackage;
10286                            return;
10287                        } else {
10288                            Slog.w(TAG, "Package " + pkg.packageName
10289                                    + " attempting to redeclare system permission "
10290                                    + perm.info.name + "; ignoring new declaration");
10291                            pkg.permissions.remove(i);
10292                        }
10293                    }
10294                }
10295            }
10296
10297            // Check if installing already existing package
10298            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10299                String oldName = mSettings.mRenamedPackages.get(pkgName);
10300                if (pkg.mOriginalPackages != null
10301                        && pkg.mOriginalPackages.contains(oldName)
10302                        && mPackages.containsKey(oldName)) {
10303                    // This package is derived from an original package,
10304                    // and this device has been updating from that original
10305                    // name.  We must continue using the original name, so
10306                    // rename the new package here.
10307                    pkg.setPackageName(oldName);
10308                    pkgName = pkg.packageName;
10309                    replace = true;
10310                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10311                            + oldName + " pkgName=" + pkgName);
10312                } else if (mPackages.containsKey(pkgName)) {
10313                    // This package, under its official name, already exists
10314                    // on the device; we should replace it.
10315                    replace = true;
10316                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10317                }
10318            }
10319            PackageSetting ps = mSettings.mPackages.get(pkgName);
10320            if (ps != null) {
10321                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10322                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10323                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10324                    systemApp = (ps.pkg.applicationInfo.flags &
10325                            ApplicationInfo.FLAG_SYSTEM) != 0;
10326                }
10327                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10328            }
10329        }
10330
10331        if (systemApp && onSd) {
10332            // Disable updates to system apps on sdcard
10333            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10334                    "Cannot install updates to system apps on sdcard");
10335            return;
10336        }
10337
10338        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10339            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10340            return;
10341        }
10342
10343        if (replace) {
10344            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10345                    installerPackageName, res);
10346        } else {
10347            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10348                    args.user, installerPackageName, res);
10349        }
10350        synchronized (mPackages) {
10351            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10352            if (ps != null) {
10353                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10354            }
10355        }
10356    }
10357
10358    private static boolean isForwardLocked(PackageParser.Package pkg) {
10359        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10360    }
10361
10362    private static boolean isForwardLocked(ApplicationInfo info) {
10363        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10364    }
10365
10366    private boolean isForwardLocked(PackageSetting ps) {
10367        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10368    }
10369
10370    private static boolean isMultiArch(PackageSetting ps) {
10371        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10372    }
10373
10374    private static boolean isMultiArch(ApplicationInfo info) {
10375        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10376    }
10377
10378    private static boolean isExternal(PackageParser.Package pkg) {
10379        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10380    }
10381
10382    private static boolean isExternal(PackageSetting ps) {
10383        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10384    }
10385
10386    private static boolean isExternal(ApplicationInfo info) {
10387        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10388    }
10389
10390    private static boolean isSystemApp(PackageParser.Package pkg) {
10391        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10392    }
10393
10394    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10395        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10396    }
10397
10398    private static boolean isSystemApp(ApplicationInfo info) {
10399        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10400    }
10401
10402    private static boolean isSystemApp(PackageSetting ps) {
10403        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10404    }
10405
10406    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10407        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10408    }
10409
10410    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10411        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10412    }
10413
10414    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10415        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10416    }
10417
10418    private int packageFlagsToInstallFlags(PackageSetting ps) {
10419        int installFlags = 0;
10420        if (isExternal(ps)) {
10421            installFlags |= PackageManager.INSTALL_EXTERNAL;
10422        }
10423        if (isForwardLocked(ps)) {
10424            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10425        }
10426        return installFlags;
10427    }
10428
10429    private void deleteTempPackageFiles() {
10430        final FilenameFilter filter = new FilenameFilter() {
10431            public boolean accept(File dir, String name) {
10432                return name.startsWith("vmdl") && name.endsWith(".tmp");
10433            }
10434        };
10435        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10436            file.delete();
10437        }
10438    }
10439
10440    @Override
10441    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10442            int flags) {
10443        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10444                flags);
10445    }
10446
10447    @Override
10448    public void deletePackage(final String packageName,
10449            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10450        mContext.enforceCallingOrSelfPermission(
10451                android.Manifest.permission.DELETE_PACKAGES, null);
10452        final int uid = Binder.getCallingUid();
10453        if (UserHandle.getUserId(uid) != userId) {
10454            mContext.enforceCallingPermission(
10455                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10456                    "deletePackage for user " + userId);
10457        }
10458        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10459            try {
10460                observer.onPackageDeleted(packageName,
10461                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10462            } catch (RemoteException re) {
10463            }
10464            return;
10465        }
10466
10467        boolean uninstallBlocked = false;
10468        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10469            int[] users = sUserManager.getUserIds();
10470            for (int i = 0; i < users.length; ++i) {
10471                if (getBlockUninstallForUser(packageName, users[i])) {
10472                    uninstallBlocked = true;
10473                    break;
10474                }
10475            }
10476        } else {
10477            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10478        }
10479        if (uninstallBlocked) {
10480            try {
10481                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10482                        null);
10483            } catch (RemoteException re) {
10484            }
10485            return;
10486        }
10487
10488        if (DEBUG_REMOVE) {
10489            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10490        }
10491        // Queue up an async operation since the package deletion may take a little while.
10492        mHandler.post(new Runnable() {
10493            public void run() {
10494                mHandler.removeCallbacks(this);
10495                final int returnCode = deletePackageX(packageName, userId, flags);
10496                if (observer != null) {
10497                    try {
10498                        observer.onPackageDeleted(packageName, returnCode, null);
10499                    } catch (RemoteException e) {
10500                        Log.i(TAG, "Observer no longer exists.");
10501                    } //end catch
10502                } //end if
10503            } //end run
10504        });
10505    }
10506
10507    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10508        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10509                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10510        try {
10511            if (dpm != null) {
10512                if (dpm.isDeviceOwner(packageName)) {
10513                    return true;
10514                }
10515                int[] users;
10516                if (userId == UserHandle.USER_ALL) {
10517                    users = sUserManager.getUserIds();
10518                } else {
10519                    users = new int[]{userId};
10520                }
10521                for (int i = 0; i < users.length; ++i) {
10522                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10523                        return true;
10524                    }
10525                }
10526            }
10527        } catch (RemoteException e) {
10528        }
10529        return false;
10530    }
10531
10532    /**
10533     *  This method is an internal method that could be get invoked either
10534     *  to delete an installed package or to clean up a failed installation.
10535     *  After deleting an installed package, a broadcast is sent to notify any
10536     *  listeners that the package has been installed. For cleaning up a failed
10537     *  installation, the broadcast is not necessary since the package's
10538     *  installation wouldn't have sent the initial broadcast either
10539     *  The key steps in deleting a package are
10540     *  deleting the package information in internal structures like mPackages,
10541     *  deleting the packages base directories through installd
10542     *  updating mSettings to reflect current status
10543     *  persisting settings for later use
10544     *  sending a broadcast if necessary
10545     */
10546    private int deletePackageX(String packageName, int userId, int flags) {
10547        final PackageRemovedInfo info = new PackageRemovedInfo();
10548        final boolean res;
10549
10550        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10551                ? UserHandle.ALL : new UserHandle(userId);
10552
10553        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10554            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10555            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10556        }
10557
10558        boolean removedForAllUsers = false;
10559        boolean systemUpdate = false;
10560
10561        // for the uninstall-updates case and restricted profiles, remember the per-
10562        // userhandle installed state
10563        int[] allUsers;
10564        boolean[] perUserInstalled;
10565        synchronized (mPackages) {
10566            PackageSetting ps = mSettings.mPackages.get(packageName);
10567            allUsers = sUserManager.getUserIds();
10568            perUserInstalled = new boolean[allUsers.length];
10569            for (int i = 0; i < allUsers.length; i++) {
10570                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10571            }
10572        }
10573
10574        synchronized (mInstallLock) {
10575            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10576            res = deletePackageLI(packageName, removeForUser,
10577                    true, allUsers, perUserInstalled,
10578                    flags | REMOVE_CHATTY, info, true);
10579            systemUpdate = info.isRemovedPackageSystemUpdate;
10580            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10581                removedForAllUsers = true;
10582            }
10583            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10584                    + " removedForAllUsers=" + removedForAllUsers);
10585        }
10586
10587        if (res) {
10588            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10589
10590            // If the removed package was a system update, the old system package
10591            // was re-enabled; we need to broadcast this information
10592            if (systemUpdate) {
10593                Bundle extras = new Bundle(1);
10594                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10595                        ? info.removedAppId : info.uid);
10596                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10597
10598                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10599                        extras, null, null, null);
10600                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10601                        extras, null, null, null);
10602                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10603                        null, packageName, null, null);
10604            }
10605        }
10606        // Force a gc here.
10607        Runtime.getRuntime().gc();
10608        // Delete the resources here after sending the broadcast to let
10609        // other processes clean up before deleting resources.
10610        if (info.args != null) {
10611            synchronized (mInstallLock) {
10612                info.args.doPostDeleteLI(true);
10613            }
10614        }
10615
10616        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10617    }
10618
10619    static class PackageRemovedInfo {
10620        String removedPackage;
10621        int uid = -1;
10622        int removedAppId = -1;
10623        int[] removedUsers = null;
10624        boolean isRemovedPackageSystemUpdate = false;
10625        // Clean up resources deleted packages.
10626        InstallArgs args = null;
10627
10628        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10629            Bundle extras = new Bundle(1);
10630            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10631            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10632            if (replacing) {
10633                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10634            }
10635            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10636            if (removedPackage != null) {
10637                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10638                        extras, null, null, removedUsers);
10639                if (fullRemove && !replacing) {
10640                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10641                            extras, null, null, removedUsers);
10642                }
10643            }
10644            if (removedAppId >= 0) {
10645                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10646                        removedUsers);
10647            }
10648        }
10649    }
10650
10651    /*
10652     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10653     * flag is not set, the data directory is removed as well.
10654     * make sure this flag is set for partially installed apps. If not its meaningless to
10655     * delete a partially installed application.
10656     */
10657    private void removePackageDataLI(PackageSetting ps,
10658            int[] allUserHandles, boolean[] perUserInstalled,
10659            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10660        String packageName = ps.name;
10661        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10662        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10663        // Retrieve object to delete permissions for shared user later on
10664        final PackageSetting deletedPs;
10665        // reader
10666        synchronized (mPackages) {
10667            deletedPs = mSettings.mPackages.get(packageName);
10668            if (outInfo != null) {
10669                outInfo.removedPackage = packageName;
10670                outInfo.removedUsers = deletedPs != null
10671                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10672                        : null;
10673            }
10674        }
10675        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10676            removeDataDirsLI(packageName);
10677            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10678        }
10679        // writer
10680        synchronized (mPackages) {
10681            if (deletedPs != null) {
10682                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10683                    if (outInfo != null) {
10684                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10685                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10686                    }
10687                    if (deletedPs != null) {
10688                        updatePermissionsLPw(deletedPs.name, null, 0);
10689                        if (deletedPs.sharedUser != null) {
10690                            // remove permissions associated with package
10691                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10692                        }
10693                    }
10694                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10695                }
10696                // make sure to preserve per-user disabled state if this removal was just
10697                // a downgrade of a system app to the factory package
10698                if (allUserHandles != null && perUserInstalled != null) {
10699                    if (DEBUG_REMOVE) {
10700                        Slog.d(TAG, "Propagating install state across downgrade");
10701                    }
10702                    for (int i = 0; i < allUserHandles.length; i++) {
10703                        if (DEBUG_REMOVE) {
10704                            Slog.d(TAG, "    user " + allUserHandles[i]
10705                                    + " => " + perUserInstalled[i]);
10706                        }
10707                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10708                    }
10709                }
10710            }
10711            // can downgrade to reader
10712            if (writeSettings) {
10713                // Save settings now
10714                mSettings.writeLPr();
10715            }
10716        }
10717        if (outInfo != null) {
10718            // A user ID was deleted here. Go through all users and remove it
10719            // from KeyStore.
10720            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10721        }
10722    }
10723
10724    static boolean locationIsPrivileged(File path) {
10725        try {
10726            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10727                    .getCanonicalPath();
10728            return path.getCanonicalPath().startsWith(privilegedAppDir);
10729        } catch (IOException e) {
10730            Slog.e(TAG, "Unable to access code path " + path);
10731        }
10732        return false;
10733    }
10734
10735    /*
10736     * Tries to delete system package.
10737     */
10738    private boolean deleteSystemPackageLI(PackageSetting newPs,
10739            int[] allUserHandles, boolean[] perUserInstalled,
10740            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10741        final boolean applyUserRestrictions
10742                = (allUserHandles != null) && (perUserInstalled != null);
10743        PackageSetting disabledPs = null;
10744        // Confirm if the system package has been updated
10745        // An updated system app can be deleted. This will also have to restore
10746        // the system pkg from system partition
10747        // reader
10748        synchronized (mPackages) {
10749            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10750        }
10751        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10752                + " disabledPs=" + disabledPs);
10753        if (disabledPs == null) {
10754            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10755            return false;
10756        } else if (DEBUG_REMOVE) {
10757            Slog.d(TAG, "Deleting system pkg from data partition");
10758        }
10759        if (DEBUG_REMOVE) {
10760            if (applyUserRestrictions) {
10761                Slog.d(TAG, "Remembering install states:");
10762                for (int i = 0; i < allUserHandles.length; i++) {
10763                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10764                }
10765            }
10766        }
10767        // Delete the updated package
10768        outInfo.isRemovedPackageSystemUpdate = true;
10769        if (disabledPs.versionCode < newPs.versionCode) {
10770            // Delete data for downgrades
10771            flags &= ~PackageManager.DELETE_KEEP_DATA;
10772        } else {
10773            // Preserve data by setting flag
10774            flags |= PackageManager.DELETE_KEEP_DATA;
10775        }
10776        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10777                allUserHandles, perUserInstalled, outInfo, writeSettings);
10778        if (!ret) {
10779            return false;
10780        }
10781        // writer
10782        synchronized (mPackages) {
10783            // Reinstate the old system package
10784            mSettings.enableSystemPackageLPw(newPs.name);
10785            // Remove any native libraries from the upgraded package.
10786            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10787        }
10788        // Install the system package
10789        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10790        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10791        if (locationIsPrivileged(disabledPs.codePath)) {
10792            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10793        }
10794
10795        final PackageParser.Package newPkg;
10796        try {
10797            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10798        } catch (PackageManagerException e) {
10799            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10800            return false;
10801        }
10802
10803        // writer
10804        synchronized (mPackages) {
10805            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10806            updatePermissionsLPw(newPkg.packageName, newPkg,
10807                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10808            if (applyUserRestrictions) {
10809                if (DEBUG_REMOVE) {
10810                    Slog.d(TAG, "Propagating install state across reinstall");
10811                }
10812                for (int i = 0; i < allUserHandles.length; i++) {
10813                    if (DEBUG_REMOVE) {
10814                        Slog.d(TAG, "    user " + allUserHandles[i]
10815                                + " => " + perUserInstalled[i]);
10816                    }
10817                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10818                }
10819                // Regardless of writeSettings we need to ensure that this restriction
10820                // state propagation is persisted
10821                mSettings.writeAllUsersPackageRestrictionsLPr();
10822            }
10823            // can downgrade to reader here
10824            if (writeSettings) {
10825                mSettings.writeLPr();
10826            }
10827        }
10828        return true;
10829    }
10830
10831    private boolean deleteInstalledPackageLI(PackageSetting ps,
10832            boolean deleteCodeAndResources, int flags,
10833            int[] allUserHandles, boolean[] perUserInstalled,
10834            PackageRemovedInfo outInfo, boolean writeSettings) {
10835        if (outInfo != null) {
10836            outInfo.uid = ps.appId;
10837        }
10838
10839        // Delete package data from internal structures and also remove data if flag is set
10840        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10841
10842        // Delete application code and resources
10843        if (deleteCodeAndResources && (outInfo != null)) {
10844            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10845                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10846                    getAppDexInstructionSets(ps));
10847            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10848        }
10849        return true;
10850    }
10851
10852    @Override
10853    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10854            int userId) {
10855        mContext.enforceCallingOrSelfPermission(
10856                android.Manifest.permission.DELETE_PACKAGES, null);
10857        synchronized (mPackages) {
10858            PackageSetting ps = mSettings.mPackages.get(packageName);
10859            if (ps == null) {
10860                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10861                return false;
10862            }
10863            if (!ps.getInstalled(userId)) {
10864                // Can't block uninstall for an app that is not installed or enabled.
10865                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10866                return false;
10867            }
10868            ps.setBlockUninstall(blockUninstall, userId);
10869            mSettings.writePackageRestrictionsLPr(userId);
10870        }
10871        return true;
10872    }
10873
10874    @Override
10875    public boolean getBlockUninstallForUser(String packageName, int userId) {
10876        synchronized (mPackages) {
10877            PackageSetting ps = mSettings.mPackages.get(packageName);
10878            if (ps == null) {
10879                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10880                return false;
10881            }
10882            return ps.getBlockUninstall(userId);
10883        }
10884    }
10885
10886    /*
10887     * This method handles package deletion in general
10888     */
10889    private boolean deletePackageLI(String packageName, UserHandle user,
10890            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10891            int flags, PackageRemovedInfo outInfo,
10892            boolean writeSettings) {
10893        if (packageName == null) {
10894            Slog.w(TAG, "Attempt to delete null packageName.");
10895            return false;
10896        }
10897        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10898        PackageSetting ps;
10899        boolean dataOnly = false;
10900        int removeUser = -1;
10901        int appId = -1;
10902        synchronized (mPackages) {
10903            ps = mSettings.mPackages.get(packageName);
10904            if (ps == null) {
10905                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10906                return false;
10907            }
10908            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10909                    && user.getIdentifier() != UserHandle.USER_ALL) {
10910                // The caller is asking that the package only be deleted for a single
10911                // user.  To do this, we just mark its uninstalled state and delete
10912                // its data.  If this is a system app, we only allow this to happen if
10913                // they have set the special DELETE_SYSTEM_APP which requests different
10914                // semantics than normal for uninstalling system apps.
10915                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10916                ps.setUserState(user.getIdentifier(),
10917                        COMPONENT_ENABLED_STATE_DEFAULT,
10918                        false, //installed
10919                        true,  //stopped
10920                        true,  //notLaunched
10921                        false, //hidden
10922                        null, null, null,
10923                        false // blockUninstall
10924                        );
10925                if (!isSystemApp(ps)) {
10926                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10927                        // Other user still have this package installed, so all
10928                        // we need to do is clear this user's data and save that
10929                        // it is uninstalled.
10930                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10931                        removeUser = user.getIdentifier();
10932                        appId = ps.appId;
10933                        mSettings.writePackageRestrictionsLPr(removeUser);
10934                    } else {
10935                        // We need to set it back to 'installed' so the uninstall
10936                        // broadcasts will be sent correctly.
10937                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10938                        ps.setInstalled(true, user.getIdentifier());
10939                    }
10940                } else {
10941                    // This is a system app, so we assume that the
10942                    // other users still have this package installed, so all
10943                    // we need to do is clear this user's data and save that
10944                    // it is uninstalled.
10945                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10946                    removeUser = user.getIdentifier();
10947                    appId = ps.appId;
10948                    mSettings.writePackageRestrictionsLPr(removeUser);
10949                }
10950            }
10951        }
10952
10953        if (removeUser >= 0) {
10954            // From above, we determined that we are deleting this only
10955            // for a single user.  Continue the work here.
10956            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10957            if (outInfo != null) {
10958                outInfo.removedPackage = packageName;
10959                outInfo.removedAppId = appId;
10960                outInfo.removedUsers = new int[] {removeUser};
10961            }
10962            mInstaller.clearUserData(packageName, removeUser);
10963            removeKeystoreDataIfNeeded(removeUser, appId);
10964            schedulePackageCleaning(packageName, removeUser, false);
10965            return true;
10966        }
10967
10968        if (dataOnly) {
10969            // Delete application data first
10970            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10971            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10972            return true;
10973        }
10974
10975        boolean ret = false;
10976        if (isSystemApp(ps)) {
10977            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10978            // When an updated system application is deleted we delete the existing resources as well and
10979            // fall back to existing code in system partition
10980            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10981                    flags, outInfo, writeSettings);
10982        } else {
10983            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10984            // Kill application pre-emptively especially for apps on sd.
10985            killApplication(packageName, ps.appId, "uninstall pkg");
10986            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10987                    allUserHandles, perUserInstalled,
10988                    outInfo, writeSettings);
10989        }
10990
10991        return ret;
10992    }
10993
10994    private final class ClearStorageConnection implements ServiceConnection {
10995        IMediaContainerService mContainerService;
10996
10997        @Override
10998        public void onServiceConnected(ComponentName name, IBinder service) {
10999            synchronized (this) {
11000                mContainerService = IMediaContainerService.Stub.asInterface(service);
11001                notifyAll();
11002            }
11003        }
11004
11005        @Override
11006        public void onServiceDisconnected(ComponentName name) {
11007        }
11008    }
11009
11010    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11011        final boolean mounted;
11012        if (Environment.isExternalStorageEmulated()) {
11013            mounted = true;
11014        } else {
11015            final String status = Environment.getExternalStorageState();
11016
11017            mounted = status.equals(Environment.MEDIA_MOUNTED)
11018                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11019        }
11020
11021        if (!mounted) {
11022            return;
11023        }
11024
11025        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11026        int[] users;
11027        if (userId == UserHandle.USER_ALL) {
11028            users = sUserManager.getUserIds();
11029        } else {
11030            users = new int[] { userId };
11031        }
11032        final ClearStorageConnection conn = new ClearStorageConnection();
11033        if (mContext.bindServiceAsUser(
11034                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11035            try {
11036                for (int curUser : users) {
11037                    long timeout = SystemClock.uptimeMillis() + 5000;
11038                    synchronized (conn) {
11039                        long now = SystemClock.uptimeMillis();
11040                        while (conn.mContainerService == null && now < timeout) {
11041                            try {
11042                                conn.wait(timeout - now);
11043                            } catch (InterruptedException e) {
11044                            }
11045                        }
11046                    }
11047                    if (conn.mContainerService == null) {
11048                        return;
11049                    }
11050
11051                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11052                    clearDirectory(conn.mContainerService,
11053                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11054                    if (allData) {
11055                        clearDirectory(conn.mContainerService,
11056                                userEnv.buildExternalStorageAppDataDirs(packageName));
11057                        clearDirectory(conn.mContainerService,
11058                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11059                    }
11060                }
11061            } finally {
11062                mContext.unbindService(conn);
11063            }
11064        }
11065    }
11066
11067    @Override
11068    public void clearApplicationUserData(final String packageName,
11069            final IPackageDataObserver observer, final int userId) {
11070        mContext.enforceCallingOrSelfPermission(
11071                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11072        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11073        // Queue up an async operation since the package deletion may take a little while.
11074        mHandler.post(new Runnable() {
11075            public void run() {
11076                mHandler.removeCallbacks(this);
11077                final boolean succeeded;
11078                synchronized (mInstallLock) {
11079                    succeeded = clearApplicationUserDataLI(packageName, userId);
11080                }
11081                clearExternalStorageDataSync(packageName, userId, true);
11082                if (succeeded) {
11083                    // invoke DeviceStorageMonitor's update method to clear any notifications
11084                    DeviceStorageMonitorInternal
11085                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11086                    if (dsm != null) {
11087                        dsm.checkMemory();
11088                    }
11089                }
11090                if(observer != null) {
11091                    try {
11092                        observer.onRemoveCompleted(packageName, succeeded);
11093                    } catch (RemoteException e) {
11094                        Log.i(TAG, "Observer no longer exists.");
11095                    }
11096                } //end if observer
11097            } //end run
11098        });
11099    }
11100
11101    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11102        if (packageName == null) {
11103            Slog.w(TAG, "Attempt to delete null packageName.");
11104            return false;
11105        }
11106
11107        // Try finding details about the requested package
11108        PackageParser.Package pkg;
11109        synchronized (mPackages) {
11110            pkg = mPackages.get(packageName);
11111            if (pkg == null) {
11112                final PackageSetting ps = mSettings.mPackages.get(packageName);
11113                if (ps != null) {
11114                    pkg = ps.pkg;
11115                }
11116            }
11117        }
11118
11119        if (pkg == null) {
11120            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11121        }
11122
11123        // Always delete data directories for package, even if we found no other
11124        // record of app. This helps users recover from UID mismatches without
11125        // resorting to a full data wipe.
11126        int retCode = mInstaller.clearUserData(packageName, userId);
11127        if (retCode < 0) {
11128            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11129            return false;
11130        }
11131
11132        if (pkg == null) {
11133            return false;
11134        }
11135
11136        if (pkg != null && pkg.applicationInfo != null) {
11137            final int appId = pkg.applicationInfo.uid;
11138            removeKeystoreDataIfNeeded(userId, appId);
11139        }
11140
11141        // Create a native library symlink only if we have native libraries
11142        // and if the native libraries are 32 bit libraries. We do not provide
11143        // this symlink for 64 bit libraries.
11144        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11145                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11146            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11147            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11148                Slog.w(TAG, "Failed linking native library dir");
11149                return false;
11150            }
11151        }
11152
11153        return true;
11154    }
11155
11156    /**
11157     * Remove entries from the keystore daemon. Will only remove it if the
11158     * {@code appId} is valid.
11159     */
11160    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11161        if (appId < 0) {
11162            return;
11163        }
11164
11165        final KeyStore keyStore = KeyStore.getInstance();
11166        if (keyStore != null) {
11167            if (userId == UserHandle.USER_ALL) {
11168                for (final int individual : sUserManager.getUserIds()) {
11169                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11170                }
11171            } else {
11172                keyStore.clearUid(UserHandle.getUid(userId, appId));
11173            }
11174        } else {
11175            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11176        }
11177    }
11178
11179    @Override
11180    public void deleteApplicationCacheFiles(final String packageName,
11181            final IPackageDataObserver observer) {
11182        mContext.enforceCallingOrSelfPermission(
11183                android.Manifest.permission.DELETE_CACHE_FILES, null);
11184        // Queue up an async operation since the package deletion may take a little while.
11185        final int userId = UserHandle.getCallingUserId();
11186        mHandler.post(new Runnable() {
11187            public void run() {
11188                mHandler.removeCallbacks(this);
11189                final boolean succeded;
11190                synchronized (mInstallLock) {
11191                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11192                }
11193                clearExternalStorageDataSync(packageName, userId, false);
11194                if(observer != null) {
11195                    try {
11196                        observer.onRemoveCompleted(packageName, succeded);
11197                    } catch (RemoteException e) {
11198                        Log.i(TAG, "Observer no longer exists.");
11199                    }
11200                } //end if observer
11201            } //end run
11202        });
11203    }
11204
11205    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11206        if (packageName == null) {
11207            Slog.w(TAG, "Attempt to delete null packageName.");
11208            return false;
11209        }
11210        PackageParser.Package p;
11211        synchronized (mPackages) {
11212            p = mPackages.get(packageName);
11213        }
11214        if (p == null) {
11215            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11216            return false;
11217        }
11218        final ApplicationInfo applicationInfo = p.applicationInfo;
11219        if (applicationInfo == null) {
11220            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11221            return false;
11222        }
11223        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11224        if (retCode < 0) {
11225            Slog.w(TAG, "Couldn't remove cache files for package: "
11226                       + packageName + " u" + userId);
11227            return false;
11228        }
11229        return true;
11230    }
11231
11232    @Override
11233    public void getPackageSizeInfo(final String packageName, int userHandle,
11234            final IPackageStatsObserver observer) {
11235        mContext.enforceCallingOrSelfPermission(
11236                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11237        if (packageName == null) {
11238            throw new IllegalArgumentException("Attempt to get size of null packageName");
11239        }
11240
11241        PackageStats stats = new PackageStats(packageName, userHandle);
11242
11243        /*
11244         * Queue up an async operation since the package measurement may take a
11245         * little while.
11246         */
11247        Message msg = mHandler.obtainMessage(INIT_COPY);
11248        msg.obj = new MeasureParams(stats, observer);
11249        mHandler.sendMessage(msg);
11250    }
11251
11252    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11253            PackageStats pStats) {
11254        if (packageName == null) {
11255            Slog.w(TAG, "Attempt to get size of null packageName.");
11256            return false;
11257        }
11258        PackageParser.Package p;
11259        boolean dataOnly = false;
11260        String libDirRoot = null;
11261        String asecPath = null;
11262        PackageSetting ps = null;
11263        synchronized (mPackages) {
11264            p = mPackages.get(packageName);
11265            ps = mSettings.mPackages.get(packageName);
11266            if(p == null) {
11267                dataOnly = true;
11268                if((ps == null) || (ps.pkg == null)) {
11269                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11270                    return false;
11271                }
11272                p = ps.pkg;
11273            }
11274            if (ps != null) {
11275                libDirRoot = ps.legacyNativeLibraryPathString;
11276            }
11277            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11278                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11279                if (secureContainerId != null) {
11280                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11281                }
11282            }
11283        }
11284        String publicSrcDir = null;
11285        if(!dataOnly) {
11286            final ApplicationInfo applicationInfo = p.applicationInfo;
11287            if (applicationInfo == null) {
11288                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11289                return false;
11290            }
11291            if (isForwardLocked(p)) {
11292                publicSrcDir = applicationInfo.getBaseResourcePath();
11293            }
11294        }
11295        // TODO: extend to measure size of split APKs
11296        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11297        // not just the first level.
11298        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11299        // just the primary.
11300        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11301        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11302                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11303        if (res < 0) {
11304            return false;
11305        }
11306
11307        // Fix-up for forward-locked applications in ASEC containers.
11308        if (!isExternal(p)) {
11309            pStats.codeSize += pStats.externalCodeSize;
11310            pStats.externalCodeSize = 0L;
11311        }
11312
11313        return true;
11314    }
11315
11316
11317    @Override
11318    public void addPackageToPreferred(String packageName) {
11319        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11320    }
11321
11322    @Override
11323    public void removePackageFromPreferred(String packageName) {
11324        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11325    }
11326
11327    @Override
11328    public List<PackageInfo> getPreferredPackages(int flags) {
11329        return new ArrayList<PackageInfo>();
11330    }
11331
11332    private int getUidTargetSdkVersionLockedLPr(int uid) {
11333        Object obj = mSettings.getUserIdLPr(uid);
11334        if (obj instanceof SharedUserSetting) {
11335            final SharedUserSetting sus = (SharedUserSetting) obj;
11336            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11337            final Iterator<PackageSetting> it = sus.packages.iterator();
11338            while (it.hasNext()) {
11339                final PackageSetting ps = it.next();
11340                if (ps.pkg != null) {
11341                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11342                    if (v < vers) vers = v;
11343                }
11344            }
11345            return vers;
11346        } else if (obj instanceof PackageSetting) {
11347            final PackageSetting ps = (PackageSetting) obj;
11348            if (ps.pkg != null) {
11349                return ps.pkg.applicationInfo.targetSdkVersion;
11350            }
11351        }
11352        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11353    }
11354
11355    @Override
11356    public void addPreferredActivity(IntentFilter filter, int match,
11357            ComponentName[] set, ComponentName activity, int userId) {
11358        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11359                "Adding preferred");
11360    }
11361
11362    private void addPreferredActivityInternal(IntentFilter filter, int match,
11363            ComponentName[] set, ComponentName activity, boolean always, int userId,
11364            String opname) {
11365        // writer
11366        int callingUid = Binder.getCallingUid();
11367        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11368        if (filter.countActions() == 0) {
11369            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11370            return;
11371        }
11372        synchronized (mPackages) {
11373            if (mContext.checkCallingOrSelfPermission(
11374                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11375                    != PackageManager.PERMISSION_GRANTED) {
11376                if (getUidTargetSdkVersionLockedLPr(callingUid)
11377                        < Build.VERSION_CODES.FROYO) {
11378                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11379                            + callingUid);
11380                    return;
11381                }
11382                mContext.enforceCallingOrSelfPermission(
11383                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11384            }
11385
11386            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11387            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11388                    + userId + ":");
11389            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11390            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11391            mSettings.writePackageRestrictionsLPr(userId);
11392        }
11393    }
11394
11395    @Override
11396    public void replacePreferredActivity(IntentFilter filter, int match,
11397            ComponentName[] set, ComponentName activity, int userId) {
11398        if (filter.countActions() != 1) {
11399            throw new IllegalArgumentException(
11400                    "replacePreferredActivity expects filter to have only 1 action.");
11401        }
11402        if (filter.countDataAuthorities() != 0
11403                || filter.countDataPaths() != 0
11404                || filter.countDataSchemes() > 1
11405                || filter.countDataTypes() != 0) {
11406            throw new IllegalArgumentException(
11407                    "replacePreferredActivity expects filter to have no data authorities, " +
11408                    "paths, or types; and at most one scheme.");
11409        }
11410
11411        final int callingUid = Binder.getCallingUid();
11412        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11413        synchronized (mPackages) {
11414            if (mContext.checkCallingOrSelfPermission(
11415                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11416                    != PackageManager.PERMISSION_GRANTED) {
11417                if (getUidTargetSdkVersionLockedLPr(callingUid)
11418                        < Build.VERSION_CODES.FROYO) {
11419                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11420                            + Binder.getCallingUid());
11421                    return;
11422                }
11423                mContext.enforceCallingOrSelfPermission(
11424                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11425            }
11426
11427            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11428            if (pir != null) {
11429                // Get all of the existing entries that exactly match this filter.
11430                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11431                if (existing != null && existing.size() == 1) {
11432                    PreferredActivity cur = existing.get(0);
11433                    if (DEBUG_PREFERRED) {
11434                        Slog.i(TAG, "Checking replace of preferred:");
11435                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11436                        if (!cur.mPref.mAlways) {
11437                            Slog.i(TAG, "  -- CUR; not mAlways!");
11438                        } else {
11439                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11440                            Slog.i(TAG, "  -- CUR: mSet="
11441                                    + Arrays.toString(cur.mPref.mSetComponents));
11442                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11443                            Slog.i(TAG, "  -- NEW: mMatch="
11444                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11445                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11446                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11447                        }
11448                    }
11449                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11450                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11451                            && cur.mPref.sameSet(set)) {
11452                        // Setting the preferred activity to what it happens to be already
11453                        if (DEBUG_PREFERRED) {
11454                            Slog.i(TAG, "Replacing with same preferred activity "
11455                                    + cur.mPref.mShortComponent + " for user "
11456                                    + userId + ":");
11457                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11458                        }
11459                        return;
11460                    }
11461                }
11462
11463                if (existing != null) {
11464                    if (DEBUG_PREFERRED) {
11465                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11466                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11467                    }
11468                    for (int i = 0; i < existing.size(); i++) {
11469                        PreferredActivity pa = existing.get(i);
11470                        if (DEBUG_PREFERRED) {
11471                            Slog.i(TAG, "Removing existing preferred activity "
11472                                    + pa.mPref.mComponent + ":");
11473                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11474                        }
11475                        pir.removeFilter(pa);
11476                    }
11477                }
11478            }
11479            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11480                    "Replacing preferred");
11481        }
11482    }
11483
11484    @Override
11485    public void clearPackagePreferredActivities(String packageName) {
11486        final int uid = Binder.getCallingUid();
11487        // writer
11488        synchronized (mPackages) {
11489            PackageParser.Package pkg = mPackages.get(packageName);
11490            if (pkg == null || pkg.applicationInfo.uid != uid) {
11491                if (mContext.checkCallingOrSelfPermission(
11492                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11493                        != PackageManager.PERMISSION_GRANTED) {
11494                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11495                            < Build.VERSION_CODES.FROYO) {
11496                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11497                                + Binder.getCallingUid());
11498                        return;
11499                    }
11500                    mContext.enforceCallingOrSelfPermission(
11501                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11502                }
11503            }
11504
11505            int user = UserHandle.getCallingUserId();
11506            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11507                mSettings.writePackageRestrictionsLPr(user);
11508                scheduleWriteSettingsLocked();
11509            }
11510        }
11511    }
11512
11513    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11514    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11515        ArrayList<PreferredActivity> removed = null;
11516        boolean changed = false;
11517        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11518            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11519            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11520            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11521                continue;
11522            }
11523            Iterator<PreferredActivity> it = pir.filterIterator();
11524            while (it.hasNext()) {
11525                PreferredActivity pa = it.next();
11526                // Mark entry for removal only if it matches the package name
11527                // and the entry is of type "always".
11528                if (packageName == null ||
11529                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11530                                && pa.mPref.mAlways)) {
11531                    if (removed == null) {
11532                        removed = new ArrayList<PreferredActivity>();
11533                    }
11534                    removed.add(pa);
11535                }
11536            }
11537            if (removed != null) {
11538                for (int j=0; j<removed.size(); j++) {
11539                    PreferredActivity pa = removed.get(j);
11540                    pir.removeFilter(pa);
11541                }
11542                changed = true;
11543            }
11544        }
11545        return changed;
11546    }
11547
11548    @Override
11549    public void resetPreferredActivities(int userId) {
11550        /* TODO: Actually use userId. Why is it being passed in? */
11551        mContext.enforceCallingOrSelfPermission(
11552                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11553        // writer
11554        synchronized (mPackages) {
11555            int user = UserHandle.getCallingUserId();
11556            clearPackagePreferredActivitiesLPw(null, user);
11557            mSettings.readDefaultPreferredAppsLPw(this, user);
11558            mSettings.writePackageRestrictionsLPr(user);
11559            scheduleWriteSettingsLocked();
11560        }
11561    }
11562
11563    @Override
11564    public int getPreferredActivities(List<IntentFilter> outFilters,
11565            List<ComponentName> outActivities, String packageName) {
11566
11567        int num = 0;
11568        final int userId = UserHandle.getCallingUserId();
11569        // reader
11570        synchronized (mPackages) {
11571            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11572            if (pir != null) {
11573                final Iterator<PreferredActivity> it = pir.filterIterator();
11574                while (it.hasNext()) {
11575                    final PreferredActivity pa = it.next();
11576                    if (packageName == null
11577                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11578                                    && pa.mPref.mAlways)) {
11579                        if (outFilters != null) {
11580                            outFilters.add(new IntentFilter(pa));
11581                        }
11582                        if (outActivities != null) {
11583                            outActivities.add(pa.mPref.mComponent);
11584                        }
11585                    }
11586                }
11587            }
11588        }
11589
11590        return num;
11591    }
11592
11593    @Override
11594    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11595            int userId) {
11596        int callingUid = Binder.getCallingUid();
11597        if (callingUid != Process.SYSTEM_UID) {
11598            throw new SecurityException(
11599                    "addPersistentPreferredActivity can only be run by the system");
11600        }
11601        if (filter.countActions() == 0) {
11602            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11603            return;
11604        }
11605        synchronized (mPackages) {
11606            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11607                    " :");
11608            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11609            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11610                    new PersistentPreferredActivity(filter, activity));
11611            mSettings.writePackageRestrictionsLPr(userId);
11612        }
11613    }
11614
11615    @Override
11616    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11617        int callingUid = Binder.getCallingUid();
11618        if (callingUid != Process.SYSTEM_UID) {
11619            throw new SecurityException(
11620                    "clearPackagePersistentPreferredActivities can only be run by the system");
11621        }
11622        ArrayList<PersistentPreferredActivity> removed = null;
11623        boolean changed = false;
11624        synchronized (mPackages) {
11625            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11626                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11627                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11628                        .valueAt(i);
11629                if (userId != thisUserId) {
11630                    continue;
11631                }
11632                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11633                while (it.hasNext()) {
11634                    PersistentPreferredActivity ppa = it.next();
11635                    // Mark entry for removal only if it matches the package name.
11636                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11637                        if (removed == null) {
11638                            removed = new ArrayList<PersistentPreferredActivity>();
11639                        }
11640                        removed.add(ppa);
11641                    }
11642                }
11643                if (removed != null) {
11644                    for (int j=0; j<removed.size(); j++) {
11645                        PersistentPreferredActivity ppa = removed.get(j);
11646                        ppir.removeFilter(ppa);
11647                    }
11648                    changed = true;
11649                }
11650            }
11651
11652            if (changed) {
11653                mSettings.writePackageRestrictionsLPr(userId);
11654            }
11655        }
11656    }
11657
11658    @Override
11659    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11660            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11661        mContext.enforceCallingOrSelfPermission(
11662                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11663        int callingUid = Binder.getCallingUid();
11664        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11665        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11666        if (intentFilter.countActions() == 0) {
11667            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11668            return;
11669        }
11670        synchronized (mPackages) {
11671            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11672                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11673            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11674            mSettings.writePackageRestrictionsLPr(sourceUserId);
11675        }
11676    }
11677
11678    @Override
11679    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11680            int ownerUserId) {
11681        mContext.enforceCallingOrSelfPermission(
11682                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11683        int callingUid = Binder.getCallingUid();
11684        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11685        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11686        int callingUserId = UserHandle.getUserId(callingUid);
11687        synchronized (mPackages) {
11688            CrossProfileIntentResolver resolver =
11689                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11690            HashSet<CrossProfileIntentFilter> set =
11691                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11692            for (CrossProfileIntentFilter filter : set) {
11693                if (filter.getOwnerPackage().equals(ownerPackage)
11694                        && filter.getOwnerUserId() == callingUserId) {
11695                    resolver.removeFilter(filter);
11696                }
11697            }
11698            mSettings.writePackageRestrictionsLPr(sourceUserId);
11699        }
11700    }
11701
11702    // Enforcing that callingUid is owning pkg on userId
11703    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11704        // The system owns everything.
11705        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11706            return;
11707        }
11708        int callingUserId = UserHandle.getUserId(callingUid);
11709        if (callingUserId != userId) {
11710            throw new SecurityException("calling uid " + callingUid
11711                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11712                    + callingUserId);
11713        }
11714        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11715        if (pi == null) {
11716            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11717                    + callingUserId);
11718        }
11719        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11720            throw new SecurityException("Calling uid " + callingUid
11721                    + " does not own package " + pkg);
11722        }
11723    }
11724
11725    @Override
11726    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11727        Intent intent = new Intent(Intent.ACTION_MAIN);
11728        intent.addCategory(Intent.CATEGORY_HOME);
11729
11730        final int callingUserId = UserHandle.getCallingUserId();
11731        List<ResolveInfo> list = queryIntentActivities(intent, null,
11732                PackageManager.GET_META_DATA, callingUserId);
11733        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11734                true, false, false, callingUserId);
11735
11736        allHomeCandidates.clear();
11737        if (list != null) {
11738            for (ResolveInfo ri : list) {
11739                allHomeCandidates.add(ri);
11740            }
11741        }
11742        return (preferred == null || preferred.activityInfo == null)
11743                ? null
11744                : new ComponentName(preferred.activityInfo.packageName,
11745                        preferred.activityInfo.name);
11746    }
11747
11748    @Override
11749    public void setApplicationEnabledSetting(String appPackageName,
11750            int newState, int flags, int userId, String callingPackage) {
11751        if (!sUserManager.exists(userId)) return;
11752        if (callingPackage == null) {
11753            callingPackage = Integer.toString(Binder.getCallingUid());
11754        }
11755        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11756    }
11757
11758    @Override
11759    public void setComponentEnabledSetting(ComponentName componentName,
11760            int newState, int flags, int userId) {
11761        if (!sUserManager.exists(userId)) return;
11762        setEnabledSetting(componentName.getPackageName(),
11763                componentName.getClassName(), newState, flags, userId, null);
11764    }
11765
11766    private void setEnabledSetting(final String packageName, String className, int newState,
11767            final int flags, int userId, String callingPackage) {
11768        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11769              || newState == COMPONENT_ENABLED_STATE_ENABLED
11770              || newState == COMPONENT_ENABLED_STATE_DISABLED
11771              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11772              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11773            throw new IllegalArgumentException("Invalid new component state: "
11774                    + newState);
11775        }
11776        PackageSetting pkgSetting;
11777        final int uid = Binder.getCallingUid();
11778        final int permission = mContext.checkCallingOrSelfPermission(
11779                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11780        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
11781        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11782        boolean sendNow = false;
11783        boolean isApp = (className == null);
11784        String componentName = isApp ? packageName : className;
11785        int packageUid = -1;
11786        ArrayList<String> components;
11787
11788        // writer
11789        synchronized (mPackages) {
11790            pkgSetting = mSettings.mPackages.get(packageName);
11791            if (pkgSetting == null) {
11792                if (className == null) {
11793                    throw new IllegalArgumentException(
11794                            "Unknown package: " + packageName);
11795                }
11796                throw new IllegalArgumentException(
11797                        "Unknown component: " + packageName
11798                        + "/" + className);
11799            }
11800            // Allow root and verify that userId is not being specified by a different user
11801            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11802                throw new SecurityException(
11803                        "Permission Denial: attempt to change component state from pid="
11804                        + Binder.getCallingPid()
11805                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11806            }
11807            if (className == null) {
11808                // We're dealing with an application/package level state change
11809                if (pkgSetting.getEnabled(userId) == newState) {
11810                    // Nothing to do
11811                    return;
11812                }
11813                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11814                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11815                    // Don't care about who enables an app.
11816                    callingPackage = null;
11817                }
11818                pkgSetting.setEnabled(newState, userId, callingPackage);
11819                // pkgSetting.pkg.mSetEnabled = newState;
11820            } else {
11821                // We're dealing with a component level state change
11822                // First, verify that this is a valid class name.
11823                PackageParser.Package pkg = pkgSetting.pkg;
11824                if (pkg == null || !pkg.hasComponentClassName(className)) {
11825                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11826                        throw new IllegalArgumentException("Component class " + className
11827                                + " does not exist in " + packageName);
11828                    } else {
11829                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11830                                + className + " does not exist in " + packageName);
11831                    }
11832                }
11833                switch (newState) {
11834                case COMPONENT_ENABLED_STATE_ENABLED:
11835                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11836                        return;
11837                    }
11838                    break;
11839                case COMPONENT_ENABLED_STATE_DISABLED:
11840                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11841                        return;
11842                    }
11843                    break;
11844                case COMPONENT_ENABLED_STATE_DEFAULT:
11845                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11846                        return;
11847                    }
11848                    break;
11849                default:
11850                    Slog.e(TAG, "Invalid new component state: " + newState);
11851                    return;
11852                }
11853            }
11854            mSettings.writePackageRestrictionsLPr(userId);
11855            components = mPendingBroadcasts.get(userId, packageName);
11856            final boolean newPackage = components == null;
11857            if (newPackage) {
11858                components = new ArrayList<String>();
11859            }
11860            if (!components.contains(componentName)) {
11861                components.add(componentName);
11862            }
11863            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11864                sendNow = true;
11865                // Purge entry from pending broadcast list if another one exists already
11866                // since we are sending one right away.
11867                mPendingBroadcasts.remove(userId, packageName);
11868            } else {
11869                if (newPackage) {
11870                    mPendingBroadcasts.put(userId, packageName, components);
11871                }
11872                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11873                    // Schedule a message
11874                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11875                }
11876            }
11877        }
11878
11879        long callingId = Binder.clearCallingIdentity();
11880        try {
11881            if (sendNow) {
11882                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11883                sendPackageChangedBroadcast(packageName,
11884                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11885            }
11886        } finally {
11887            Binder.restoreCallingIdentity(callingId);
11888        }
11889    }
11890
11891    private void sendPackageChangedBroadcast(String packageName,
11892            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11893        if (DEBUG_INSTALL)
11894            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11895                    + componentNames);
11896        Bundle extras = new Bundle(4);
11897        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11898        String nameList[] = new String[componentNames.size()];
11899        componentNames.toArray(nameList);
11900        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11901        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11902        extras.putInt(Intent.EXTRA_UID, packageUid);
11903        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11904                new int[] {UserHandle.getUserId(packageUid)});
11905    }
11906
11907    @Override
11908    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11909        if (!sUserManager.exists(userId)) return;
11910        final int uid = Binder.getCallingUid();
11911        final int permission = mContext.checkCallingOrSelfPermission(
11912                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11913        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11914        enforceCrossUserPermission(uid, userId, true, true, "stop package");
11915        // writer
11916        synchronized (mPackages) {
11917            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11918                    uid, userId)) {
11919                scheduleWritePackageRestrictionsLocked(userId);
11920            }
11921        }
11922    }
11923
11924    @Override
11925    public String getInstallerPackageName(String packageName) {
11926        // reader
11927        synchronized (mPackages) {
11928            return mSettings.getInstallerPackageNameLPr(packageName);
11929        }
11930    }
11931
11932    @Override
11933    public int getApplicationEnabledSetting(String packageName, int userId) {
11934        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11935        int uid = Binder.getCallingUid();
11936        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
11937        // reader
11938        synchronized (mPackages) {
11939            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11940        }
11941    }
11942
11943    @Override
11944    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11945        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11946        int uid = Binder.getCallingUid();
11947        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
11948        // reader
11949        synchronized (mPackages) {
11950            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11951        }
11952    }
11953
11954    @Override
11955    public void enterSafeMode() {
11956        enforceSystemOrRoot("Only the system can request entering safe mode");
11957
11958        if (!mSystemReady) {
11959            mSafeMode = true;
11960        }
11961    }
11962
11963    @Override
11964    public void systemReady() {
11965        mSystemReady = true;
11966
11967        // Read the compatibilty setting when the system is ready.
11968        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11969                mContext.getContentResolver(),
11970                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11971        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11972        if (DEBUG_SETTINGS) {
11973            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11974        }
11975
11976        synchronized (mPackages) {
11977            // Verify that all of the preferred activity components actually
11978            // exist.  It is possible for applications to be updated and at
11979            // that point remove a previously declared activity component that
11980            // had been set as a preferred activity.  We try to clean this up
11981            // the next time we encounter that preferred activity, but it is
11982            // possible for the user flow to never be able to return to that
11983            // situation so here we do a sanity check to make sure we haven't
11984            // left any junk around.
11985            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11986            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11987                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11988                removed.clear();
11989                for (PreferredActivity pa : pir.filterSet()) {
11990                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11991                        removed.add(pa);
11992                    }
11993                }
11994                if (removed.size() > 0) {
11995                    for (int r=0; r<removed.size(); r++) {
11996                        PreferredActivity pa = removed.get(r);
11997                        Slog.w(TAG, "Removing dangling preferred activity: "
11998                                + pa.mPref.mComponent);
11999                        pir.removeFilter(pa);
12000                    }
12001                    mSettings.writePackageRestrictionsLPr(
12002                            mSettings.mPreferredActivities.keyAt(i));
12003                }
12004            }
12005        }
12006        sUserManager.systemReady();
12007
12008        // Kick off any messages waiting for system ready
12009        if (mPostSystemReadyMessages != null) {
12010            for (Message msg : mPostSystemReadyMessages) {
12011                msg.sendToTarget();
12012            }
12013            mPostSystemReadyMessages = null;
12014        }
12015    }
12016
12017    @Override
12018    public boolean isSafeMode() {
12019        return mSafeMode;
12020    }
12021
12022    @Override
12023    public boolean hasSystemUidErrors() {
12024        return mHasSystemUidErrors;
12025    }
12026
12027    static String arrayToString(int[] array) {
12028        StringBuffer buf = new StringBuffer(128);
12029        buf.append('[');
12030        if (array != null) {
12031            for (int i=0; i<array.length; i++) {
12032                if (i > 0) buf.append(", ");
12033                buf.append(array[i]);
12034            }
12035        }
12036        buf.append(']');
12037        return buf.toString();
12038    }
12039
12040    static class DumpState {
12041        public static final int DUMP_LIBS = 1 << 0;
12042        public static final int DUMP_FEATURES = 1 << 1;
12043        public static final int DUMP_RESOLVERS = 1 << 2;
12044        public static final int DUMP_PERMISSIONS = 1 << 3;
12045        public static final int DUMP_PACKAGES = 1 << 4;
12046        public static final int DUMP_SHARED_USERS = 1 << 5;
12047        public static final int DUMP_MESSAGES = 1 << 6;
12048        public static final int DUMP_PROVIDERS = 1 << 7;
12049        public static final int DUMP_VERIFIERS = 1 << 8;
12050        public static final int DUMP_PREFERRED = 1 << 9;
12051        public static final int DUMP_PREFERRED_XML = 1 << 10;
12052        public static final int DUMP_KEYSETS = 1 << 11;
12053        public static final int DUMP_VERSION = 1 << 12;
12054        public static final int DUMP_INSTALLS = 1 << 13;
12055
12056        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12057
12058        private int mTypes;
12059
12060        private int mOptions;
12061
12062        private boolean mTitlePrinted;
12063
12064        private SharedUserSetting mSharedUser;
12065
12066        public boolean isDumping(int type) {
12067            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12068                return true;
12069            }
12070
12071            return (mTypes & type) != 0;
12072        }
12073
12074        public void setDump(int type) {
12075            mTypes |= type;
12076        }
12077
12078        public boolean isOptionEnabled(int option) {
12079            return (mOptions & option) != 0;
12080        }
12081
12082        public void setOptionEnabled(int option) {
12083            mOptions |= option;
12084        }
12085
12086        public boolean onTitlePrinted() {
12087            final boolean printed = mTitlePrinted;
12088            mTitlePrinted = true;
12089            return printed;
12090        }
12091
12092        public boolean getTitlePrinted() {
12093            return mTitlePrinted;
12094        }
12095
12096        public void setTitlePrinted(boolean enabled) {
12097            mTitlePrinted = enabled;
12098        }
12099
12100        public SharedUserSetting getSharedUser() {
12101            return mSharedUser;
12102        }
12103
12104        public void setSharedUser(SharedUserSetting user) {
12105            mSharedUser = user;
12106        }
12107    }
12108
12109    @Override
12110    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12111        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12112                != PackageManager.PERMISSION_GRANTED) {
12113            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12114                    + Binder.getCallingPid()
12115                    + ", uid=" + Binder.getCallingUid()
12116                    + " without permission "
12117                    + android.Manifest.permission.DUMP);
12118            return;
12119        }
12120
12121        DumpState dumpState = new DumpState();
12122        boolean fullPreferred = false;
12123        boolean checkin = false;
12124
12125        String packageName = null;
12126
12127        int opti = 0;
12128        while (opti < args.length) {
12129            String opt = args[opti];
12130            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12131                break;
12132            }
12133            opti++;
12134
12135            if ("-a".equals(opt)) {
12136                // Right now we only know how to print all.
12137            } else if ("-h".equals(opt)) {
12138                pw.println("Package manager dump options:");
12139                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12140                pw.println("    --checkin: dump for a checkin");
12141                pw.println("    -f: print details of intent filters");
12142                pw.println("    -h: print this help");
12143                pw.println("  cmd may be one of:");
12144                pw.println("    l[ibraries]: list known shared libraries");
12145                pw.println("    f[ibraries]: list device features");
12146                pw.println("    k[eysets]: print known keysets");
12147                pw.println("    r[esolvers]: dump intent resolvers");
12148                pw.println("    perm[issions]: dump permissions");
12149                pw.println("    pref[erred]: print preferred package settings");
12150                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12151                pw.println("    prov[iders]: dump content providers");
12152                pw.println("    p[ackages]: dump installed packages");
12153                pw.println("    s[hared-users]: dump shared user IDs");
12154                pw.println("    m[essages]: print collected runtime messages");
12155                pw.println("    v[erifiers]: print package verifier info");
12156                pw.println("    version: print database version info");
12157                pw.println("    write: write current settings now");
12158                pw.println("    <package.name>: info about given package");
12159                pw.println("    installs: details about install sessions");
12160                return;
12161            } else if ("--checkin".equals(opt)) {
12162                checkin = true;
12163            } else if ("-f".equals(opt)) {
12164                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12165            } else {
12166                pw.println("Unknown argument: " + opt + "; use -h for help");
12167            }
12168        }
12169
12170        // Is the caller requesting to dump a particular piece of data?
12171        if (opti < args.length) {
12172            String cmd = args[opti];
12173            opti++;
12174            // Is this a package name?
12175            if ("android".equals(cmd) || cmd.contains(".")) {
12176                packageName = cmd;
12177                // When dumping a single package, we always dump all of its
12178                // filter information since the amount of data will be reasonable.
12179                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12180            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12181                dumpState.setDump(DumpState.DUMP_LIBS);
12182            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12183                dumpState.setDump(DumpState.DUMP_FEATURES);
12184            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12185                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12186            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12187                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12188            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12189                dumpState.setDump(DumpState.DUMP_PREFERRED);
12190            } else if ("preferred-xml".equals(cmd)) {
12191                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12192                if (opti < args.length && "--full".equals(args[opti])) {
12193                    fullPreferred = true;
12194                    opti++;
12195                }
12196            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12197                dumpState.setDump(DumpState.DUMP_PACKAGES);
12198            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12199                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12200            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12201                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12202            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12203                dumpState.setDump(DumpState.DUMP_MESSAGES);
12204            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12205                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12206            } else if ("version".equals(cmd)) {
12207                dumpState.setDump(DumpState.DUMP_VERSION);
12208            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12209                dumpState.setDump(DumpState.DUMP_KEYSETS);
12210            } else if ("installs".equals(cmd)) {
12211                dumpState.setDump(DumpState.DUMP_INSTALLS);
12212            } else if ("write".equals(cmd)) {
12213                synchronized (mPackages) {
12214                    mSettings.writeLPr();
12215                    pw.println("Settings written.");
12216                    return;
12217                }
12218            }
12219        }
12220
12221        if (checkin) {
12222            pw.println("vers,1");
12223        }
12224
12225        // reader
12226        synchronized (mPackages) {
12227            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12228                if (!checkin) {
12229                    if (dumpState.onTitlePrinted())
12230                        pw.println();
12231                    pw.println("Database versions:");
12232                    pw.print("  SDK Version:");
12233                    pw.print(" internal=");
12234                    pw.print(mSettings.mInternalSdkPlatform);
12235                    pw.print(" external=");
12236                    pw.println(mSettings.mExternalSdkPlatform);
12237                    pw.print("  DB Version:");
12238                    pw.print(" internal=");
12239                    pw.print(mSettings.mInternalDatabaseVersion);
12240                    pw.print(" external=");
12241                    pw.println(mSettings.mExternalDatabaseVersion);
12242                }
12243            }
12244
12245            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12246                if (!checkin) {
12247                    if (dumpState.onTitlePrinted())
12248                        pw.println();
12249                    pw.println("Verifiers:");
12250                    pw.print("  Required: ");
12251                    pw.print(mRequiredVerifierPackage);
12252                    pw.print(" (uid=");
12253                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12254                    pw.println(")");
12255                } else if (mRequiredVerifierPackage != null) {
12256                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12257                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12258                }
12259            }
12260
12261            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12262                boolean printedHeader = false;
12263                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12264                while (it.hasNext()) {
12265                    String name = it.next();
12266                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12267                    if (!checkin) {
12268                        if (!printedHeader) {
12269                            if (dumpState.onTitlePrinted())
12270                                pw.println();
12271                            pw.println("Libraries:");
12272                            printedHeader = true;
12273                        }
12274                        pw.print("  ");
12275                    } else {
12276                        pw.print("lib,");
12277                    }
12278                    pw.print(name);
12279                    if (!checkin) {
12280                        pw.print(" -> ");
12281                    }
12282                    if (ent.path != null) {
12283                        if (!checkin) {
12284                            pw.print("(jar) ");
12285                            pw.print(ent.path);
12286                        } else {
12287                            pw.print(",jar,");
12288                            pw.print(ent.path);
12289                        }
12290                    } else {
12291                        if (!checkin) {
12292                            pw.print("(apk) ");
12293                            pw.print(ent.apk);
12294                        } else {
12295                            pw.print(",apk,");
12296                            pw.print(ent.apk);
12297                        }
12298                    }
12299                    pw.println();
12300                }
12301            }
12302
12303            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12304                if (dumpState.onTitlePrinted())
12305                    pw.println();
12306                if (!checkin) {
12307                    pw.println("Features:");
12308                }
12309                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12310                while (it.hasNext()) {
12311                    String name = it.next();
12312                    if (!checkin) {
12313                        pw.print("  ");
12314                    } else {
12315                        pw.print("feat,");
12316                    }
12317                    pw.println(name);
12318                }
12319            }
12320
12321            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12322                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12323                        : "Activity Resolver Table:", "  ", packageName,
12324                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12325                    dumpState.setTitlePrinted(true);
12326                }
12327                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12328                        : "Receiver Resolver Table:", "  ", packageName,
12329                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12330                    dumpState.setTitlePrinted(true);
12331                }
12332                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12333                        : "Service Resolver Table:", "  ", packageName,
12334                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12335                    dumpState.setTitlePrinted(true);
12336                }
12337                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12338                        : "Provider Resolver Table:", "  ", packageName,
12339                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12340                    dumpState.setTitlePrinted(true);
12341                }
12342            }
12343
12344            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12345                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12346                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12347                    int user = mSettings.mPreferredActivities.keyAt(i);
12348                    if (pir.dump(pw,
12349                            dumpState.getTitlePrinted()
12350                                ? "\nPreferred Activities User " + user + ":"
12351                                : "Preferred Activities User " + user + ":", "  ",
12352                            packageName, true)) {
12353                        dumpState.setTitlePrinted(true);
12354                    }
12355                }
12356            }
12357
12358            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12359                pw.flush();
12360                FileOutputStream fout = new FileOutputStream(fd);
12361                BufferedOutputStream str = new BufferedOutputStream(fout);
12362                XmlSerializer serializer = new FastXmlSerializer();
12363                try {
12364                    serializer.setOutput(str, "utf-8");
12365                    serializer.startDocument(null, true);
12366                    serializer.setFeature(
12367                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12368                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12369                    serializer.endDocument();
12370                    serializer.flush();
12371                } catch (IllegalArgumentException e) {
12372                    pw.println("Failed writing: " + e);
12373                } catch (IllegalStateException e) {
12374                    pw.println("Failed writing: " + e);
12375                } catch (IOException e) {
12376                    pw.println("Failed writing: " + e);
12377                }
12378            }
12379
12380            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12381                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12382                if (packageName == null) {
12383                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12384                        if (iperm == 0) {
12385                            if (dumpState.onTitlePrinted())
12386                                pw.println();
12387                            pw.println("AppOp Permissions:");
12388                        }
12389                        pw.print("  AppOp Permission ");
12390                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12391                        pw.println(":");
12392                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12393                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12394                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12395                        }
12396                    }
12397                }
12398            }
12399
12400            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12401                boolean printedSomething = false;
12402                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12403                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12404                        continue;
12405                    }
12406                    if (!printedSomething) {
12407                        if (dumpState.onTitlePrinted())
12408                            pw.println();
12409                        pw.println("Registered ContentProviders:");
12410                        printedSomething = true;
12411                    }
12412                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12413                    pw.print("    "); pw.println(p.toString());
12414                }
12415                printedSomething = false;
12416                for (Map.Entry<String, PackageParser.Provider> entry :
12417                        mProvidersByAuthority.entrySet()) {
12418                    PackageParser.Provider p = entry.getValue();
12419                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12420                        continue;
12421                    }
12422                    if (!printedSomething) {
12423                        if (dumpState.onTitlePrinted())
12424                            pw.println();
12425                        pw.println("ContentProvider Authorities:");
12426                        printedSomething = true;
12427                    }
12428                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12429                    pw.print("    "); pw.println(p.toString());
12430                    if (p.info != null && p.info.applicationInfo != null) {
12431                        final String appInfo = p.info.applicationInfo.toString();
12432                        pw.print("      applicationInfo="); pw.println(appInfo);
12433                    }
12434                }
12435            }
12436
12437            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12438                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12439            }
12440
12441            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12442                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12443            }
12444
12445            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12446                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12447            }
12448
12449            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12450                // XXX should handle packageName != null by dumping only install data that
12451                // the given package is involved with.
12452                if (dumpState.onTitlePrinted()) pw.println();
12453                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12454            }
12455
12456            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12457                if (dumpState.onTitlePrinted()) pw.println();
12458                mSettings.dumpReadMessagesLPr(pw, dumpState);
12459
12460                pw.println();
12461                pw.println("Package warning messages:");
12462                final File fname = getSettingsProblemFile();
12463                FileInputStream in = null;
12464                try {
12465                    in = new FileInputStream(fname);
12466                    final int avail = in.available();
12467                    final byte[] data = new byte[avail];
12468                    in.read(data);
12469                    pw.print(new String(data));
12470                } catch (FileNotFoundException e) {
12471                } catch (IOException e) {
12472                } finally {
12473                    if (in != null) {
12474                        try {
12475                            in.close();
12476                        } catch (IOException e) {
12477                        }
12478                    }
12479                }
12480            }
12481
12482            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
12483                BufferedReader in = null;
12484                String line = null;
12485                try {
12486                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12487                    while ((line = in.readLine()) != null) {
12488                        pw.print("msg,");
12489                        pw.println(line);
12490                    }
12491                } catch (IOException ignored) {
12492                } finally {
12493                    IoUtils.closeQuietly(in);
12494                }
12495            }
12496        }
12497    }
12498
12499    // ------- apps on sdcard specific code -------
12500    static final boolean DEBUG_SD_INSTALL = false;
12501
12502    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12503
12504    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12505
12506    private boolean mMediaMounted = false;
12507
12508    static String getEncryptKey() {
12509        try {
12510            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12511                    SD_ENCRYPTION_KEYSTORE_NAME);
12512            if (sdEncKey == null) {
12513                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12514                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12515                if (sdEncKey == null) {
12516                    Slog.e(TAG, "Failed to create encryption keys");
12517                    return null;
12518                }
12519            }
12520            return sdEncKey;
12521        } catch (NoSuchAlgorithmException nsae) {
12522            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12523            return null;
12524        } catch (IOException ioe) {
12525            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12526            return null;
12527        }
12528    }
12529
12530    /*
12531     * Update media status on PackageManager.
12532     */
12533    @Override
12534    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12535        int callingUid = Binder.getCallingUid();
12536        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12537            throw new SecurityException("Media status can only be updated by the system");
12538        }
12539        // reader; this apparently protects mMediaMounted, but should probably
12540        // be a different lock in that case.
12541        synchronized (mPackages) {
12542            Log.i(TAG, "Updating external media status from "
12543                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12544                    + (mediaStatus ? "mounted" : "unmounted"));
12545            if (DEBUG_SD_INSTALL)
12546                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12547                        + ", mMediaMounted=" + mMediaMounted);
12548            if (mediaStatus == mMediaMounted) {
12549                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12550                        : 0, -1);
12551                mHandler.sendMessage(msg);
12552                return;
12553            }
12554            mMediaMounted = mediaStatus;
12555        }
12556        // Queue up an async operation since the package installation may take a
12557        // little while.
12558        mHandler.post(new Runnable() {
12559            public void run() {
12560                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12561            }
12562        });
12563    }
12564
12565    /**
12566     * Called by MountService when the initial ASECs to scan are available.
12567     * Should block until all the ASEC containers are finished being scanned.
12568     */
12569    public void scanAvailableAsecs() {
12570        updateExternalMediaStatusInner(true, false, false);
12571        if (mShouldRestoreconData) {
12572            SELinuxMMAC.setRestoreconDone();
12573            mShouldRestoreconData = false;
12574        }
12575    }
12576
12577    /*
12578     * Collect information of applications on external media, map them against
12579     * existing containers and update information based on current mount status.
12580     * Please note that we always have to report status if reportStatus has been
12581     * set to true especially when unloading packages.
12582     */
12583    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12584            boolean externalStorage) {
12585        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12586        int[] uidArr = EmptyArray.INT;
12587
12588        final String[] list = PackageHelper.getSecureContainerList();
12589        if (ArrayUtils.isEmpty(list)) {
12590            Log.i(TAG, "No secure containers found");
12591        } else {
12592            // Process list of secure containers and categorize them
12593            // as active or stale based on their package internal state.
12594
12595            // reader
12596            synchronized (mPackages) {
12597                for (String cid : list) {
12598                    // Leave stages untouched for now; installer service owns them
12599                    if (PackageInstallerService.isStageName(cid)) continue;
12600
12601                    if (DEBUG_SD_INSTALL)
12602                        Log.i(TAG, "Processing container " + cid);
12603                    String pkgName = getAsecPackageName(cid);
12604                    if (pkgName == null) {
12605                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12606                        continue;
12607                    }
12608                    if (DEBUG_SD_INSTALL)
12609                        Log.i(TAG, "Looking for pkg : " + pkgName);
12610
12611                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12612                    if (ps == null) {
12613                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12614                        continue;
12615                    }
12616
12617                    /*
12618                     * Skip packages that are not external if we're unmounting
12619                     * external storage.
12620                     */
12621                    if (externalStorage && !isMounted && !isExternal(ps)) {
12622                        continue;
12623                    }
12624
12625                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12626                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12627                    // The package status is changed only if the code path
12628                    // matches between settings and the container id.
12629                    if (ps.codePathString != null
12630                            && ps.codePathString.startsWith(args.getCodePath())) {
12631                        if (DEBUG_SD_INSTALL) {
12632                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12633                                    + " at code path: " + ps.codePathString);
12634                        }
12635
12636                        // We do have a valid package installed on sdcard
12637                        processCids.put(args, ps.codePathString);
12638                        final int uid = ps.appId;
12639                        if (uid != -1) {
12640                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12641                        }
12642                    } else {
12643                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12644                                + ps.codePathString);
12645                    }
12646                }
12647            }
12648
12649            Arrays.sort(uidArr);
12650        }
12651
12652        // Process packages with valid entries.
12653        if (isMounted) {
12654            if (DEBUG_SD_INSTALL)
12655                Log.i(TAG, "Loading packages");
12656            loadMediaPackages(processCids, uidArr);
12657            startCleaningPackages();
12658            mInstallerService.onSecureContainersAvailable();
12659        } else {
12660            if (DEBUG_SD_INSTALL)
12661                Log.i(TAG, "Unloading packages");
12662            unloadMediaPackages(processCids, uidArr, reportStatus);
12663        }
12664    }
12665
12666    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12667            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12668        int size = pkgList.size();
12669        if (size > 0) {
12670            // Send broadcasts here
12671            Bundle extras = new Bundle();
12672            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12673                    .toArray(new String[size]));
12674            if (uidArr != null) {
12675                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12676            }
12677            if (replacing) {
12678                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12679            }
12680            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12681                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12682            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12683        }
12684    }
12685
12686   /*
12687     * Look at potentially valid container ids from processCids If package
12688     * information doesn't match the one on record or package scanning fails,
12689     * the cid is added to list of removeCids. We currently don't delete stale
12690     * containers.
12691     */
12692    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12693        ArrayList<String> pkgList = new ArrayList<String>();
12694        Set<AsecInstallArgs> keys = processCids.keySet();
12695
12696        for (AsecInstallArgs args : keys) {
12697            String codePath = processCids.get(args);
12698            if (DEBUG_SD_INSTALL)
12699                Log.i(TAG, "Loading container : " + args.cid);
12700            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12701            try {
12702                // Make sure there are no container errors first.
12703                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12704                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12705                            + " when installing from sdcard");
12706                    continue;
12707                }
12708                // Check code path here.
12709                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12710                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12711                            + " does not match one in settings " + codePath);
12712                    continue;
12713                }
12714                // Parse package
12715                int parseFlags = mDefParseFlags;
12716                if (args.isExternal()) {
12717                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12718                }
12719                if (args.isFwdLocked()) {
12720                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12721                }
12722
12723                synchronized (mInstallLock) {
12724                    PackageParser.Package pkg = null;
12725                    try {
12726                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12727                    } catch (PackageManagerException e) {
12728                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12729                    }
12730                    // Scan the package
12731                    if (pkg != null) {
12732                        /*
12733                         * TODO why is the lock being held? doPostInstall is
12734                         * called in other places without the lock. This needs
12735                         * to be straightened out.
12736                         */
12737                        // writer
12738                        synchronized (mPackages) {
12739                            retCode = PackageManager.INSTALL_SUCCEEDED;
12740                            pkgList.add(pkg.packageName);
12741                            // Post process args
12742                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12743                                    pkg.applicationInfo.uid);
12744                        }
12745                    } else {
12746                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12747                    }
12748                }
12749
12750            } finally {
12751                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12752                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12753                }
12754            }
12755        }
12756        // writer
12757        synchronized (mPackages) {
12758            // If the platform SDK has changed since the last time we booted,
12759            // we need to re-grant app permission to catch any new ones that
12760            // appear. This is really a hack, and means that apps can in some
12761            // cases get permissions that the user didn't initially explicitly
12762            // allow... it would be nice to have some better way to handle
12763            // this situation.
12764            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12765            if (regrantPermissions)
12766                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12767                        + mSdkVersion + "; regranting permissions for external storage");
12768            mSettings.mExternalSdkPlatform = mSdkVersion;
12769
12770            // Make sure group IDs have been assigned, and any permission
12771            // changes in other apps are accounted for
12772            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12773                    | (regrantPermissions
12774                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12775                            : 0));
12776
12777            mSettings.updateExternalDatabaseVersion();
12778
12779            // can downgrade to reader
12780            // Persist settings
12781            mSettings.writeLPr();
12782        }
12783        // Send a broadcast to let everyone know we are done processing
12784        if (pkgList.size() > 0) {
12785            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12786        }
12787    }
12788
12789   /*
12790     * Utility method to unload a list of specified containers
12791     */
12792    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12793        // Just unmount all valid containers.
12794        for (AsecInstallArgs arg : cidArgs) {
12795            synchronized (mInstallLock) {
12796                arg.doPostDeleteLI(false);
12797           }
12798       }
12799   }
12800
12801    /*
12802     * Unload packages mounted on external media. This involves deleting package
12803     * data from internal structures, sending broadcasts about diabled packages,
12804     * gc'ing to free up references, unmounting all secure containers
12805     * corresponding to packages on external media, and posting a
12806     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12807     * that we always have to post this message if status has been requested no
12808     * matter what.
12809     */
12810    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12811            final boolean reportStatus) {
12812        if (DEBUG_SD_INSTALL)
12813            Log.i(TAG, "unloading media packages");
12814        ArrayList<String> pkgList = new ArrayList<String>();
12815        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12816        final Set<AsecInstallArgs> keys = processCids.keySet();
12817        for (AsecInstallArgs args : keys) {
12818            String pkgName = args.getPackageName();
12819            if (DEBUG_SD_INSTALL)
12820                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12821            // Delete package internally
12822            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12823            synchronized (mInstallLock) {
12824                boolean res = deletePackageLI(pkgName, null, false, null, null,
12825                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12826                if (res) {
12827                    pkgList.add(pkgName);
12828                } else {
12829                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12830                    failedList.add(args);
12831                }
12832            }
12833        }
12834
12835        // reader
12836        synchronized (mPackages) {
12837            // We didn't update the settings after removing each package;
12838            // write them now for all packages.
12839            mSettings.writeLPr();
12840        }
12841
12842        // We have to absolutely send UPDATED_MEDIA_STATUS only
12843        // after confirming that all the receivers processed the ordered
12844        // broadcast when packages get disabled, force a gc to clean things up.
12845        // and unload all the containers.
12846        if (pkgList.size() > 0) {
12847            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12848                    new IIntentReceiver.Stub() {
12849                public void performReceive(Intent intent, int resultCode, String data,
12850                        Bundle extras, boolean ordered, boolean sticky,
12851                        int sendingUser) throws RemoteException {
12852                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12853                            reportStatus ? 1 : 0, 1, keys);
12854                    mHandler.sendMessage(msg);
12855                }
12856            });
12857        } else {
12858            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12859                    keys);
12860            mHandler.sendMessage(msg);
12861        }
12862    }
12863
12864    /** Binder call */
12865    @Override
12866    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12867            final int flags) {
12868        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12869        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12870        int returnCode = PackageManager.MOVE_SUCCEEDED;
12871        int currInstallFlags = 0;
12872        int newInstallFlags = 0;
12873
12874        File codeFile = null;
12875        String installerPackageName = null;
12876        String packageAbiOverride = null;
12877
12878        // reader
12879        synchronized (mPackages) {
12880            final PackageParser.Package pkg = mPackages.get(packageName);
12881            final PackageSetting ps = mSettings.mPackages.get(packageName);
12882            if (pkg == null || ps == null) {
12883                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12884            } else {
12885                // Disable moving fwd locked apps and system packages
12886                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12887                    Slog.w(TAG, "Cannot move system application");
12888                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12889                } else if (pkg.mOperationPending) {
12890                    Slog.w(TAG, "Attempt to move package which has pending operations");
12891                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12892                } else {
12893                    // Find install location first
12894                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12895                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12896                        Slog.w(TAG, "Ambigous flags specified for move location.");
12897                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12898                    } else {
12899                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12900                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12901                        currInstallFlags = isExternal(pkg)
12902                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12903
12904                        if (newInstallFlags == currInstallFlags) {
12905                            Slog.w(TAG, "No move required. Trying to move to same location");
12906                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12907                        } else {
12908                            if (isForwardLocked(pkg)) {
12909                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12910                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12911                            }
12912                        }
12913                    }
12914                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12915                        pkg.mOperationPending = true;
12916                    }
12917                }
12918
12919                codeFile = new File(pkg.codePath);
12920                installerPackageName = ps.installerPackageName;
12921                packageAbiOverride = ps.cpuAbiOverrideString;
12922            }
12923        }
12924
12925        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12926            try {
12927                observer.packageMoved(packageName, returnCode);
12928            } catch (RemoteException ignored) {
12929            }
12930            return;
12931        }
12932
12933        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
12934            @Override
12935            public void onUserActionRequired(Intent intent) throws RemoteException {
12936                throw new IllegalStateException();
12937            }
12938
12939            @Override
12940            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
12941                    Bundle extras) throws RemoteException {
12942                Slog.d(TAG, "Install result for move: "
12943                        + PackageManager.installStatusToString(returnCode, msg));
12944
12945                // We usually have a new package now after the install, but if
12946                // we failed we need to clear the pending flag on the original
12947                // package object.
12948                synchronized (mPackages) {
12949                    final PackageParser.Package pkg = mPackages.get(packageName);
12950                    if (pkg != null) {
12951                        pkg.mOperationPending = false;
12952                    }
12953                }
12954
12955                final int status = PackageManager.installStatusToPublicStatus(returnCode);
12956                switch (status) {
12957                    case PackageInstaller.STATUS_SUCCESS:
12958                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
12959                        break;
12960                    case PackageInstaller.STATUS_FAILURE_STORAGE:
12961                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
12962                        break;
12963                    default:
12964                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
12965                        break;
12966                }
12967            }
12968        };
12969
12970        // Treat a move like reinstalling an existing app, which ensures that we
12971        // process everythign uniformly, like unpacking native libraries.
12972        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
12973
12974        final Message msg = mHandler.obtainMessage(INIT_COPY);
12975        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
12976        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
12977                installerPackageName, null, user, packageAbiOverride);
12978        mHandler.sendMessage(msg);
12979    }
12980
12981    @Override
12982    public boolean setInstallLocation(int loc) {
12983        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12984                null);
12985        if (getInstallLocation() == loc) {
12986            return true;
12987        }
12988        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12989                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12990            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12991                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12992            return true;
12993        }
12994        return false;
12995   }
12996
12997    @Override
12998    public int getInstallLocation() {
12999        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13000                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13001                PackageHelper.APP_INSTALL_AUTO);
13002    }
13003
13004    /** Called by UserManagerService */
13005    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13006        mDirtyUsers.remove(userHandle);
13007        mSettings.removeUserLPw(userHandle);
13008        mPendingBroadcasts.remove(userHandle);
13009        if (mInstaller != null) {
13010            // Technically, we shouldn't be doing this with the package lock
13011            // held.  However, this is very rare, and there is already so much
13012            // other disk I/O going on, that we'll let it slide for now.
13013            mInstaller.removeUserDataDirs(userHandle);
13014        }
13015        mUserNeedsBadging.delete(userHandle);
13016        removeUnusedPackagesLILPw(userManager, userHandle);
13017    }
13018
13019    /**
13020     * We're removing userHandle and would like to remove any downloaded packages
13021     * that are no longer in use by any other user.
13022     * @param userHandle the user being removed
13023     */
13024    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13025        final boolean DEBUG_CLEAN_APKS = false;
13026        int [] users = userManager.getUserIdsLPr();
13027        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13028        while (psit.hasNext()) {
13029            PackageSetting ps = psit.next();
13030            if (ps.pkg == null) {
13031                continue;
13032            }
13033            final String packageName = ps.pkg.packageName;
13034            // Skip over if system app
13035            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13036                continue;
13037            }
13038            if (DEBUG_CLEAN_APKS) {
13039                Slog.i(TAG, "Checking package " + packageName);
13040            }
13041            boolean keep = false;
13042            for (int i = 0; i < users.length; i++) {
13043                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13044                    keep = true;
13045                    if (DEBUG_CLEAN_APKS) {
13046                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13047                                + users[i]);
13048                    }
13049                    break;
13050                }
13051            }
13052            if (!keep) {
13053                if (DEBUG_CLEAN_APKS) {
13054                    Slog.i(TAG, "  Removing package " + packageName);
13055                }
13056                mHandler.post(new Runnable() {
13057                    public void run() {
13058                        deletePackageX(packageName, userHandle, 0);
13059                    } //end run
13060                });
13061            }
13062        }
13063    }
13064
13065    /** Called by UserManagerService */
13066    void createNewUserLILPw(int userHandle, File path) {
13067        if (mInstaller != null) {
13068            mInstaller.createUserConfig(userHandle);
13069            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13070        }
13071    }
13072
13073    @Override
13074    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13075        mContext.enforceCallingOrSelfPermission(
13076                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13077                "Only package verification agents can read the verifier device identity");
13078
13079        synchronized (mPackages) {
13080            return mSettings.getVerifierDeviceIdentityLPw();
13081        }
13082    }
13083
13084    @Override
13085    public void setPermissionEnforced(String permission, boolean enforced) {
13086        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13087        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13088            synchronized (mPackages) {
13089                if (mSettings.mReadExternalStorageEnforced == null
13090                        || mSettings.mReadExternalStorageEnforced != enforced) {
13091                    mSettings.mReadExternalStorageEnforced = enforced;
13092                    mSettings.writeLPr();
13093                }
13094            }
13095            // kill any non-foreground processes so we restart them and
13096            // grant/revoke the GID.
13097            final IActivityManager am = ActivityManagerNative.getDefault();
13098            if (am != null) {
13099                final long token = Binder.clearCallingIdentity();
13100                try {
13101                    am.killProcessesBelowForeground("setPermissionEnforcement");
13102                } catch (RemoteException e) {
13103                } finally {
13104                    Binder.restoreCallingIdentity(token);
13105                }
13106            }
13107        } else {
13108            throw new IllegalArgumentException("No selective enforcement for " + permission);
13109        }
13110    }
13111
13112    @Override
13113    @Deprecated
13114    public boolean isPermissionEnforced(String permission) {
13115        return true;
13116    }
13117
13118    @Override
13119    public boolean isStorageLow() {
13120        final long token = Binder.clearCallingIdentity();
13121        try {
13122            final DeviceStorageMonitorInternal
13123                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13124            if (dsm != null) {
13125                return dsm.isMemoryLow();
13126            } else {
13127                return false;
13128            }
13129        } finally {
13130            Binder.restoreCallingIdentity(token);
13131        }
13132    }
13133
13134    @Override
13135    public IPackageInstaller getPackageInstaller() {
13136        return mInstallerService;
13137    }
13138
13139    private boolean userNeedsBadging(int userId) {
13140        int index = mUserNeedsBadging.indexOfKey(userId);
13141        if (index < 0) {
13142            final UserInfo userInfo;
13143            final long token = Binder.clearCallingIdentity();
13144            try {
13145                userInfo = sUserManager.getUserInfo(userId);
13146            } finally {
13147                Binder.restoreCallingIdentity(token);
13148            }
13149            final boolean b;
13150            if (userInfo != null && userInfo.isManagedProfile()) {
13151                b = true;
13152            } else {
13153                b = false;
13154            }
13155            mUserNeedsBadging.put(userId, b);
13156            return b;
13157        }
13158        return mUserNeedsBadging.valueAt(index);
13159    }
13160
13161    @Override
13162    public KeySet getKeySetByAlias(String packageName, String alias) {
13163        if (packageName == null || alias == null) {
13164            return null;
13165        }
13166        synchronized(mPackages) {
13167            final PackageParser.Package pkg = mPackages.get(packageName);
13168            if (pkg == null) {
13169                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13170                throw new IllegalArgumentException("Unknown package: " + packageName);
13171            }
13172            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13173            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13174        }
13175    }
13176
13177    @Override
13178    public KeySet getSigningKeySet(String packageName) {
13179        if (packageName == null) {
13180            return null;
13181        }
13182        synchronized(mPackages) {
13183            final PackageParser.Package pkg = mPackages.get(packageName);
13184            if (pkg == null) {
13185                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13186                throw new IllegalArgumentException("Unknown package: " + packageName);
13187            }
13188            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13189                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13190                throw new SecurityException("May not access signing KeySet of other apps.");
13191            }
13192            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13193            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13194        }
13195    }
13196
13197    @Override
13198    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13199        if (packageName == null || ks == null) {
13200            return false;
13201        }
13202        synchronized(mPackages) {
13203            final PackageParser.Package pkg = mPackages.get(packageName);
13204            if (pkg == null) {
13205                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13206                throw new IllegalArgumentException("Unknown package: " + packageName);
13207            }
13208            IBinder ksh = ks.getToken();
13209            if (ksh instanceof KeySetHandle) {
13210                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13211                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13212            }
13213            return false;
13214        }
13215    }
13216
13217    @Override
13218    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13219        if (packageName == null || ks == null) {
13220            return false;
13221        }
13222        synchronized(mPackages) {
13223            final PackageParser.Package pkg = mPackages.get(packageName);
13224            if (pkg == null) {
13225                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13226                throw new IllegalArgumentException("Unknown package: " + packageName);
13227            }
13228            IBinder ksh = ks.getToken();
13229            if (ksh instanceof KeySetHandle) {
13230                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13231                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13232            }
13233            return false;
13234        }
13235    }
13236}
13237