PackageManagerService.java revision 53651b9982f53236b767d766e85ec0ce3acc6f0f
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_FAILED_VERSION_DOWNGRADE;
45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
46import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
47import static android.content.pm.PackageParser.isApkFile;
48import static android.os.Process.PACKAGE_INFO_GID;
49import static android.os.Process.SYSTEM_UID;
50import static android.system.OsConstants.O_CREAT;
51import static android.system.OsConstants.O_RDWR;
52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
53import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
54import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
55import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
56import static com.android.internal.util.ArrayUtils.appendInt;
57import static com.android.internal.util.ArrayUtils.removeInt;
58
59import android.util.ArrayMap;
60
61import com.android.internal.R;
62import com.android.internal.app.IMediaContainerService;
63import com.android.internal.app.ResolverActivity;
64import com.android.internal.content.NativeLibraryHelper;
65import com.android.internal.content.PackageHelper;
66import com.android.internal.os.IParcelFileDescriptorFactory;
67import com.android.internal.util.ArrayUtils;
68import com.android.internal.util.FastPrintWriter;
69import com.android.internal.util.FastXmlSerializer;
70import com.android.internal.util.IndentingPrintWriter;
71import com.android.server.EventLogTags;
72import com.android.server.IntentResolver;
73import com.android.server.LocalServices;
74import com.android.server.ServiceThread;
75import com.android.server.SystemConfig;
76import com.android.server.Watchdog;
77import com.android.server.pm.Settings.DatabaseVersion;
78import com.android.server.storage.DeviceStorageMonitorInternal;
79
80import org.xmlpull.v1.XmlSerializer;
81
82import android.app.ActivityManager;
83import android.app.ActivityManagerNative;
84import android.app.AppGlobals;
85import android.app.IActivityManager;
86import android.app.admin.IDevicePolicyManager;
87import android.app.backup.IBackupManager;
88import android.app.usage.UsageStats;
89import android.app.usage.UsageStatsManager;
90import android.content.BroadcastReceiver;
91import android.content.ComponentName;
92import android.content.Context;
93import android.content.IIntentReceiver;
94import android.content.Intent;
95import android.content.IntentFilter;
96import android.content.IntentSender;
97import android.content.IntentSender.SendIntentException;
98import android.content.ServiceConnection;
99import android.content.pm.ActivityInfo;
100import android.content.pm.ApplicationInfo;
101import android.content.pm.FeatureInfo;
102import android.content.pm.IPackageDataObserver;
103import android.content.pm.IPackageDeleteObserver;
104import android.content.pm.IPackageDeleteObserver2;
105import android.content.pm.IPackageInstallObserver2;
106import android.content.pm.IPackageInstaller;
107import android.content.pm.IPackageManager;
108import android.content.pm.IPackageMoveObserver;
109import android.content.pm.IPackageStatsObserver;
110import android.content.pm.InstrumentationInfo;
111import android.content.pm.KeySet;
112import android.content.pm.ManifestDigest;
113import android.content.pm.PackageCleanItem;
114import android.content.pm.PackageInfo;
115import android.content.pm.PackageInfoLite;
116import android.content.pm.PackageInstaller;
117import android.content.pm.PackageManager;
118import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
119import android.content.pm.PackageParser.ActivityIntentInfo;
120import android.content.pm.PackageParser.PackageLite;
121import android.content.pm.PackageParser.PackageParserException;
122import android.content.pm.PackageParser;
123import android.content.pm.PackageStats;
124import android.content.pm.PackageUserState;
125import android.content.pm.ParceledListSlice;
126import android.content.pm.PermissionGroupInfo;
127import android.content.pm.PermissionInfo;
128import android.content.pm.ProviderInfo;
129import android.content.pm.ResolveInfo;
130import android.content.pm.ServiceInfo;
131import android.content.pm.Signature;
132import android.content.pm.UserInfo;
133import android.content.pm.VerificationParams;
134import android.content.pm.VerifierDeviceIdentity;
135import android.content.pm.VerifierInfo;
136import android.content.res.Resources;
137import android.hardware.display.DisplayManager;
138import android.net.Uri;
139import android.os.Binder;
140import android.os.Build;
141import android.os.Bundle;
142import android.os.Environment;
143import android.os.Environment.UserEnvironment;
144import android.os.storage.IMountService;
145import android.os.storage.StorageManager;
146import android.os.Debug;
147import android.os.FileUtils;
148import android.os.Handler;
149import android.os.IBinder;
150import android.os.Looper;
151import android.os.Message;
152import android.os.Parcel;
153import android.os.ParcelFileDescriptor;
154import android.os.Process;
155import android.os.RemoteException;
156import android.os.SELinux;
157import android.os.ServiceManager;
158import android.os.SystemClock;
159import android.os.SystemProperties;
160import android.os.UserHandle;
161import android.os.UserManager;
162import android.security.KeyStore;
163import android.security.SystemKeyStore;
164import android.system.ErrnoException;
165import android.system.Os;
166import android.system.StructStat;
167import android.text.TextUtils;
168import android.text.format.DateUtils;
169import android.util.ArraySet;
170import android.util.AtomicFile;
171import android.util.DisplayMetrics;
172import android.util.EventLog;
173import android.util.ExceptionUtils;
174import android.util.Log;
175import android.util.LogPrinter;
176import android.util.PrintStreamPrinter;
177import android.util.Slog;
178import android.util.SparseArray;
179import android.util.SparseBooleanArray;
180import android.view.Display;
181
182import java.io.BufferedInputStream;
183import java.io.BufferedOutputStream;
184import java.io.BufferedReader;
185import java.io.File;
186import java.io.FileDescriptor;
187import java.io.FileInputStream;
188import java.io.FileNotFoundException;
189import java.io.FileOutputStream;
190import java.io.FileReader;
191import java.io.FilenameFilter;
192import java.io.IOException;
193import java.io.InputStream;
194import java.io.PrintWriter;
195import java.nio.charset.StandardCharsets;
196import java.security.NoSuchAlgorithmException;
197import java.security.PublicKey;
198import java.security.cert.CertificateEncodingException;
199import java.security.cert.CertificateException;
200import java.text.SimpleDateFormat;
201import java.util.ArrayList;
202import java.util.Arrays;
203import java.util.Collection;
204import java.util.Collections;
205import java.util.Comparator;
206import java.util.Date;
207import java.util.Iterator;
208import java.util.List;
209import java.util.Map;
210import java.util.Objects;
211import java.util.Set;
212import java.util.concurrent.atomic.AtomicBoolean;
213import java.util.concurrent.atomic.AtomicLong;
214
215import dalvik.system.DexFile;
216import dalvik.system.StaleDexCacheError;
217import dalvik.system.VMRuntime;
218
219import libcore.io.IoUtils;
220import libcore.util.EmptyArray;
221
222/**
223 * Keep track of all those .apks everywhere.
224 *
225 * This is very central to the platform's security; please run the unit
226 * tests whenever making modifications here:
227 *
228mmm frameworks/base/tests/AndroidTests
229adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
230adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
231 *
232 * {@hide}
233 */
234public class PackageManagerService extends IPackageManager.Stub {
235    static final String TAG = "PackageManager";
236    static final boolean DEBUG_SETTINGS = false;
237    static final boolean DEBUG_PREFERRED = false;
238    static final boolean DEBUG_UPGRADE = false;
239    private static final boolean DEBUG_INSTALL = false;
240    private static final boolean DEBUG_REMOVE = false;
241    private static final boolean DEBUG_BROADCASTS = false;
242    private static final boolean DEBUG_SHOW_INFO = false;
243    private static final boolean DEBUG_PACKAGE_INFO = false;
244    private static final boolean DEBUG_INTENT_MATCHING = false;
245    private static final boolean DEBUG_PACKAGE_SCANNING = false;
246    private static final boolean DEBUG_VERIFY = false;
247    private static final boolean DEBUG_DEXOPT = false;
248    private static final boolean DEBUG_ABI_SELECTION = false;
249
250    private static final int RADIO_UID = Process.PHONE_UID;
251    private static final int LOG_UID = Process.LOG_UID;
252    private static final int NFC_UID = Process.NFC_UID;
253    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
254    private static final int SHELL_UID = Process.SHELL_UID;
255
256    // Cap the size of permission trees that 3rd party apps can define
257    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
258
259    // Suffix used during package installation when copying/moving
260    // package apks to install directory.
261    private static final String INSTALL_PACKAGE_SUFFIX = "-";
262
263    static final int SCAN_NO_DEX = 1<<1;
264    static final int SCAN_FORCE_DEX = 1<<2;
265    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
266    static final int SCAN_NEW_INSTALL = 1<<4;
267    static final int SCAN_NO_PATHS = 1<<5;
268    static final int SCAN_UPDATE_TIME = 1<<6;
269    static final int SCAN_DEFER_DEX = 1<<7;
270    static final int SCAN_BOOTING = 1<<8;
271    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
272    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
273    static final int SCAN_REPLACING = 1<<11;
274
275    static final int REMOVE_CHATTY = 1<<16;
276
277    /**
278     * Timeout (in milliseconds) after which the watchdog should declare that
279     * our handler thread is wedged.  The usual default for such things is one
280     * minute but we sometimes do very lengthy I/O operations on this thread,
281     * such as installing multi-gigabyte applications, so ours needs to be longer.
282     */
283    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
284
285    /**
286     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
287     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
288     * settings entry if available, otherwise we use the hardcoded default.  If it's been
289     * more than this long since the last fstrim, we force one during the boot sequence.
290     *
291     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
292     * one gets run at the next available charging+idle time.  This final mandatory
293     * no-fstrim check kicks in only of the other scheduling criteria is never met.
294     */
295    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
296
297    /**
298     * Whether verification is enabled by default.
299     */
300    private static final boolean DEFAULT_VERIFY_ENABLE = true;
301
302    /**
303     * The default maximum time to wait for the verification agent to return in
304     * milliseconds.
305     */
306    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
307
308    /**
309     * The default response for package verification timeout.
310     *
311     * This can be either PackageManager.VERIFICATION_ALLOW or
312     * PackageManager.VERIFICATION_REJECT.
313     */
314    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
315
316    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
317
318    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
319            DEFAULT_CONTAINER_PACKAGE,
320            "com.android.defcontainer.DefaultContainerService");
321
322    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
323
324    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
325
326    private static String sPreferredInstructionSet;
327
328    final ServiceThread mHandlerThread;
329
330    private static final String IDMAP_PREFIX = "/data/resource-cache/";
331    private static final String IDMAP_SUFFIX = "@idmap";
332
333    final PackageHandler mHandler;
334
335    /**
336     * Messages for {@link #mHandler} that need to wait for system ready before
337     * being dispatched.
338     */
339    private ArrayList<Message> mPostSystemReadyMessages;
340
341    final int mSdkVersion = Build.VERSION.SDK_INT;
342
343    final Context mContext;
344    final boolean mFactoryTest;
345    final boolean mOnlyCore;
346    final boolean mLazyDexOpt;
347    final long mDexOptLRUThresholdInMills;
348    final DisplayMetrics mMetrics;
349    final int mDefParseFlags;
350    final String[] mSeparateProcesses;
351    final boolean mIsUpgrade;
352
353    // This is where all application persistent data goes.
354    final File mAppDataDir;
355
356    // This is where all application persistent data goes for secondary users.
357    final File mUserAppDataDir;
358
359    /** The location for ASEC container files on internal storage. */
360    final String mAsecInternalPath;
361
362    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
363    // LOCK HELD.  Can be called with mInstallLock held.
364    final Installer mInstaller;
365
366    /** Directory where installed third-party apps stored */
367    final File mAppInstallDir;
368
369    /**
370     * Directory to which applications installed internally have their
371     * 32 bit native libraries copied.
372     */
373    private File mAppLib32InstallDir;
374
375    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
376    // apps.
377    final File mDrmAppPrivateInstallDir;
378
379    // ----------------------------------------------------------------
380
381    // Lock for state used when installing and doing other long running
382    // operations.  Methods that must be called with this lock held have
383    // the suffix "LI".
384    final Object mInstallLock = new Object();
385
386    // ----------------------------------------------------------------
387
388    // Keys are String (package name), values are Package.  This also serves
389    // as the lock for the global state.  Methods that must be called with
390    // this lock held have the prefix "LP".
391    final ArrayMap<String, PackageParser.Package> mPackages =
392            new ArrayMap<String, PackageParser.Package>();
393
394    // Tracks available target package names -> overlay package paths.
395    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
396        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
397
398    final Settings mSettings;
399    boolean mRestoredSettings;
400
401    // System configuration read by SystemConfig.
402    final int[] mGlobalGids;
403    final SparseArray<ArraySet<String>> mSystemPermissions;
404    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
405
406    // If mac_permissions.xml was found for seinfo labeling.
407    boolean mFoundPolicyFile;
408
409    // If a recursive restorecon of /data/data/<pkg> is needed.
410    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
411
412    public static final class SharedLibraryEntry {
413        public final String path;
414        public final String apk;
415
416        SharedLibraryEntry(String _path, String _apk) {
417            path = _path;
418            apk = _apk;
419        }
420    }
421
422    // Currently known shared libraries.
423    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
424            new ArrayMap<String, SharedLibraryEntry>();
425
426    // All available activities, for your resolving pleasure.
427    final ActivityIntentResolver mActivities =
428            new ActivityIntentResolver();
429
430    // All available receivers, for your resolving pleasure.
431    final ActivityIntentResolver mReceivers =
432            new ActivityIntentResolver();
433
434    // All available services, for your resolving pleasure.
435    final ServiceIntentResolver mServices = new ServiceIntentResolver();
436
437    // All available providers, for your resolving pleasure.
438    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
439
440    // Mapping from provider base names (first directory in content URI codePath)
441    // to the provider information.
442    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
443            new ArrayMap<String, PackageParser.Provider>();
444
445    // Mapping from instrumentation class names to info about them.
446    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
447            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
448
449    // Mapping from permission names to info about them.
450    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
451            new ArrayMap<String, PackageParser.PermissionGroup>();
452
453    // Packages whose data we have transfered into another package, thus
454    // should no longer exist.
455    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
456
457    // Broadcast actions that are only available to the system.
458    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
459
460    /** List of packages waiting for verification. */
461    final SparseArray<PackageVerificationState> mPendingVerification
462            = new SparseArray<PackageVerificationState>();
463
464    /** Set of packages associated with each app op permission. */
465    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
466
467    final PackageInstallerService mInstallerService;
468
469    ArraySet<PackageParser.Package> mDeferredDexOpt = null;
470
471    // Cache of users who need badging.
472    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
473
474    /** Token for keys in mPendingVerification. */
475    private int mPendingVerificationToken = 0;
476
477    volatile boolean mSystemReady;
478    volatile boolean mSafeMode;
479    volatile boolean mHasSystemUidErrors;
480
481    ApplicationInfo mAndroidApplication;
482    final ActivityInfo mResolveActivity = new ActivityInfo();
483    final ResolveInfo mResolveInfo = new ResolveInfo();
484    ComponentName mResolveComponentName;
485    PackageParser.Package mPlatformPackage;
486    ComponentName mCustomResolverComponentName;
487
488    boolean mResolverReplaced = false;
489
490    // Set of pending broadcasts for aggregating enable/disable of components.
491    static class PendingPackageBroadcasts {
492        // for each user id, a map of <package name -> components within that package>
493        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
494
495        public PendingPackageBroadcasts() {
496            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
497        }
498
499        public ArrayList<String> get(int userId, String packageName) {
500            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
501            return packages.get(packageName);
502        }
503
504        public void put(int userId, String packageName, ArrayList<String> components) {
505            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
506            packages.put(packageName, components);
507        }
508
509        public void remove(int userId, String packageName) {
510            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
511            if (packages != null) {
512                packages.remove(packageName);
513            }
514        }
515
516        public void remove(int userId) {
517            mUidMap.remove(userId);
518        }
519
520        public int userIdCount() {
521            return mUidMap.size();
522        }
523
524        public int userIdAt(int n) {
525            return mUidMap.keyAt(n);
526        }
527
528        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
529            return mUidMap.get(userId);
530        }
531
532        public int size() {
533            // total number of pending broadcast entries across all userIds
534            int num = 0;
535            for (int i = 0; i< mUidMap.size(); i++) {
536                num += mUidMap.valueAt(i).size();
537            }
538            return num;
539        }
540
541        public void clear() {
542            mUidMap.clear();
543        }
544
545        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
546            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
547            if (map == null) {
548                map = new ArrayMap<String, ArrayList<String>>();
549                mUidMap.put(userId, map);
550            }
551            return map;
552        }
553    }
554    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
555
556    // Service Connection to remote media container service to copy
557    // package uri's from external media onto secure containers
558    // or internal storage.
559    private IMediaContainerService mContainerService = null;
560
561    static final int SEND_PENDING_BROADCAST = 1;
562    static final int MCS_BOUND = 3;
563    static final int END_COPY = 4;
564    static final int INIT_COPY = 5;
565    static final int MCS_UNBIND = 6;
566    static final int START_CLEANING_PACKAGE = 7;
567    static final int FIND_INSTALL_LOC = 8;
568    static final int POST_INSTALL = 9;
569    static final int MCS_RECONNECT = 10;
570    static final int MCS_GIVE_UP = 11;
571    static final int UPDATED_MEDIA_STATUS = 12;
572    static final int WRITE_SETTINGS = 13;
573    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
574    static final int PACKAGE_VERIFIED = 15;
575    static final int CHECK_PENDING_VERIFICATION = 16;
576
577    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
578
579    // Delay time in millisecs
580    static final int BROADCAST_DELAY = 10 * 1000;
581
582    static UserManagerService sUserManager;
583
584    // Stores a list of users whose package restrictions file needs to be updated
585    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
586
587    final private DefaultContainerConnection mDefContainerConn =
588            new DefaultContainerConnection();
589    class DefaultContainerConnection implements ServiceConnection {
590        public void onServiceConnected(ComponentName name, IBinder service) {
591            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
592            IMediaContainerService imcs =
593                IMediaContainerService.Stub.asInterface(service);
594            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
595        }
596
597        public void onServiceDisconnected(ComponentName name) {
598            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
599        }
600    };
601
602    // Recordkeeping of restore-after-install operations that are currently in flight
603    // between the Package Manager and the Backup Manager
604    class PostInstallData {
605        public InstallArgs args;
606        public PackageInstalledInfo res;
607
608        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
609            args = _a;
610            res = _r;
611        }
612    };
613    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
614    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
615
616    private final String mRequiredVerifierPackage;
617
618    private final PackageUsage mPackageUsage = new PackageUsage();
619
620    private class PackageUsage {
621        private static final int WRITE_INTERVAL
622            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
623
624        private final Object mFileLock = new Object();
625        private final AtomicLong mLastWritten = new AtomicLong(0);
626        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
627
628        private boolean mIsHistoricalPackageUsageAvailable = true;
629
630        boolean isHistoricalPackageUsageAvailable() {
631            return mIsHistoricalPackageUsageAvailable;
632        }
633
634        void write(boolean force) {
635            if (force) {
636                writeInternal();
637                return;
638            }
639            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
640                && !DEBUG_DEXOPT) {
641                return;
642            }
643            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
644                new Thread("PackageUsage_DiskWriter") {
645                    @Override
646                    public void run() {
647                        try {
648                            writeInternal();
649                        } finally {
650                            mBackgroundWriteRunning.set(false);
651                        }
652                    }
653                }.start();
654            }
655        }
656
657        private void writeInternal() {
658            synchronized (mPackages) {
659                synchronized (mFileLock) {
660                    AtomicFile file = getFile();
661                    FileOutputStream f = null;
662                    try {
663                        f = file.startWrite();
664                        BufferedOutputStream out = new BufferedOutputStream(f);
665                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
666                        StringBuilder sb = new StringBuilder();
667                        for (PackageParser.Package pkg : mPackages.values()) {
668                            if (pkg.mLastPackageUsageTimeInMills == 0) {
669                                continue;
670                            }
671                            sb.setLength(0);
672                            sb.append(pkg.packageName);
673                            sb.append(' ');
674                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
675                            sb.append('\n');
676                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
677                        }
678                        out.flush();
679                        file.finishWrite(f);
680                    } catch (IOException e) {
681                        if (f != null) {
682                            file.failWrite(f);
683                        }
684                        Log.e(TAG, "Failed to write package usage times", e);
685                    }
686                }
687            }
688            mLastWritten.set(SystemClock.elapsedRealtime());
689        }
690
691        void readLP() {
692            synchronized (mFileLock) {
693                AtomicFile file = getFile();
694                BufferedInputStream in = null;
695                try {
696                    in = new BufferedInputStream(file.openRead());
697                    StringBuffer sb = new StringBuffer();
698                    while (true) {
699                        String packageName = readToken(in, sb, ' ');
700                        if (packageName == null) {
701                            break;
702                        }
703                        String timeInMillisString = readToken(in, sb, '\n');
704                        if (timeInMillisString == null) {
705                            throw new IOException("Failed to find last usage time for package "
706                                                  + packageName);
707                        }
708                        PackageParser.Package pkg = mPackages.get(packageName);
709                        if (pkg == null) {
710                            continue;
711                        }
712                        long timeInMillis;
713                        try {
714                            timeInMillis = Long.parseLong(timeInMillisString.toString());
715                        } catch (NumberFormatException e) {
716                            throw new IOException("Failed to parse " + timeInMillisString
717                                                  + " as a long.", e);
718                        }
719                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
720                    }
721                } catch (FileNotFoundException expected) {
722                    mIsHistoricalPackageUsageAvailable = false;
723                } catch (IOException e) {
724                    Log.w(TAG, "Failed to read package usage times", e);
725                } finally {
726                    IoUtils.closeQuietly(in);
727                }
728            }
729            mLastWritten.set(SystemClock.elapsedRealtime());
730        }
731
732        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
733                throws IOException {
734            sb.setLength(0);
735            while (true) {
736                int ch = in.read();
737                if (ch == -1) {
738                    if (sb.length() == 0) {
739                        return null;
740                    }
741                    throw new IOException("Unexpected EOF");
742                }
743                if (ch == endOfToken) {
744                    return sb.toString();
745                }
746                sb.append((char)ch);
747            }
748        }
749
750        private AtomicFile getFile() {
751            File dataDir = Environment.getDataDirectory();
752            File systemDir = new File(dataDir, "system");
753            File fname = new File(systemDir, "package-usage.list");
754            return new AtomicFile(fname);
755        }
756    }
757
758    class PackageHandler extends Handler {
759        private boolean mBound = false;
760        final ArrayList<HandlerParams> mPendingInstalls =
761            new ArrayList<HandlerParams>();
762
763        private boolean connectToService() {
764            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
765                    " DefaultContainerService");
766            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
767            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
768            if (mContext.bindServiceAsUser(service, mDefContainerConn,
769                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
770                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
771                mBound = true;
772                return true;
773            }
774            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
775            return false;
776        }
777
778        private void disconnectService() {
779            mContainerService = null;
780            mBound = false;
781            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
782            mContext.unbindService(mDefContainerConn);
783            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
784        }
785
786        PackageHandler(Looper looper) {
787            super(looper);
788        }
789
790        public void handleMessage(Message msg) {
791            try {
792                doHandleMessage(msg);
793            } finally {
794                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
795            }
796        }
797
798        void doHandleMessage(Message msg) {
799            switch (msg.what) {
800                case INIT_COPY: {
801                    HandlerParams params = (HandlerParams) msg.obj;
802                    int idx = mPendingInstalls.size();
803                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
804                    // If a bind was already initiated we dont really
805                    // need to do anything. The pending install
806                    // will be processed later on.
807                    if (!mBound) {
808                        // If this is the only one pending we might
809                        // have to bind to the service again.
810                        if (!connectToService()) {
811                            Slog.e(TAG, "Failed to bind to media container service");
812                            params.serviceError();
813                            return;
814                        } else {
815                            // Once we bind to the service, the first
816                            // pending request will be processed.
817                            mPendingInstalls.add(idx, params);
818                        }
819                    } else {
820                        mPendingInstalls.add(idx, params);
821                        // Already bound to the service. Just make
822                        // sure we trigger off processing the first request.
823                        if (idx == 0) {
824                            mHandler.sendEmptyMessage(MCS_BOUND);
825                        }
826                    }
827                    break;
828                }
829                case MCS_BOUND: {
830                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
831                    if (msg.obj != null) {
832                        mContainerService = (IMediaContainerService) msg.obj;
833                    }
834                    if (mContainerService == null) {
835                        // Something seriously wrong. Bail out
836                        Slog.e(TAG, "Cannot bind to media container service");
837                        for (HandlerParams params : mPendingInstalls) {
838                            // Indicate service bind error
839                            params.serviceError();
840                        }
841                        mPendingInstalls.clear();
842                    } else if (mPendingInstalls.size() > 0) {
843                        HandlerParams params = mPendingInstalls.get(0);
844                        if (params != null) {
845                            if (params.startCopy()) {
846                                // We are done...  look for more work or to
847                                // go idle.
848                                if (DEBUG_SD_INSTALL) Log.i(TAG,
849                                        "Checking for more work or unbind...");
850                                // Delete pending install
851                                if (mPendingInstalls.size() > 0) {
852                                    mPendingInstalls.remove(0);
853                                }
854                                if (mPendingInstalls.size() == 0) {
855                                    if (mBound) {
856                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
857                                                "Posting delayed MCS_UNBIND");
858                                        removeMessages(MCS_UNBIND);
859                                        Message ubmsg = obtainMessage(MCS_UNBIND);
860                                        // Unbind after a little delay, to avoid
861                                        // continual thrashing.
862                                        sendMessageDelayed(ubmsg, 10000);
863                                    }
864                                } else {
865                                    // There are more pending requests in queue.
866                                    // Just post MCS_BOUND message to trigger processing
867                                    // of next pending install.
868                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
869                                            "Posting MCS_BOUND for next work");
870                                    mHandler.sendEmptyMessage(MCS_BOUND);
871                                }
872                            }
873                        }
874                    } else {
875                        // Should never happen ideally.
876                        Slog.w(TAG, "Empty queue");
877                    }
878                    break;
879                }
880                case MCS_RECONNECT: {
881                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
882                    if (mPendingInstalls.size() > 0) {
883                        if (mBound) {
884                            disconnectService();
885                        }
886                        if (!connectToService()) {
887                            Slog.e(TAG, "Failed to bind to media container service");
888                            for (HandlerParams params : mPendingInstalls) {
889                                // Indicate service bind error
890                                params.serviceError();
891                            }
892                            mPendingInstalls.clear();
893                        }
894                    }
895                    break;
896                }
897                case MCS_UNBIND: {
898                    // If there is no actual work left, then time to unbind.
899                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
900
901                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
902                        if (mBound) {
903                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
904
905                            disconnectService();
906                        }
907                    } else if (mPendingInstalls.size() > 0) {
908                        // There are more pending requests in queue.
909                        // Just post MCS_BOUND message to trigger processing
910                        // of next pending install.
911                        mHandler.sendEmptyMessage(MCS_BOUND);
912                    }
913
914                    break;
915                }
916                case MCS_GIVE_UP: {
917                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
918                    mPendingInstalls.remove(0);
919                    break;
920                }
921                case SEND_PENDING_BROADCAST: {
922                    String packages[];
923                    ArrayList<String> components[];
924                    int size = 0;
925                    int uids[];
926                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
927                    synchronized (mPackages) {
928                        if (mPendingBroadcasts == null) {
929                            return;
930                        }
931                        size = mPendingBroadcasts.size();
932                        if (size <= 0) {
933                            // Nothing to be done. Just return
934                            return;
935                        }
936                        packages = new String[size];
937                        components = new ArrayList[size];
938                        uids = new int[size];
939                        int i = 0;  // filling out the above arrays
940
941                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
942                            int packageUserId = mPendingBroadcasts.userIdAt(n);
943                            Iterator<Map.Entry<String, ArrayList<String>>> it
944                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
945                                            .entrySet().iterator();
946                            while (it.hasNext() && i < size) {
947                                Map.Entry<String, ArrayList<String>> ent = it.next();
948                                packages[i] = ent.getKey();
949                                components[i] = ent.getValue();
950                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
951                                uids[i] = (ps != null)
952                                        ? UserHandle.getUid(packageUserId, ps.appId)
953                                        : -1;
954                                i++;
955                            }
956                        }
957                        size = i;
958                        mPendingBroadcasts.clear();
959                    }
960                    // Send broadcasts
961                    for (int i = 0; i < size; i++) {
962                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
963                    }
964                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
965                    break;
966                }
967                case START_CLEANING_PACKAGE: {
968                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
969                    final String packageName = (String)msg.obj;
970                    final int userId = msg.arg1;
971                    final boolean andCode = msg.arg2 != 0;
972                    synchronized (mPackages) {
973                        if (userId == UserHandle.USER_ALL) {
974                            int[] users = sUserManager.getUserIds();
975                            for (int user : users) {
976                                mSettings.addPackageToCleanLPw(
977                                        new PackageCleanItem(user, packageName, andCode));
978                            }
979                        } else {
980                            mSettings.addPackageToCleanLPw(
981                                    new PackageCleanItem(userId, packageName, andCode));
982                        }
983                    }
984                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
985                    startCleaningPackages();
986                } break;
987                case POST_INSTALL: {
988                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
989                    PostInstallData data = mRunningInstalls.get(msg.arg1);
990                    mRunningInstalls.delete(msg.arg1);
991                    boolean deleteOld = false;
992
993                    if (data != null) {
994                        InstallArgs args = data.args;
995                        PackageInstalledInfo res = data.res;
996
997                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
998                            res.removedInfo.sendBroadcast(false, true, false);
999                            Bundle extras = new Bundle(1);
1000                            extras.putInt(Intent.EXTRA_UID, res.uid);
1001                            // Determine the set of users who are adding this
1002                            // package for the first time vs. those who are seeing
1003                            // an update.
1004                            int[] firstUsers;
1005                            int[] updateUsers = new int[0];
1006                            if (res.origUsers == null || res.origUsers.length == 0) {
1007                                firstUsers = res.newUsers;
1008                            } else {
1009                                firstUsers = new int[0];
1010                                for (int i=0; i<res.newUsers.length; i++) {
1011                                    int user = res.newUsers[i];
1012                                    boolean isNew = true;
1013                                    for (int j=0; j<res.origUsers.length; j++) {
1014                                        if (res.origUsers[j] == user) {
1015                                            isNew = false;
1016                                            break;
1017                                        }
1018                                    }
1019                                    if (isNew) {
1020                                        int[] newFirst = new int[firstUsers.length+1];
1021                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1022                                                firstUsers.length);
1023                                        newFirst[firstUsers.length] = user;
1024                                        firstUsers = newFirst;
1025                                    } else {
1026                                        int[] newUpdate = new int[updateUsers.length+1];
1027                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1028                                                updateUsers.length);
1029                                        newUpdate[updateUsers.length] = user;
1030                                        updateUsers = newUpdate;
1031                                    }
1032                                }
1033                            }
1034                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1035                                    res.pkg.applicationInfo.packageName,
1036                                    extras, null, null, firstUsers);
1037                            final boolean update = res.removedInfo.removedPackage != null;
1038                            if (update) {
1039                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1040                            }
1041                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1042                                    res.pkg.applicationInfo.packageName,
1043                                    extras, null, null, updateUsers);
1044                            if (update) {
1045                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1046                                        res.pkg.applicationInfo.packageName,
1047                                        extras, null, null, updateUsers);
1048                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1049                                        null, null,
1050                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1051
1052                                // treat asec-hosted packages like removable media on upgrade
1053                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1054                                    if (DEBUG_INSTALL) {
1055                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1056                                                + " is ASEC-hosted -> AVAILABLE");
1057                                    }
1058                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1059                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1060                                    pkgList.add(res.pkg.applicationInfo.packageName);
1061                                    sendResourcesChangedBroadcast(true, true,
1062                                            pkgList,uidArray, null);
1063                                }
1064                            }
1065                            if (res.removedInfo.args != null) {
1066                                // Remove the replaced package's older resources safely now
1067                                deleteOld = true;
1068                            }
1069
1070                            // Log current value of "unknown sources" setting
1071                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1072                                getUnknownSourcesSettings());
1073                        }
1074                        // Force a gc to clear up things
1075                        Runtime.getRuntime().gc();
1076                        // We delete after a gc for applications  on sdcard.
1077                        if (deleteOld) {
1078                            synchronized (mInstallLock) {
1079                                res.removedInfo.args.doPostDeleteLI(true);
1080                            }
1081                        }
1082                        if (args.observer != null) {
1083                            try {
1084                                Bundle extras = extrasForInstallResult(res);
1085                                args.observer.onPackageInstalled(res.name, res.returnCode,
1086                                        res.returnMsg, extras);
1087                            } catch (RemoteException e) {
1088                                Slog.i(TAG, "Observer no longer exists.");
1089                            }
1090                        }
1091                    } else {
1092                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1093                    }
1094                } break;
1095                case UPDATED_MEDIA_STATUS: {
1096                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1097                    boolean reportStatus = msg.arg1 == 1;
1098                    boolean doGc = msg.arg2 == 1;
1099                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1100                    if (doGc) {
1101                        // Force a gc to clear up stale containers.
1102                        Runtime.getRuntime().gc();
1103                    }
1104                    if (msg.obj != null) {
1105                        @SuppressWarnings("unchecked")
1106                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1107                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1108                        // Unload containers
1109                        unloadAllContainers(args);
1110                    }
1111                    if (reportStatus) {
1112                        try {
1113                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1114                            PackageHelper.getMountService().finishMediaUpdate();
1115                        } catch (RemoteException e) {
1116                            Log.e(TAG, "MountService not running?");
1117                        }
1118                    }
1119                } break;
1120                case WRITE_SETTINGS: {
1121                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1122                    synchronized (mPackages) {
1123                        removeMessages(WRITE_SETTINGS);
1124                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1125                        mSettings.writeLPr();
1126                        mDirtyUsers.clear();
1127                    }
1128                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1129                } break;
1130                case WRITE_PACKAGE_RESTRICTIONS: {
1131                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1132                    synchronized (mPackages) {
1133                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1134                        for (int userId : mDirtyUsers) {
1135                            mSettings.writePackageRestrictionsLPr(userId);
1136                        }
1137                        mDirtyUsers.clear();
1138                    }
1139                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1140                } break;
1141                case CHECK_PENDING_VERIFICATION: {
1142                    final int verificationId = msg.arg1;
1143                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1144
1145                    if ((state != null) && !state.timeoutExtended()) {
1146                        final InstallArgs args = state.getInstallArgs();
1147                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1148
1149                        Slog.i(TAG, "Verification timed out for " + originUri);
1150                        mPendingVerification.remove(verificationId);
1151
1152                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1153
1154                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1155                            Slog.i(TAG, "Continuing with installation of " + originUri);
1156                            state.setVerifierResponse(Binder.getCallingUid(),
1157                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1158                            broadcastPackageVerified(verificationId, originUri,
1159                                    PackageManager.VERIFICATION_ALLOW,
1160                                    state.getInstallArgs().getUser());
1161                            try {
1162                                ret = args.copyApk(mContainerService, true);
1163                            } catch (RemoteException e) {
1164                                Slog.e(TAG, "Could not contact the ContainerService");
1165                            }
1166                        } else {
1167                            broadcastPackageVerified(verificationId, originUri,
1168                                    PackageManager.VERIFICATION_REJECT,
1169                                    state.getInstallArgs().getUser());
1170                        }
1171
1172                        processPendingInstall(args, ret);
1173                        mHandler.sendEmptyMessage(MCS_UNBIND);
1174                    }
1175                    break;
1176                }
1177                case PACKAGE_VERIFIED: {
1178                    final int verificationId = msg.arg1;
1179
1180                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1181                    if (state == null) {
1182                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1183                        break;
1184                    }
1185
1186                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1187
1188                    state.setVerifierResponse(response.callerUid, response.code);
1189
1190                    if (state.isVerificationComplete()) {
1191                        mPendingVerification.remove(verificationId);
1192
1193                        final InstallArgs args = state.getInstallArgs();
1194                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1195
1196                        int ret;
1197                        if (state.isInstallAllowed()) {
1198                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1199                            broadcastPackageVerified(verificationId, originUri,
1200                                    response.code, state.getInstallArgs().getUser());
1201                            try {
1202                                ret = args.copyApk(mContainerService, true);
1203                            } catch (RemoteException e) {
1204                                Slog.e(TAG, "Could not contact the ContainerService");
1205                            }
1206                        } else {
1207                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1208                        }
1209
1210                        processPendingInstall(args, ret);
1211
1212                        mHandler.sendEmptyMessage(MCS_UNBIND);
1213                    }
1214
1215                    break;
1216                }
1217            }
1218        }
1219    }
1220
1221    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1222        Bundle extras = null;
1223        switch (res.returnCode) {
1224            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1225                extras = new Bundle();
1226                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1227                        res.origPermission);
1228                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1229                        res.origPackage);
1230                break;
1231            }
1232        }
1233        return extras;
1234    }
1235
1236    void scheduleWriteSettingsLocked() {
1237        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1238            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1239        }
1240    }
1241
1242    void scheduleWritePackageRestrictionsLocked(int userId) {
1243        if (!sUserManager.exists(userId)) return;
1244        mDirtyUsers.add(userId);
1245        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1246            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1247        }
1248    }
1249
1250    public static final PackageManagerService main(Context context, Installer installer,
1251            boolean factoryTest, boolean onlyCore) {
1252        PackageManagerService m = new PackageManagerService(context, installer,
1253                factoryTest, onlyCore);
1254        ServiceManager.addService("package", m);
1255        return m;
1256    }
1257
1258    static String[] splitString(String str, char sep) {
1259        int count = 1;
1260        int i = 0;
1261        while ((i=str.indexOf(sep, i)) >= 0) {
1262            count++;
1263            i++;
1264        }
1265
1266        String[] res = new String[count];
1267        i=0;
1268        count = 0;
1269        int lastI=0;
1270        while ((i=str.indexOf(sep, i)) >= 0) {
1271            res[count] = str.substring(lastI, i);
1272            count++;
1273            i++;
1274            lastI = i;
1275        }
1276        res[count] = str.substring(lastI, str.length());
1277        return res;
1278    }
1279
1280    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1281        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1282                Context.DISPLAY_SERVICE);
1283        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1284    }
1285
1286    public PackageManagerService(Context context, Installer installer,
1287            boolean factoryTest, boolean onlyCore) {
1288        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1289                SystemClock.uptimeMillis());
1290
1291        if (mSdkVersion <= 0) {
1292            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1293        }
1294
1295        mContext = context;
1296        mFactoryTest = factoryTest;
1297        mOnlyCore = onlyCore;
1298        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1299        mMetrics = new DisplayMetrics();
1300        mSettings = new Settings(context);
1301        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1302                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1303        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1304                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1305        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1306                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1307        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1308                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1309        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1310                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1311        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1312                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1313
1314        // TODO: add a property to control this?
1315        long dexOptLRUThresholdInMinutes;
1316        if (mLazyDexOpt) {
1317            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1318        } else {
1319            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1320        }
1321        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1322
1323        String separateProcesses = SystemProperties.get("debug.separate_processes");
1324        if (separateProcesses != null && separateProcesses.length() > 0) {
1325            if ("*".equals(separateProcesses)) {
1326                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1327                mSeparateProcesses = null;
1328                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1329            } else {
1330                mDefParseFlags = 0;
1331                mSeparateProcesses = separateProcesses.split(",");
1332                Slog.w(TAG, "Running with debug.separate_processes: "
1333                        + separateProcesses);
1334            }
1335        } else {
1336            mDefParseFlags = 0;
1337            mSeparateProcesses = null;
1338        }
1339
1340        mInstaller = installer;
1341
1342        getDefaultDisplayMetrics(context, mMetrics);
1343
1344        SystemConfig systemConfig = SystemConfig.getInstance();
1345        mGlobalGids = systemConfig.getGlobalGids();
1346        mSystemPermissions = systemConfig.getSystemPermissions();
1347        mAvailableFeatures = systemConfig.getAvailableFeatures();
1348
1349        synchronized (mInstallLock) {
1350        // writer
1351        synchronized (mPackages) {
1352            mHandlerThread = new ServiceThread(TAG,
1353                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1354            mHandlerThread.start();
1355            mHandler = new PackageHandler(mHandlerThread.getLooper());
1356            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1357
1358            File dataDir = Environment.getDataDirectory();
1359            mAppDataDir = new File(dataDir, "data");
1360            mAppInstallDir = new File(dataDir, "app");
1361            mAppLib32InstallDir = new File(dataDir, "app-lib");
1362            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1363            mUserAppDataDir = new File(dataDir, "user");
1364            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1365
1366            sUserManager = new UserManagerService(context, this,
1367                    mInstallLock, mPackages);
1368
1369            // Propagate permission configuration in to package manager.
1370            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1371                    = systemConfig.getPermissions();
1372            for (int i=0; i<permConfig.size(); i++) {
1373                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1374                BasePermission bp = mSettings.mPermissions.get(perm.name);
1375                if (bp == null) {
1376                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1377                    mSettings.mPermissions.put(perm.name, bp);
1378                }
1379                if (perm.gids != null) {
1380                    bp.gids = appendInts(bp.gids, perm.gids);
1381                }
1382            }
1383
1384            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1385            for (int i=0; i<libConfig.size(); i++) {
1386                mSharedLibraries.put(libConfig.keyAt(i),
1387                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1388            }
1389
1390            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1391
1392            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1393                    mSdkVersion, mOnlyCore);
1394
1395            String customResolverActivity = Resources.getSystem().getString(
1396                    R.string.config_customResolverActivity);
1397            if (TextUtils.isEmpty(customResolverActivity)) {
1398                customResolverActivity = null;
1399            } else {
1400                mCustomResolverComponentName = ComponentName.unflattenFromString(
1401                        customResolverActivity);
1402            }
1403
1404            long startTime = SystemClock.uptimeMillis();
1405
1406            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1407                    startTime);
1408
1409            // Set flag to monitor and not change apk file paths when
1410            // scanning install directories.
1411            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1412
1413            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1414
1415            /**
1416             * Add everything in the in the boot class path to the
1417             * list of process files because dexopt will have been run
1418             * if necessary during zygote startup.
1419             */
1420            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1421            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1422
1423            if (bootClassPath != null) {
1424                String[] bootClassPathElements = splitString(bootClassPath, ':');
1425                for (String element : bootClassPathElements) {
1426                    alreadyDexOpted.add(element);
1427                }
1428            } else {
1429                Slog.w(TAG, "No BOOTCLASSPATH found!");
1430            }
1431
1432            if (systemServerClassPath != null) {
1433                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1434                for (String element : systemServerClassPathElements) {
1435                    alreadyDexOpted.add(element);
1436                }
1437            } else {
1438                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1439            }
1440
1441            final List<String> allInstructionSets = getAllInstructionSets();
1442            final String[] dexCodeInstructionSets =
1443                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1444
1445            /**
1446             * Ensure all external libraries have had dexopt run on them.
1447             */
1448            if (mSharedLibraries.size() > 0) {
1449                // NOTE: For now, we're compiling these system "shared libraries"
1450                // (and framework jars) into all available architectures. It's possible
1451                // to compile them only when we come across an app that uses them (there's
1452                // already logic for that in scanPackageLI) but that adds some complexity.
1453                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1454                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1455                        final String lib = libEntry.path;
1456                        if (lib == null) {
1457                            continue;
1458                        }
1459
1460                        try {
1461                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1462                                                                                 dexCodeInstructionSet,
1463                                                                                 false);
1464                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1465                                alreadyDexOpted.add(lib);
1466
1467                                // The list of "shared libraries" we have at this point is
1468                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1469                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1470                                } else {
1471                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1472                                }
1473                            }
1474                        } catch (FileNotFoundException e) {
1475                            Slog.w(TAG, "Library not found: " + lib);
1476                        } catch (IOException e) {
1477                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1478                                    + e.getMessage());
1479                        }
1480                    }
1481                }
1482            }
1483
1484            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1485
1486            // Gross hack for now: we know this file doesn't contain any
1487            // code, so don't dexopt it to avoid the resulting log spew.
1488            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1489
1490            // Gross hack for now: we know this file is only part of
1491            // the boot class path for art, so don't dexopt it to
1492            // avoid the resulting log spew.
1493            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1494
1495            /**
1496             * And there are a number of commands implemented in Java, which
1497             * we currently need to do the dexopt on so that they can be
1498             * run from a non-root shell.
1499             */
1500            String[] frameworkFiles = frameworkDir.list();
1501            if (frameworkFiles != null) {
1502                // TODO: We could compile these only for the most preferred ABI. We should
1503                // first double check that the dex files for these commands are not referenced
1504                // by other system apps.
1505                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1506                    for (int i=0; i<frameworkFiles.length; i++) {
1507                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1508                        String path = libPath.getPath();
1509                        // Skip the file if we already did it.
1510                        if (alreadyDexOpted.contains(path)) {
1511                            continue;
1512                        }
1513                        // Skip the file if it is not a type we want to dexopt.
1514                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1515                            continue;
1516                        }
1517                        try {
1518                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1519                                                                                 dexCodeInstructionSet,
1520                                                                                 false);
1521                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1522                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1523                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1524                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1525                            }
1526                        } catch (FileNotFoundException e) {
1527                            Slog.w(TAG, "Jar not found: " + path);
1528                        } catch (IOException e) {
1529                            Slog.w(TAG, "Exception reading jar: " + path, e);
1530                        }
1531                    }
1532                }
1533            }
1534
1535            // Collect vendor overlay packages.
1536            // (Do this before scanning any apps.)
1537            // For security and version matching reason, only consider
1538            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1539            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1540            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1541                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1542
1543            // Find base frameworks (resource packages without code).
1544            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1545                    | PackageParser.PARSE_IS_SYSTEM_DIR
1546                    | PackageParser.PARSE_IS_PRIVILEGED,
1547                    scanFlags | SCAN_NO_DEX, 0);
1548
1549            // Collected privileged system packages.
1550            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1551            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1552                    | PackageParser.PARSE_IS_SYSTEM_DIR
1553                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1554
1555            // Collect ordinary system packages.
1556            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1557            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1558                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1559
1560            // Collect all vendor packages.
1561            File vendorAppDir = new File("/vendor/app");
1562            try {
1563                vendorAppDir = vendorAppDir.getCanonicalFile();
1564            } catch (IOException e) {
1565                // failed to look up canonical path, continue with original one
1566            }
1567            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1568                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1569
1570            // Collect all OEM packages.
1571            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1572            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1573                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1574
1575            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1576            mInstaller.moveFiles();
1577
1578            // Prune any system packages that no longer exist.
1579            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1580            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1581            if (!mOnlyCore) {
1582                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1583                while (psit.hasNext()) {
1584                    PackageSetting ps = psit.next();
1585
1586                    /*
1587                     * If this is not a system app, it can't be a
1588                     * disable system app.
1589                     */
1590                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1591                        continue;
1592                    }
1593
1594                    /*
1595                     * If the package is scanned, it's not erased.
1596                     */
1597                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1598                    if (scannedPkg != null) {
1599                        /*
1600                         * If the system app is both scanned and in the
1601                         * disabled packages list, then it must have been
1602                         * added via OTA. Remove it from the currently
1603                         * scanned package so the previously user-installed
1604                         * application can be scanned.
1605                         */
1606                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1607                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1608                                    + ps.name + "; removing system app.  Last known codePath="
1609                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1610                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1611                                    + scannedPkg.mVersionCode);
1612                            removePackageLI(ps, true);
1613                            expectingBetter.put(ps.name, ps.codePath);
1614                        }
1615
1616                        continue;
1617                    }
1618
1619                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1620                        psit.remove();
1621                        logCriticalInfo(Log.WARN, "System package " + ps.name
1622                                + " no longer exists; wiping its data");
1623                        removeDataDirsLI(ps.name);
1624                    } else {
1625                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1626                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1627                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1628                        }
1629                    }
1630                }
1631            }
1632
1633            //look for any incomplete package installations
1634            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1635            //clean up list
1636            for(int i = 0; i < deletePkgsList.size(); i++) {
1637                //clean up here
1638                cleanupInstallFailedPackage(deletePkgsList.get(i));
1639            }
1640            //delete tmp files
1641            deleteTempPackageFiles();
1642
1643            // Remove any shared userIDs that have no associated packages
1644            mSettings.pruneSharedUsersLPw();
1645
1646            if (!mOnlyCore) {
1647                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1648                        SystemClock.uptimeMillis());
1649                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1650
1651                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1652                        scanFlags, 0);
1653
1654                /**
1655                 * Remove disable package settings for any updated system
1656                 * apps that were removed via an OTA. If they're not a
1657                 * previously-updated app, remove them completely.
1658                 * Otherwise, just revoke their system-level permissions.
1659                 */
1660                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1661                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1662                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1663
1664                    String msg;
1665                    if (deletedPkg == null) {
1666                        msg = "Updated system package " + deletedAppName
1667                                + " no longer exists; wiping its data";
1668                        removeDataDirsLI(deletedAppName);
1669                    } else {
1670                        msg = "Updated system app + " + deletedAppName
1671                                + " no longer present; removing system privileges for "
1672                                + deletedAppName;
1673
1674                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1675
1676                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1677                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1678                    }
1679                    logCriticalInfo(Log.WARN, msg);
1680                }
1681
1682                /**
1683                 * Make sure all system apps that we expected to appear on
1684                 * the userdata partition actually showed up. If they never
1685                 * appeared, crawl back and revive the system version.
1686                 */
1687                for (int i = 0; i < expectingBetter.size(); i++) {
1688                    final String packageName = expectingBetter.keyAt(i);
1689                    if (!mPackages.containsKey(packageName)) {
1690                        final File scanFile = expectingBetter.valueAt(i);
1691
1692                        logCriticalInfo(Log.WARN, "Expected better " + packageName
1693                                + " but never showed up; reverting to system");
1694
1695                        final int reparseFlags;
1696                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
1697                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1698                                    | PackageParser.PARSE_IS_SYSTEM_DIR
1699                                    | PackageParser.PARSE_IS_PRIVILEGED;
1700                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
1701                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1702                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1703                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
1704                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1705                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1706                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
1707                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1708                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1709                        } else {
1710                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
1711                            continue;
1712                        }
1713
1714                        mSettings.enableSystemPackageLPw(packageName);
1715
1716                        try {
1717                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
1718                        } catch (PackageManagerException e) {
1719                            Slog.e(TAG, "Failed to parse original system package: "
1720                                    + e.getMessage());
1721                        }
1722                    }
1723                }
1724            }
1725
1726            // Now that we know all of the shared libraries, update all clients to have
1727            // the correct library paths.
1728            updateAllSharedLibrariesLPw();
1729
1730            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1731                // NOTE: We ignore potential failures here during a system scan (like
1732                // the rest of the commands above) because there's precious little we
1733                // can do about it. A settings error is reported, though.
1734                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1735                        false /* force dexopt */, false /* defer dexopt */);
1736            }
1737
1738            // Now that we know all the packages we are keeping,
1739            // read and update their last usage times.
1740            mPackageUsage.readLP();
1741
1742            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1743                    SystemClock.uptimeMillis());
1744            Slog.i(TAG, "Time to scan packages: "
1745                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1746                    + " seconds");
1747
1748            // If the platform SDK has changed since the last time we booted,
1749            // we need to re-grant app permission to catch any new ones that
1750            // appear.  This is really a hack, and means that apps can in some
1751            // cases get permissions that the user didn't initially explicitly
1752            // allow...  it would be nice to have some better way to handle
1753            // this situation.
1754            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1755                    != mSdkVersion;
1756            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1757                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1758                    + "; regranting permissions for internal storage");
1759            mSettings.mInternalSdkPlatform = mSdkVersion;
1760
1761            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1762                    | (regrantPermissions
1763                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1764                            : 0));
1765
1766            // If this is the first boot, and it is a normal boot, then
1767            // we need to initialize the default preferred apps.
1768            if (!mRestoredSettings && !onlyCore) {
1769                mSettings.readDefaultPreferredAppsLPw(this, 0);
1770            }
1771
1772            // If this is first boot after an OTA, and a normal boot, then
1773            // we need to clear code cache directories.
1774            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
1775            if (mIsUpgrade && !onlyCore) {
1776                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1777                for (String pkgName : mSettings.mPackages.keySet()) {
1778                    deleteCodeCacheDirsLI(pkgName);
1779                }
1780                mSettings.mFingerprint = Build.FINGERPRINT;
1781            }
1782
1783            // All the changes are done during package scanning.
1784            mSettings.updateInternalDatabaseVersion();
1785
1786            // can downgrade to reader
1787            mSettings.writeLPr();
1788
1789            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1790                    SystemClock.uptimeMillis());
1791
1792
1793            mRequiredVerifierPackage = getRequiredVerifierLPr();
1794        } // synchronized (mPackages)
1795        } // synchronized (mInstallLock)
1796
1797        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1798
1799        // Now after opening every single application zip, make sure they
1800        // are all flushed.  Not really needed, but keeps things nice and
1801        // tidy.
1802        Runtime.getRuntime().gc();
1803    }
1804
1805    @Override
1806    public boolean isFirstBoot() {
1807        return !mRestoredSettings;
1808    }
1809
1810    @Override
1811    public boolean isOnlyCoreApps() {
1812        return mOnlyCore;
1813    }
1814
1815    @Override
1816    public boolean isUpgrade() {
1817        return mIsUpgrade;
1818    }
1819
1820    private String getRequiredVerifierLPr() {
1821        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1822        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1823                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1824
1825        String requiredVerifier = null;
1826
1827        final int N = receivers.size();
1828        for (int i = 0; i < N; i++) {
1829            final ResolveInfo info = receivers.get(i);
1830
1831            if (info.activityInfo == null) {
1832                continue;
1833            }
1834
1835            final String packageName = info.activityInfo.packageName;
1836
1837            final PackageSetting ps = mSettings.mPackages.get(packageName);
1838            if (ps == null) {
1839                continue;
1840            }
1841
1842            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1843            if (!gp.grantedPermissions
1844                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1845                continue;
1846            }
1847
1848            if (requiredVerifier != null) {
1849                throw new RuntimeException("There can be only one required verifier");
1850            }
1851
1852            requiredVerifier = packageName;
1853        }
1854
1855        return requiredVerifier;
1856    }
1857
1858    @Override
1859    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1860            throws RemoteException {
1861        try {
1862            return super.onTransact(code, data, reply, flags);
1863        } catch (RuntimeException e) {
1864            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1865                Slog.wtf(TAG, "Package Manager Crash", e);
1866            }
1867            throw e;
1868        }
1869    }
1870
1871    void cleanupInstallFailedPackage(PackageSetting ps) {
1872        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
1873
1874        removeDataDirsLI(ps.name);
1875        if (ps.codePath != null) {
1876            if (ps.codePath.isDirectory()) {
1877                FileUtils.deleteContents(ps.codePath);
1878            }
1879            ps.codePath.delete();
1880        }
1881        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1882            if (ps.resourcePath.isDirectory()) {
1883                FileUtils.deleteContents(ps.resourcePath);
1884            }
1885            ps.resourcePath.delete();
1886        }
1887        mSettings.removePackageLPw(ps.name);
1888    }
1889
1890    static int[] appendInts(int[] cur, int[] add) {
1891        if (add == null) return cur;
1892        if (cur == null) return add;
1893        final int N = add.length;
1894        for (int i=0; i<N; i++) {
1895            cur = appendInt(cur, add[i]);
1896        }
1897        return cur;
1898    }
1899
1900    static int[] removeInts(int[] cur, int[] rem) {
1901        if (rem == null) return cur;
1902        if (cur == null) return cur;
1903        final int N = rem.length;
1904        for (int i=0; i<N; i++) {
1905            cur = removeInt(cur, rem[i]);
1906        }
1907        return cur;
1908    }
1909
1910    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1911        if (!sUserManager.exists(userId)) return null;
1912        final PackageSetting ps = (PackageSetting) p.mExtras;
1913        if (ps == null) {
1914            return null;
1915        }
1916        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1917        final PackageUserState state = ps.readUserState(userId);
1918        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1919                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1920                state, userId);
1921    }
1922
1923    @Override
1924    public boolean isPackageAvailable(String packageName, int userId) {
1925        if (!sUserManager.exists(userId)) return false;
1926        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
1927        synchronized (mPackages) {
1928            PackageParser.Package p = mPackages.get(packageName);
1929            if (p != null) {
1930                final PackageSetting ps = (PackageSetting) p.mExtras;
1931                if (ps != null) {
1932                    final PackageUserState state = ps.readUserState(userId);
1933                    if (state != null) {
1934                        return PackageParser.isAvailable(state);
1935                    }
1936                }
1937            }
1938        }
1939        return false;
1940    }
1941
1942    @Override
1943    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1944        if (!sUserManager.exists(userId)) return null;
1945        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
1946        // reader
1947        synchronized (mPackages) {
1948            PackageParser.Package p = mPackages.get(packageName);
1949            if (DEBUG_PACKAGE_INFO)
1950                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1951            if (p != null) {
1952                return generatePackageInfo(p, flags, userId);
1953            }
1954            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1955                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1956            }
1957        }
1958        return null;
1959    }
1960
1961    @Override
1962    public String[] currentToCanonicalPackageNames(String[] names) {
1963        String[] out = new String[names.length];
1964        // reader
1965        synchronized (mPackages) {
1966            for (int i=names.length-1; i>=0; i--) {
1967                PackageSetting ps = mSettings.mPackages.get(names[i]);
1968                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1969            }
1970        }
1971        return out;
1972    }
1973
1974    @Override
1975    public String[] canonicalToCurrentPackageNames(String[] names) {
1976        String[] out = new String[names.length];
1977        // reader
1978        synchronized (mPackages) {
1979            for (int i=names.length-1; i>=0; i--) {
1980                String cur = mSettings.mRenamedPackages.get(names[i]);
1981                out[i] = cur != null ? cur : names[i];
1982            }
1983        }
1984        return out;
1985    }
1986
1987    @Override
1988    public int getPackageUid(String packageName, int userId) {
1989        if (!sUserManager.exists(userId)) return -1;
1990        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
1991        // reader
1992        synchronized (mPackages) {
1993            PackageParser.Package p = mPackages.get(packageName);
1994            if(p != null) {
1995                return UserHandle.getUid(userId, p.applicationInfo.uid);
1996            }
1997            PackageSetting ps = mSettings.mPackages.get(packageName);
1998            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1999                return -1;
2000            }
2001            p = ps.pkg;
2002            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2003        }
2004    }
2005
2006    @Override
2007    public int[] getPackageGids(String packageName) {
2008        // reader
2009        synchronized (mPackages) {
2010            PackageParser.Package p = mPackages.get(packageName);
2011            if (DEBUG_PACKAGE_INFO)
2012                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2013            if (p != null) {
2014                final PackageSetting ps = (PackageSetting)p.mExtras;
2015                return ps.getGids();
2016            }
2017        }
2018        // stupid thing to indicate an error.
2019        return new int[0];
2020    }
2021
2022    static final PermissionInfo generatePermissionInfo(
2023            BasePermission bp, int flags) {
2024        if (bp.perm != null) {
2025            return PackageParser.generatePermissionInfo(bp.perm, flags);
2026        }
2027        PermissionInfo pi = new PermissionInfo();
2028        pi.name = bp.name;
2029        pi.packageName = bp.sourcePackage;
2030        pi.nonLocalizedLabel = bp.name;
2031        pi.protectionLevel = bp.protectionLevel;
2032        return pi;
2033    }
2034
2035    @Override
2036    public PermissionInfo getPermissionInfo(String name, int flags) {
2037        // reader
2038        synchronized (mPackages) {
2039            final BasePermission p = mSettings.mPermissions.get(name);
2040            if (p != null) {
2041                return generatePermissionInfo(p, flags);
2042            }
2043            return null;
2044        }
2045    }
2046
2047    @Override
2048    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2049        // reader
2050        synchronized (mPackages) {
2051            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2052            for (BasePermission p : mSettings.mPermissions.values()) {
2053                if (group == null) {
2054                    if (p.perm == null || p.perm.info.group == null) {
2055                        out.add(generatePermissionInfo(p, flags));
2056                    }
2057                } else {
2058                    if (p.perm != null && group.equals(p.perm.info.group)) {
2059                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2060                    }
2061                }
2062            }
2063
2064            if (out.size() > 0) {
2065                return out;
2066            }
2067            return mPermissionGroups.containsKey(group) ? out : null;
2068        }
2069    }
2070
2071    @Override
2072    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2073        // reader
2074        synchronized (mPackages) {
2075            return PackageParser.generatePermissionGroupInfo(
2076                    mPermissionGroups.get(name), flags);
2077        }
2078    }
2079
2080    @Override
2081    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2082        // reader
2083        synchronized (mPackages) {
2084            final int N = mPermissionGroups.size();
2085            ArrayList<PermissionGroupInfo> out
2086                    = new ArrayList<PermissionGroupInfo>(N);
2087            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2088                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2089            }
2090            return out;
2091        }
2092    }
2093
2094    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2095            int userId) {
2096        if (!sUserManager.exists(userId)) return null;
2097        PackageSetting ps = mSettings.mPackages.get(packageName);
2098        if (ps != null) {
2099            if (ps.pkg == null) {
2100                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2101                        flags, userId);
2102                if (pInfo != null) {
2103                    return pInfo.applicationInfo;
2104                }
2105                return null;
2106            }
2107            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2108                    ps.readUserState(userId), userId);
2109        }
2110        return null;
2111    }
2112
2113    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2114            int userId) {
2115        if (!sUserManager.exists(userId)) return null;
2116        PackageSetting ps = mSettings.mPackages.get(packageName);
2117        if (ps != null) {
2118            PackageParser.Package pkg = ps.pkg;
2119            if (pkg == null) {
2120                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2121                    return null;
2122                }
2123                // Only data remains, so we aren't worried about code paths
2124                pkg = new PackageParser.Package(packageName);
2125                pkg.applicationInfo.packageName = packageName;
2126                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2127                pkg.applicationInfo.dataDir =
2128                        getDataPathForPackage(packageName, 0).getPath();
2129                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2130                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2131            }
2132            return generatePackageInfo(pkg, flags, userId);
2133        }
2134        return null;
2135    }
2136
2137    @Override
2138    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2139        if (!sUserManager.exists(userId)) return null;
2140        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2141        // writer
2142        synchronized (mPackages) {
2143            PackageParser.Package p = mPackages.get(packageName);
2144            if (DEBUG_PACKAGE_INFO) Log.v(
2145                    TAG, "getApplicationInfo " + packageName
2146                    + ": " + p);
2147            if (p != null) {
2148                PackageSetting ps = mSettings.mPackages.get(packageName);
2149                if (ps == null) return null;
2150                // Note: isEnabledLP() does not apply here - always return info
2151                return PackageParser.generateApplicationInfo(
2152                        p, flags, ps.readUserState(userId), userId);
2153            }
2154            if ("android".equals(packageName)||"system".equals(packageName)) {
2155                return mAndroidApplication;
2156            }
2157            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2158                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2159            }
2160        }
2161        return null;
2162    }
2163
2164
2165    @Override
2166    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2167        mContext.enforceCallingOrSelfPermission(
2168                android.Manifest.permission.CLEAR_APP_CACHE, null);
2169        // Queue up an async operation since clearing cache may take a little while.
2170        mHandler.post(new Runnable() {
2171            public void run() {
2172                mHandler.removeCallbacks(this);
2173                int retCode = -1;
2174                synchronized (mInstallLock) {
2175                    retCode = mInstaller.freeCache(freeStorageSize);
2176                    if (retCode < 0) {
2177                        Slog.w(TAG, "Couldn't clear application caches");
2178                    }
2179                }
2180                if (observer != null) {
2181                    try {
2182                        observer.onRemoveCompleted(null, (retCode >= 0));
2183                    } catch (RemoteException e) {
2184                        Slog.w(TAG, "RemoveException when invoking call back");
2185                    }
2186                }
2187            }
2188        });
2189    }
2190
2191    @Override
2192    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2193        mContext.enforceCallingOrSelfPermission(
2194                android.Manifest.permission.CLEAR_APP_CACHE, null);
2195        // Queue up an async operation since clearing cache may take a little while.
2196        mHandler.post(new Runnable() {
2197            public void run() {
2198                mHandler.removeCallbacks(this);
2199                int retCode = -1;
2200                synchronized (mInstallLock) {
2201                    retCode = mInstaller.freeCache(freeStorageSize);
2202                    if (retCode < 0) {
2203                        Slog.w(TAG, "Couldn't clear application caches");
2204                    }
2205                }
2206                if(pi != null) {
2207                    try {
2208                        // Callback via pending intent
2209                        int code = (retCode >= 0) ? 1 : 0;
2210                        pi.sendIntent(null, code, null,
2211                                null, null);
2212                    } catch (SendIntentException e1) {
2213                        Slog.i(TAG, "Failed to send pending intent");
2214                    }
2215                }
2216            }
2217        });
2218    }
2219
2220    void freeStorage(long freeStorageSize) throws IOException {
2221        synchronized (mInstallLock) {
2222            if (mInstaller.freeCache(freeStorageSize) < 0) {
2223                throw new IOException("Failed to free enough space");
2224            }
2225        }
2226    }
2227
2228    @Override
2229    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2230        if (!sUserManager.exists(userId)) return null;
2231        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2232        synchronized (mPackages) {
2233            PackageParser.Activity a = mActivities.mActivities.get(component);
2234
2235            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2236            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2237                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2238                if (ps == null) return null;
2239                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2240                        userId);
2241            }
2242            if (mResolveComponentName.equals(component)) {
2243                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2244                        new PackageUserState(), userId);
2245            }
2246        }
2247        return null;
2248    }
2249
2250    @Override
2251    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2252            String resolvedType) {
2253        synchronized (mPackages) {
2254            PackageParser.Activity a = mActivities.mActivities.get(component);
2255            if (a == null) {
2256                return false;
2257            }
2258            for (int i=0; i<a.intents.size(); i++) {
2259                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2260                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2261                    return true;
2262                }
2263            }
2264            return false;
2265        }
2266    }
2267
2268    @Override
2269    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2270        if (!sUserManager.exists(userId)) return null;
2271        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2272        synchronized (mPackages) {
2273            PackageParser.Activity a = mReceivers.mActivities.get(component);
2274            if (DEBUG_PACKAGE_INFO) Log.v(
2275                TAG, "getReceiverInfo " + component + ": " + a);
2276            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2277                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2278                if (ps == null) return null;
2279                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2280                        userId);
2281            }
2282        }
2283        return null;
2284    }
2285
2286    @Override
2287    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2288        if (!sUserManager.exists(userId)) return null;
2289        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2290        synchronized (mPackages) {
2291            PackageParser.Service s = mServices.mServices.get(component);
2292            if (DEBUG_PACKAGE_INFO) Log.v(
2293                TAG, "getServiceInfo " + component + ": " + s);
2294            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2295                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2296                if (ps == null) return null;
2297                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2298                        userId);
2299            }
2300        }
2301        return null;
2302    }
2303
2304    @Override
2305    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2306        if (!sUserManager.exists(userId)) return null;
2307        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2308        synchronized (mPackages) {
2309            PackageParser.Provider p = mProviders.mProviders.get(component);
2310            if (DEBUG_PACKAGE_INFO) Log.v(
2311                TAG, "getProviderInfo " + component + ": " + p);
2312            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2313                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2314                if (ps == null) return null;
2315                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2316                        userId);
2317            }
2318        }
2319        return null;
2320    }
2321
2322    @Override
2323    public String[] getSystemSharedLibraryNames() {
2324        Set<String> libSet;
2325        synchronized (mPackages) {
2326            libSet = mSharedLibraries.keySet();
2327            int size = libSet.size();
2328            if (size > 0) {
2329                String[] libs = new String[size];
2330                libSet.toArray(libs);
2331                return libs;
2332            }
2333        }
2334        return null;
2335    }
2336
2337    @Override
2338    public FeatureInfo[] getSystemAvailableFeatures() {
2339        Collection<FeatureInfo> featSet;
2340        synchronized (mPackages) {
2341            featSet = mAvailableFeatures.values();
2342            int size = featSet.size();
2343            if (size > 0) {
2344                FeatureInfo[] features = new FeatureInfo[size+1];
2345                featSet.toArray(features);
2346                FeatureInfo fi = new FeatureInfo();
2347                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2348                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2349                features[size] = fi;
2350                return features;
2351            }
2352        }
2353        return null;
2354    }
2355
2356    @Override
2357    public boolean hasSystemFeature(String name) {
2358        synchronized (mPackages) {
2359            return mAvailableFeatures.containsKey(name);
2360        }
2361    }
2362
2363    private void checkValidCaller(int uid, int userId) {
2364        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2365            return;
2366
2367        throw new SecurityException("Caller uid=" + uid
2368                + " is not privileged to communicate with user=" + userId);
2369    }
2370
2371    @Override
2372    public int checkPermission(String permName, String pkgName) {
2373        synchronized (mPackages) {
2374            PackageParser.Package p = mPackages.get(pkgName);
2375            if (p != null && p.mExtras != null) {
2376                PackageSetting ps = (PackageSetting)p.mExtras;
2377                if (ps.sharedUser != null) {
2378                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2379                        return PackageManager.PERMISSION_GRANTED;
2380                    }
2381                } else if (ps.grantedPermissions.contains(permName)) {
2382                    return PackageManager.PERMISSION_GRANTED;
2383                }
2384            }
2385        }
2386        return PackageManager.PERMISSION_DENIED;
2387    }
2388
2389    @Override
2390    public int checkUidPermission(String permName, int uid) {
2391        synchronized (mPackages) {
2392            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2393            if (obj != null) {
2394                GrantedPermissions gp = (GrantedPermissions)obj;
2395                if (gp.grantedPermissions.contains(permName)) {
2396                    return PackageManager.PERMISSION_GRANTED;
2397                }
2398            } else {
2399                ArraySet<String> perms = mSystemPermissions.get(uid);
2400                if (perms != null && perms.contains(permName)) {
2401                    return PackageManager.PERMISSION_GRANTED;
2402                }
2403            }
2404        }
2405        return PackageManager.PERMISSION_DENIED;
2406    }
2407
2408    /**
2409     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2410     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2411     * @param checkShell TODO(yamasani):
2412     * @param message the message to log on security exception
2413     */
2414    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2415            boolean checkShell, String message) {
2416        if (userId < 0) {
2417            throw new IllegalArgumentException("Invalid userId " + userId);
2418        }
2419        if (checkShell) {
2420            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2421        }
2422        if (userId == UserHandle.getUserId(callingUid)) return;
2423        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2424            if (requireFullPermission) {
2425                mContext.enforceCallingOrSelfPermission(
2426                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2427            } else {
2428                try {
2429                    mContext.enforceCallingOrSelfPermission(
2430                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2431                } catch (SecurityException se) {
2432                    mContext.enforceCallingOrSelfPermission(
2433                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2434                }
2435            }
2436        }
2437    }
2438
2439    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2440        if (callingUid == Process.SHELL_UID) {
2441            if (userHandle >= 0
2442                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2443                throw new SecurityException("Shell does not have permission to access user "
2444                        + userHandle);
2445            } else if (userHandle < 0) {
2446                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2447                        + Debug.getCallers(3));
2448            }
2449        }
2450    }
2451
2452    private BasePermission findPermissionTreeLP(String permName) {
2453        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2454            if (permName.startsWith(bp.name) &&
2455                    permName.length() > bp.name.length() &&
2456                    permName.charAt(bp.name.length()) == '.') {
2457                return bp;
2458            }
2459        }
2460        return null;
2461    }
2462
2463    private BasePermission checkPermissionTreeLP(String permName) {
2464        if (permName != null) {
2465            BasePermission bp = findPermissionTreeLP(permName);
2466            if (bp != null) {
2467                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2468                    return bp;
2469                }
2470                throw new SecurityException("Calling uid "
2471                        + Binder.getCallingUid()
2472                        + " is not allowed to add to permission tree "
2473                        + bp.name + " owned by uid " + bp.uid);
2474            }
2475        }
2476        throw new SecurityException("No permission tree found for " + permName);
2477    }
2478
2479    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2480        if (s1 == null) {
2481            return s2 == null;
2482        }
2483        if (s2 == null) {
2484            return false;
2485        }
2486        if (s1.getClass() != s2.getClass()) {
2487            return false;
2488        }
2489        return s1.equals(s2);
2490    }
2491
2492    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2493        if (pi1.icon != pi2.icon) return false;
2494        if (pi1.logo != pi2.logo) return false;
2495        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2496        if (!compareStrings(pi1.name, pi2.name)) return false;
2497        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2498        // We'll take care of setting this one.
2499        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2500        // These are not currently stored in settings.
2501        //if (!compareStrings(pi1.group, pi2.group)) return false;
2502        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2503        //if (pi1.labelRes != pi2.labelRes) return false;
2504        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2505        return true;
2506    }
2507
2508    int permissionInfoFootprint(PermissionInfo info) {
2509        int size = info.name.length();
2510        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2511        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2512        return size;
2513    }
2514
2515    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2516        int size = 0;
2517        for (BasePermission perm : mSettings.mPermissions.values()) {
2518            if (perm.uid == tree.uid) {
2519                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2520            }
2521        }
2522        return size;
2523    }
2524
2525    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2526        // We calculate the max size of permissions defined by this uid and throw
2527        // if that plus the size of 'info' would exceed our stated maximum.
2528        if (tree.uid != Process.SYSTEM_UID) {
2529            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2530            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2531                throw new SecurityException("Permission tree size cap exceeded");
2532            }
2533        }
2534    }
2535
2536    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2537        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2538            throw new SecurityException("Label must be specified in permission");
2539        }
2540        BasePermission tree = checkPermissionTreeLP(info.name);
2541        BasePermission bp = mSettings.mPermissions.get(info.name);
2542        boolean added = bp == null;
2543        boolean changed = true;
2544        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2545        if (added) {
2546            enforcePermissionCapLocked(info, tree);
2547            bp = new BasePermission(info.name, tree.sourcePackage,
2548                    BasePermission.TYPE_DYNAMIC);
2549        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2550            throw new SecurityException(
2551                    "Not allowed to modify non-dynamic permission "
2552                    + info.name);
2553        } else {
2554            if (bp.protectionLevel == fixedLevel
2555                    && bp.perm.owner.equals(tree.perm.owner)
2556                    && bp.uid == tree.uid
2557                    && comparePermissionInfos(bp.perm.info, info)) {
2558                changed = false;
2559            }
2560        }
2561        bp.protectionLevel = fixedLevel;
2562        info = new PermissionInfo(info);
2563        info.protectionLevel = fixedLevel;
2564        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2565        bp.perm.info.packageName = tree.perm.info.packageName;
2566        bp.uid = tree.uid;
2567        if (added) {
2568            mSettings.mPermissions.put(info.name, bp);
2569        }
2570        if (changed) {
2571            if (!async) {
2572                mSettings.writeLPr();
2573            } else {
2574                scheduleWriteSettingsLocked();
2575            }
2576        }
2577        return added;
2578    }
2579
2580    @Override
2581    public boolean addPermission(PermissionInfo info) {
2582        synchronized (mPackages) {
2583            return addPermissionLocked(info, false);
2584        }
2585    }
2586
2587    @Override
2588    public boolean addPermissionAsync(PermissionInfo info) {
2589        synchronized (mPackages) {
2590            return addPermissionLocked(info, true);
2591        }
2592    }
2593
2594    @Override
2595    public void removePermission(String name) {
2596        synchronized (mPackages) {
2597            checkPermissionTreeLP(name);
2598            BasePermission bp = mSettings.mPermissions.get(name);
2599            if (bp != null) {
2600                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2601                    throw new SecurityException(
2602                            "Not allowed to modify non-dynamic permission "
2603                            + name);
2604                }
2605                mSettings.mPermissions.remove(name);
2606                mSettings.writeLPr();
2607            }
2608        }
2609    }
2610
2611    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2612        int index = pkg.requestedPermissions.indexOf(bp.name);
2613        if (index == -1) {
2614            throw new SecurityException("Package " + pkg.packageName
2615                    + " has not requested permission " + bp.name);
2616        }
2617        boolean isNormal =
2618                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2619                        == PermissionInfo.PROTECTION_NORMAL);
2620        boolean isDangerous =
2621                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2622                        == PermissionInfo.PROTECTION_DANGEROUS);
2623        boolean isDevelopment =
2624                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2625
2626        if (!isNormal && !isDangerous && !isDevelopment) {
2627            throw new SecurityException("Permission " + bp.name
2628                    + " is not a changeable permission type");
2629        }
2630
2631        if (isNormal || isDangerous) {
2632            if (pkg.requestedPermissionsRequired.get(index)) {
2633                throw new SecurityException("Can't change " + bp.name
2634                        + ". It is required by the application");
2635            }
2636        }
2637    }
2638
2639    @Override
2640    public void grantPermission(String packageName, String permissionName) {
2641        mContext.enforceCallingOrSelfPermission(
2642                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2643        synchronized (mPackages) {
2644            final PackageParser.Package pkg = mPackages.get(packageName);
2645            if (pkg == null) {
2646                throw new IllegalArgumentException("Unknown package: " + packageName);
2647            }
2648            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2649            if (bp == null) {
2650                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2651            }
2652
2653            checkGrantRevokePermissions(pkg, bp);
2654
2655            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2656            if (ps == null) {
2657                return;
2658            }
2659            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2660            if (gp.grantedPermissions.add(permissionName)) {
2661                if (ps.haveGids) {
2662                    gp.gids = appendInts(gp.gids, bp.gids);
2663                }
2664                mSettings.writeLPr();
2665            }
2666        }
2667    }
2668
2669    @Override
2670    public void revokePermission(String packageName, String permissionName) {
2671        int changedAppId = -1;
2672
2673        synchronized (mPackages) {
2674            final PackageParser.Package pkg = mPackages.get(packageName);
2675            if (pkg == null) {
2676                throw new IllegalArgumentException("Unknown package: " + packageName);
2677            }
2678            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2679                mContext.enforceCallingOrSelfPermission(
2680                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2681            }
2682            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2683            if (bp == null) {
2684                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2685            }
2686
2687            checkGrantRevokePermissions(pkg, bp);
2688
2689            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2690            if (ps == null) {
2691                return;
2692            }
2693            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2694            if (gp.grantedPermissions.remove(permissionName)) {
2695                gp.grantedPermissions.remove(permissionName);
2696                if (ps.haveGids) {
2697                    gp.gids = removeInts(gp.gids, bp.gids);
2698                }
2699                mSettings.writeLPr();
2700                changedAppId = ps.appId;
2701            }
2702        }
2703
2704        if (changedAppId >= 0) {
2705            // We changed the perm on someone, kill its processes.
2706            IActivityManager am = ActivityManagerNative.getDefault();
2707            if (am != null) {
2708                final int callingUserId = UserHandle.getCallingUserId();
2709                final long ident = Binder.clearCallingIdentity();
2710                try {
2711                    //XXX we should only revoke for the calling user's app permissions,
2712                    // but for now we impact all users.
2713                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2714                    //        "revoke " + permissionName);
2715                    int[] users = sUserManager.getUserIds();
2716                    for (int user : users) {
2717                        am.killUid(UserHandle.getUid(user, changedAppId),
2718                                "revoke " + permissionName);
2719                    }
2720                } catch (RemoteException e) {
2721                } finally {
2722                    Binder.restoreCallingIdentity(ident);
2723                }
2724            }
2725        }
2726    }
2727
2728    @Override
2729    public boolean isProtectedBroadcast(String actionName) {
2730        synchronized (mPackages) {
2731            return mProtectedBroadcasts.contains(actionName);
2732        }
2733    }
2734
2735    @Override
2736    public int checkSignatures(String pkg1, String pkg2) {
2737        synchronized (mPackages) {
2738            final PackageParser.Package p1 = mPackages.get(pkg1);
2739            final PackageParser.Package p2 = mPackages.get(pkg2);
2740            if (p1 == null || p1.mExtras == null
2741                    || p2 == null || p2.mExtras == null) {
2742                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2743            }
2744            return compareSignatures(p1.mSignatures, p2.mSignatures);
2745        }
2746    }
2747
2748    @Override
2749    public int checkUidSignatures(int uid1, int uid2) {
2750        // Map to base uids.
2751        uid1 = UserHandle.getAppId(uid1);
2752        uid2 = UserHandle.getAppId(uid2);
2753        // reader
2754        synchronized (mPackages) {
2755            Signature[] s1;
2756            Signature[] s2;
2757            Object obj = mSettings.getUserIdLPr(uid1);
2758            if (obj != null) {
2759                if (obj instanceof SharedUserSetting) {
2760                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2761                } else if (obj instanceof PackageSetting) {
2762                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2763                } else {
2764                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2765                }
2766            } else {
2767                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2768            }
2769            obj = mSettings.getUserIdLPr(uid2);
2770            if (obj != null) {
2771                if (obj instanceof SharedUserSetting) {
2772                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2773                } else if (obj instanceof PackageSetting) {
2774                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2775                } else {
2776                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2777                }
2778            } else {
2779                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2780            }
2781            return compareSignatures(s1, s2);
2782        }
2783    }
2784
2785    /**
2786     * Compares two sets of signatures. Returns:
2787     * <br />
2788     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2789     * <br />
2790     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2791     * <br />
2792     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2793     * <br />
2794     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2795     * <br />
2796     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2797     */
2798    static int compareSignatures(Signature[] s1, Signature[] s2) {
2799        if (s1 == null) {
2800            return s2 == null
2801                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2802                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2803        }
2804
2805        if (s2 == null) {
2806            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2807        }
2808
2809        if (s1.length != s2.length) {
2810            return PackageManager.SIGNATURE_NO_MATCH;
2811        }
2812
2813        // Since both signature sets are of size 1, we can compare without HashSets.
2814        if (s1.length == 1) {
2815            return s1[0].equals(s2[0]) ?
2816                    PackageManager.SIGNATURE_MATCH :
2817                    PackageManager.SIGNATURE_NO_MATCH;
2818        }
2819
2820        ArraySet<Signature> set1 = new ArraySet<Signature>();
2821        for (Signature sig : s1) {
2822            set1.add(sig);
2823        }
2824        ArraySet<Signature> set2 = new ArraySet<Signature>();
2825        for (Signature sig : s2) {
2826            set2.add(sig);
2827        }
2828        // Make sure s2 contains all signatures in s1.
2829        if (set1.equals(set2)) {
2830            return PackageManager.SIGNATURE_MATCH;
2831        }
2832        return PackageManager.SIGNATURE_NO_MATCH;
2833    }
2834
2835    /**
2836     * If the database version for this type of package (internal storage or
2837     * external storage) is less than the version where package signatures
2838     * were updated, return true.
2839     */
2840    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2841        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2842                DatabaseVersion.SIGNATURE_END_ENTITY))
2843                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2844                        DatabaseVersion.SIGNATURE_END_ENTITY));
2845    }
2846
2847    /**
2848     * Used for backward compatibility to make sure any packages with
2849     * certificate chains get upgraded to the new style. {@code existingSigs}
2850     * will be in the old format (since they were stored on disk from before the
2851     * system upgrade) and {@code scannedSigs} will be in the newer format.
2852     */
2853    private int compareSignaturesCompat(PackageSignatures existingSigs,
2854            PackageParser.Package scannedPkg) {
2855        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2856            return PackageManager.SIGNATURE_NO_MATCH;
2857        }
2858
2859        ArraySet<Signature> existingSet = new ArraySet<Signature>();
2860        for (Signature sig : existingSigs.mSignatures) {
2861            existingSet.add(sig);
2862        }
2863        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
2864        for (Signature sig : scannedPkg.mSignatures) {
2865            try {
2866                Signature[] chainSignatures = sig.getChainSignatures();
2867                for (Signature chainSig : chainSignatures) {
2868                    scannedCompatSet.add(chainSig);
2869                }
2870            } catch (CertificateEncodingException e) {
2871                scannedCompatSet.add(sig);
2872            }
2873        }
2874        /*
2875         * Make sure the expanded scanned set contains all signatures in the
2876         * existing one.
2877         */
2878        if (scannedCompatSet.equals(existingSet)) {
2879            // Migrate the old signatures to the new scheme.
2880            existingSigs.assignSignatures(scannedPkg.mSignatures);
2881            // The new KeySets will be re-added later in the scanning process.
2882            synchronized (mPackages) {
2883                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2884            }
2885            return PackageManager.SIGNATURE_MATCH;
2886        }
2887        return PackageManager.SIGNATURE_NO_MATCH;
2888    }
2889
2890    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2891        if (isExternal(scannedPkg)) {
2892            return mSettings.isExternalDatabaseVersionOlderThan(
2893                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
2894        } else {
2895            return mSettings.isInternalDatabaseVersionOlderThan(
2896                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
2897        }
2898    }
2899
2900    private int compareSignaturesRecover(PackageSignatures existingSigs,
2901            PackageParser.Package scannedPkg) {
2902        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
2903            return PackageManager.SIGNATURE_NO_MATCH;
2904        }
2905
2906        String msg = null;
2907        try {
2908            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
2909                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
2910                        + scannedPkg.packageName);
2911                return PackageManager.SIGNATURE_MATCH;
2912            }
2913        } catch (CertificateException e) {
2914            msg = e.getMessage();
2915        }
2916
2917        logCriticalInfo(Log.INFO,
2918                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
2919        return PackageManager.SIGNATURE_NO_MATCH;
2920    }
2921
2922    @Override
2923    public String[] getPackagesForUid(int uid) {
2924        uid = UserHandle.getAppId(uid);
2925        // reader
2926        synchronized (mPackages) {
2927            Object obj = mSettings.getUserIdLPr(uid);
2928            if (obj instanceof SharedUserSetting) {
2929                final SharedUserSetting sus = (SharedUserSetting) obj;
2930                final int N = sus.packages.size();
2931                final String[] res = new String[N];
2932                final Iterator<PackageSetting> it = sus.packages.iterator();
2933                int i = 0;
2934                while (it.hasNext()) {
2935                    res[i++] = it.next().name;
2936                }
2937                return res;
2938            } else if (obj instanceof PackageSetting) {
2939                final PackageSetting ps = (PackageSetting) obj;
2940                return new String[] { ps.name };
2941            }
2942        }
2943        return null;
2944    }
2945
2946    @Override
2947    public String getNameForUid(int uid) {
2948        // reader
2949        synchronized (mPackages) {
2950            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2951            if (obj instanceof SharedUserSetting) {
2952                final SharedUserSetting sus = (SharedUserSetting) obj;
2953                return sus.name + ":" + sus.userId;
2954            } else if (obj instanceof PackageSetting) {
2955                final PackageSetting ps = (PackageSetting) obj;
2956                return ps.name;
2957            }
2958        }
2959        return null;
2960    }
2961
2962    @Override
2963    public int getUidForSharedUser(String sharedUserName) {
2964        if(sharedUserName == null) {
2965            return -1;
2966        }
2967        // reader
2968        synchronized (mPackages) {
2969            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2970            if (suid == null) {
2971                return -1;
2972            }
2973            return suid.userId;
2974        }
2975    }
2976
2977    @Override
2978    public int getFlagsForUid(int uid) {
2979        synchronized (mPackages) {
2980            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2981            if (obj instanceof SharedUserSetting) {
2982                final SharedUserSetting sus = (SharedUserSetting) obj;
2983                return sus.pkgFlags;
2984            } else if (obj instanceof PackageSetting) {
2985                final PackageSetting ps = (PackageSetting) obj;
2986                return ps.pkgFlags;
2987            }
2988        }
2989        return 0;
2990    }
2991
2992    @Override
2993    public boolean isUidPrivileged(int uid) {
2994        uid = UserHandle.getAppId(uid);
2995        // reader
2996        synchronized (mPackages) {
2997            Object obj = mSettings.getUserIdLPr(uid);
2998            if (obj instanceof SharedUserSetting) {
2999                final SharedUserSetting sus = (SharedUserSetting) obj;
3000                final Iterator<PackageSetting> it = sus.packages.iterator();
3001                while (it.hasNext()) {
3002                    if (it.next().isPrivileged()) {
3003                        return true;
3004                    }
3005                }
3006            } else if (obj instanceof PackageSetting) {
3007                final PackageSetting ps = (PackageSetting) obj;
3008                return ps.isPrivileged();
3009            }
3010        }
3011        return false;
3012    }
3013
3014    @Override
3015    public String[] getAppOpPermissionPackages(String permissionName) {
3016        synchronized (mPackages) {
3017            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3018            if (pkgs == null) {
3019                return null;
3020            }
3021            return pkgs.toArray(new String[pkgs.size()]);
3022        }
3023    }
3024
3025    @Override
3026    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3027            int flags, int userId) {
3028        if (!sUserManager.exists(userId)) return null;
3029        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3030        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3031        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3032    }
3033
3034    @Override
3035    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3036            IntentFilter filter, int match, ComponentName activity) {
3037        final int userId = UserHandle.getCallingUserId();
3038        if (DEBUG_PREFERRED) {
3039            Log.v(TAG, "setLastChosenActivity intent=" + intent
3040                + " resolvedType=" + resolvedType
3041                + " flags=" + flags
3042                + " filter=" + filter
3043                + " match=" + match
3044                + " activity=" + activity);
3045            filter.dump(new PrintStreamPrinter(System.out), "    ");
3046        }
3047        intent.setComponent(null);
3048        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3049        // Find any earlier preferred or last chosen entries and nuke them
3050        findPreferredActivity(intent, resolvedType,
3051                flags, query, 0, false, true, false, userId);
3052        // Add the new activity as the last chosen for this filter
3053        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3054                "Setting last chosen");
3055    }
3056
3057    @Override
3058    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3059        final int userId = UserHandle.getCallingUserId();
3060        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3061        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3062        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3063                false, false, false, userId);
3064    }
3065
3066    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3067            int flags, List<ResolveInfo> query, int userId) {
3068        if (query != null) {
3069            final int N = query.size();
3070            if (N == 1) {
3071                return query.get(0);
3072            } else if (N > 1) {
3073                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3074                // If there is more than one activity with the same priority,
3075                // then let the user decide between them.
3076                ResolveInfo r0 = query.get(0);
3077                ResolveInfo r1 = query.get(1);
3078                if (DEBUG_INTENT_MATCHING || debug) {
3079                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3080                            + r1.activityInfo.name + "=" + r1.priority);
3081                }
3082                // If the first activity has a higher priority, or a different
3083                // default, then it is always desireable to pick it.
3084                if (r0.priority != r1.priority
3085                        || r0.preferredOrder != r1.preferredOrder
3086                        || r0.isDefault != r1.isDefault) {
3087                    return query.get(0);
3088                }
3089                // If we have saved a preference for a preferred activity for
3090                // this Intent, use that.
3091                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3092                        flags, query, r0.priority, true, false, debug, userId);
3093                if (ri != null) {
3094                    return ri;
3095                }
3096                if (userId != 0) {
3097                    ri = new ResolveInfo(mResolveInfo);
3098                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3099                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3100                            ri.activityInfo.applicationInfo);
3101                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3102                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3103                    return ri;
3104                }
3105                return mResolveInfo;
3106            }
3107        }
3108        return null;
3109    }
3110
3111    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3112            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3113        final int N = query.size();
3114        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3115                .get(userId);
3116        // Get the list of persistent preferred activities that handle the intent
3117        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3118        List<PersistentPreferredActivity> pprefs = ppir != null
3119                ? ppir.queryIntent(intent, resolvedType,
3120                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3121                : null;
3122        if (pprefs != null && pprefs.size() > 0) {
3123            final int M = pprefs.size();
3124            for (int i=0; i<M; i++) {
3125                final PersistentPreferredActivity ppa = pprefs.get(i);
3126                if (DEBUG_PREFERRED || debug) {
3127                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3128                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3129                            + "\n  component=" + ppa.mComponent);
3130                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3131                }
3132                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3133                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3134                if (DEBUG_PREFERRED || debug) {
3135                    Slog.v(TAG, "Found persistent preferred activity:");
3136                    if (ai != null) {
3137                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3138                    } else {
3139                        Slog.v(TAG, "  null");
3140                    }
3141                }
3142                if (ai == null) {
3143                    // This previously registered persistent preferred activity
3144                    // component is no longer known. Ignore it and do NOT remove it.
3145                    continue;
3146                }
3147                for (int j=0; j<N; j++) {
3148                    final ResolveInfo ri = query.get(j);
3149                    if (!ri.activityInfo.applicationInfo.packageName
3150                            .equals(ai.applicationInfo.packageName)) {
3151                        continue;
3152                    }
3153                    if (!ri.activityInfo.name.equals(ai.name)) {
3154                        continue;
3155                    }
3156                    //  Found a persistent preference that can handle the intent.
3157                    if (DEBUG_PREFERRED || debug) {
3158                        Slog.v(TAG, "Returning persistent preferred activity: " +
3159                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3160                    }
3161                    return ri;
3162                }
3163            }
3164        }
3165        return null;
3166    }
3167
3168    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3169            List<ResolveInfo> query, int priority, boolean always,
3170            boolean removeMatches, boolean debug, int userId) {
3171        if (!sUserManager.exists(userId)) return null;
3172        // writer
3173        synchronized (mPackages) {
3174            if (intent.getSelector() != null) {
3175                intent = intent.getSelector();
3176            }
3177            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3178
3179            // Try to find a matching persistent preferred activity.
3180            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3181                    debug, userId);
3182
3183            // If a persistent preferred activity matched, use it.
3184            if (pri != null) {
3185                return pri;
3186            }
3187
3188            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3189            // Get the list of preferred activities that handle the intent
3190            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3191            List<PreferredActivity> prefs = pir != null
3192                    ? pir.queryIntent(intent, resolvedType,
3193                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3194                    : null;
3195            if (prefs != null && prefs.size() > 0) {
3196                boolean changed = false;
3197                try {
3198                    // First figure out how good the original match set is.
3199                    // We will only allow preferred activities that came
3200                    // from the same match quality.
3201                    int match = 0;
3202
3203                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3204
3205                    final int N = query.size();
3206                    for (int j=0; j<N; j++) {
3207                        final ResolveInfo ri = query.get(j);
3208                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3209                                + ": 0x" + Integer.toHexString(match));
3210                        if (ri.match > match) {
3211                            match = ri.match;
3212                        }
3213                    }
3214
3215                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3216                            + Integer.toHexString(match));
3217
3218                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3219                    final int M = prefs.size();
3220                    for (int i=0; i<M; i++) {
3221                        final PreferredActivity pa = prefs.get(i);
3222                        if (DEBUG_PREFERRED || debug) {
3223                            Slog.v(TAG, "Checking PreferredActivity ds="
3224                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3225                                    + "\n  component=" + pa.mPref.mComponent);
3226                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3227                        }
3228                        if (pa.mPref.mMatch != match) {
3229                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3230                                    + Integer.toHexString(pa.mPref.mMatch));
3231                            continue;
3232                        }
3233                        // If it's not an "always" type preferred activity and that's what we're
3234                        // looking for, skip it.
3235                        if (always && !pa.mPref.mAlways) {
3236                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3237                            continue;
3238                        }
3239                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3240                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3241                        if (DEBUG_PREFERRED || debug) {
3242                            Slog.v(TAG, "Found preferred activity:");
3243                            if (ai != null) {
3244                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3245                            } else {
3246                                Slog.v(TAG, "  null");
3247                            }
3248                        }
3249                        if (ai == null) {
3250                            // This previously registered preferred activity
3251                            // component is no longer known.  Most likely an update
3252                            // to the app was installed and in the new version this
3253                            // component no longer exists.  Clean it up by removing
3254                            // it from the preferred activities list, and skip it.
3255                            Slog.w(TAG, "Removing dangling preferred activity: "
3256                                    + pa.mPref.mComponent);
3257                            pir.removeFilter(pa);
3258                            changed = true;
3259                            continue;
3260                        }
3261                        for (int j=0; j<N; j++) {
3262                            final ResolveInfo ri = query.get(j);
3263                            if (!ri.activityInfo.applicationInfo.packageName
3264                                    .equals(ai.applicationInfo.packageName)) {
3265                                continue;
3266                            }
3267                            if (!ri.activityInfo.name.equals(ai.name)) {
3268                                continue;
3269                            }
3270
3271                            if (removeMatches) {
3272                                pir.removeFilter(pa);
3273                                changed = true;
3274                                if (DEBUG_PREFERRED) {
3275                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3276                                }
3277                                break;
3278                            }
3279
3280                            // Okay we found a previously set preferred or last chosen app.
3281                            // If the result set is different from when this
3282                            // was created, we need to clear it and re-ask the
3283                            // user their preference, if we're looking for an "always" type entry.
3284                            if (always && !pa.mPref.sameSet(query, priority)) {
3285                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3286                                        + intent + " type " + resolvedType);
3287                                if (DEBUG_PREFERRED) {
3288                                    Slog.v(TAG, "Removing preferred activity since set changed "
3289                                            + pa.mPref.mComponent);
3290                                }
3291                                pir.removeFilter(pa);
3292                                // Re-add the filter as a "last chosen" entry (!always)
3293                                PreferredActivity lastChosen = new PreferredActivity(
3294                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3295                                pir.addFilter(lastChosen);
3296                                changed = true;
3297                                return null;
3298                            }
3299
3300                            // Yay! Either the set matched or we're looking for the last chosen
3301                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3302                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3303                            return ri;
3304                        }
3305                    }
3306                } finally {
3307                    if (changed) {
3308                        if (DEBUG_PREFERRED) {
3309                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3310                        }
3311                        scheduleWritePackageRestrictionsLocked(userId);
3312                    }
3313                }
3314            }
3315        }
3316        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3317        return null;
3318    }
3319
3320    /*
3321     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3322     */
3323    @Override
3324    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3325            int targetUserId) {
3326        mContext.enforceCallingOrSelfPermission(
3327                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3328        List<CrossProfileIntentFilter> matches =
3329                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3330        if (matches != null) {
3331            int size = matches.size();
3332            for (int i = 0; i < size; i++) {
3333                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3334            }
3335        }
3336        return false;
3337    }
3338
3339    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3340            String resolvedType, int userId) {
3341        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3342        if (resolver != null) {
3343            return resolver.queryIntent(intent, resolvedType, false, userId);
3344        }
3345        return null;
3346    }
3347
3348    @Override
3349    public List<ResolveInfo> queryIntentActivities(Intent intent,
3350            String resolvedType, int flags, int userId) {
3351        if (!sUserManager.exists(userId)) return Collections.emptyList();
3352        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3353        ComponentName comp = intent.getComponent();
3354        if (comp == null) {
3355            if (intent.getSelector() != null) {
3356                intent = intent.getSelector();
3357                comp = intent.getComponent();
3358            }
3359        }
3360
3361        if (comp != null) {
3362            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3363            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3364            if (ai != null) {
3365                final ResolveInfo ri = new ResolveInfo();
3366                ri.activityInfo = ai;
3367                list.add(ri);
3368            }
3369            return list;
3370        }
3371
3372        // reader
3373        synchronized (mPackages) {
3374            final String pkgName = intent.getPackage();
3375            if (pkgName == null) {
3376                List<CrossProfileIntentFilter> matchingFilters =
3377                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3378                // Check for results that need to skip the current profile.
3379                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3380                        resolvedType, flags, userId);
3381                if (resolveInfo != null) {
3382                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3383                    result.add(resolveInfo);
3384                    return result;
3385                }
3386                // Check for cross profile results.
3387                resolveInfo = queryCrossProfileIntents(
3388                        matchingFilters, intent, resolvedType, flags, userId);
3389
3390                // Check for results in the current profile.
3391                List<ResolveInfo> result = mActivities.queryIntent(
3392                        intent, resolvedType, flags, userId);
3393                if (resolveInfo != null) {
3394                    result.add(resolveInfo);
3395                    Collections.sort(result, mResolvePrioritySorter);
3396                }
3397                return result;
3398            }
3399            final PackageParser.Package pkg = mPackages.get(pkgName);
3400            if (pkg != null) {
3401                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3402                        pkg.activities, userId);
3403            }
3404            return new ArrayList<ResolveInfo>();
3405        }
3406    }
3407
3408    private ResolveInfo querySkipCurrentProfileIntents(
3409            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3410            int flags, int sourceUserId) {
3411        if (matchingFilters != null) {
3412            int size = matchingFilters.size();
3413            for (int i = 0; i < size; i ++) {
3414                CrossProfileIntentFilter filter = matchingFilters.get(i);
3415                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3416                    // Checking if there are activities in the target user that can handle the
3417                    // intent.
3418                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3419                            flags, sourceUserId);
3420                    if (resolveInfo != null) {
3421                        return resolveInfo;
3422                    }
3423                }
3424            }
3425        }
3426        return null;
3427    }
3428
3429    // Return matching ResolveInfo if any for skip current profile intent filters.
3430    private ResolveInfo queryCrossProfileIntents(
3431            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3432            int flags, int sourceUserId) {
3433        if (matchingFilters != null) {
3434            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3435            // match the same intent. For performance reasons, it is better not to
3436            // run queryIntent twice for the same userId
3437            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3438            int size = matchingFilters.size();
3439            for (int i = 0; i < size; i++) {
3440                CrossProfileIntentFilter filter = matchingFilters.get(i);
3441                int targetUserId = filter.getTargetUserId();
3442                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3443                        && !alreadyTriedUserIds.get(targetUserId)) {
3444                    // Checking if there are activities in the target user that can handle the
3445                    // intent.
3446                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3447                            flags, sourceUserId);
3448                    if (resolveInfo != null) return resolveInfo;
3449                    alreadyTriedUserIds.put(targetUserId, true);
3450                }
3451            }
3452        }
3453        return null;
3454    }
3455
3456    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3457            String resolvedType, int flags, int sourceUserId) {
3458        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3459                resolvedType, flags, filter.getTargetUserId());
3460        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3461            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3462        }
3463        return null;
3464    }
3465
3466    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3467            int sourceUserId, int targetUserId) {
3468        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3469        String className;
3470        if (targetUserId == UserHandle.USER_OWNER) {
3471            className = FORWARD_INTENT_TO_USER_OWNER;
3472        } else {
3473            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3474        }
3475        ComponentName forwardingActivityComponentName = new ComponentName(
3476                mAndroidApplication.packageName, className);
3477        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3478                sourceUserId);
3479        if (targetUserId == UserHandle.USER_OWNER) {
3480            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3481            forwardingResolveInfo.noResourceId = true;
3482        }
3483        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3484        forwardingResolveInfo.priority = 0;
3485        forwardingResolveInfo.preferredOrder = 0;
3486        forwardingResolveInfo.match = 0;
3487        forwardingResolveInfo.isDefault = true;
3488        forwardingResolveInfo.filter = filter;
3489        forwardingResolveInfo.targetUserId = targetUserId;
3490        return forwardingResolveInfo;
3491    }
3492
3493    @Override
3494    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3495            Intent[] specifics, String[] specificTypes, Intent intent,
3496            String resolvedType, int flags, int userId) {
3497        if (!sUserManager.exists(userId)) return Collections.emptyList();
3498        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3499                false, "query intent activity options");
3500        final String resultsAction = intent.getAction();
3501
3502        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3503                | PackageManager.GET_RESOLVED_FILTER, userId);
3504
3505        if (DEBUG_INTENT_MATCHING) {
3506            Log.v(TAG, "Query " + intent + ": " + results);
3507        }
3508
3509        int specificsPos = 0;
3510        int N;
3511
3512        // todo: note that the algorithm used here is O(N^2).  This
3513        // isn't a problem in our current environment, but if we start running
3514        // into situations where we have more than 5 or 10 matches then this
3515        // should probably be changed to something smarter...
3516
3517        // First we go through and resolve each of the specific items
3518        // that were supplied, taking care of removing any corresponding
3519        // duplicate items in the generic resolve list.
3520        if (specifics != null) {
3521            for (int i=0; i<specifics.length; i++) {
3522                final Intent sintent = specifics[i];
3523                if (sintent == null) {
3524                    continue;
3525                }
3526
3527                if (DEBUG_INTENT_MATCHING) {
3528                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3529                }
3530
3531                String action = sintent.getAction();
3532                if (resultsAction != null && resultsAction.equals(action)) {
3533                    // If this action was explicitly requested, then don't
3534                    // remove things that have it.
3535                    action = null;
3536                }
3537
3538                ResolveInfo ri = null;
3539                ActivityInfo ai = null;
3540
3541                ComponentName comp = sintent.getComponent();
3542                if (comp == null) {
3543                    ri = resolveIntent(
3544                        sintent,
3545                        specificTypes != null ? specificTypes[i] : null,
3546                            flags, userId);
3547                    if (ri == null) {
3548                        continue;
3549                    }
3550                    if (ri == mResolveInfo) {
3551                        // ACK!  Must do something better with this.
3552                    }
3553                    ai = ri.activityInfo;
3554                    comp = new ComponentName(ai.applicationInfo.packageName,
3555                            ai.name);
3556                } else {
3557                    ai = getActivityInfo(comp, flags, userId);
3558                    if (ai == null) {
3559                        continue;
3560                    }
3561                }
3562
3563                // Look for any generic query activities that are duplicates
3564                // of this specific one, and remove them from the results.
3565                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3566                N = results.size();
3567                int j;
3568                for (j=specificsPos; j<N; j++) {
3569                    ResolveInfo sri = results.get(j);
3570                    if ((sri.activityInfo.name.equals(comp.getClassName())
3571                            && sri.activityInfo.applicationInfo.packageName.equals(
3572                                    comp.getPackageName()))
3573                        || (action != null && sri.filter.matchAction(action))) {
3574                        results.remove(j);
3575                        if (DEBUG_INTENT_MATCHING) Log.v(
3576                            TAG, "Removing duplicate item from " + j
3577                            + " due to specific " + specificsPos);
3578                        if (ri == null) {
3579                            ri = sri;
3580                        }
3581                        j--;
3582                        N--;
3583                    }
3584                }
3585
3586                // Add this specific item to its proper place.
3587                if (ri == null) {
3588                    ri = new ResolveInfo();
3589                    ri.activityInfo = ai;
3590                }
3591                results.add(specificsPos, ri);
3592                ri.specificIndex = i;
3593                specificsPos++;
3594            }
3595        }
3596
3597        // Now we go through the remaining generic results and remove any
3598        // duplicate actions that are found here.
3599        N = results.size();
3600        for (int i=specificsPos; i<N-1; i++) {
3601            final ResolveInfo rii = results.get(i);
3602            if (rii.filter == null) {
3603                continue;
3604            }
3605
3606            // Iterate over all of the actions of this result's intent
3607            // filter...  typically this should be just one.
3608            final Iterator<String> it = rii.filter.actionsIterator();
3609            if (it == null) {
3610                continue;
3611            }
3612            while (it.hasNext()) {
3613                final String action = it.next();
3614                if (resultsAction != null && resultsAction.equals(action)) {
3615                    // If this action was explicitly requested, then don't
3616                    // remove things that have it.
3617                    continue;
3618                }
3619                for (int j=i+1; j<N; j++) {
3620                    final ResolveInfo rij = results.get(j);
3621                    if (rij.filter != null && rij.filter.hasAction(action)) {
3622                        results.remove(j);
3623                        if (DEBUG_INTENT_MATCHING) Log.v(
3624                            TAG, "Removing duplicate item from " + j
3625                            + " due to action " + action + " at " + i);
3626                        j--;
3627                        N--;
3628                    }
3629                }
3630            }
3631
3632            // If the caller didn't request filter information, drop it now
3633            // so we don't have to marshall/unmarshall it.
3634            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3635                rii.filter = null;
3636            }
3637        }
3638
3639        // Filter out the caller activity if so requested.
3640        if (caller != null) {
3641            N = results.size();
3642            for (int i=0; i<N; i++) {
3643                ActivityInfo ainfo = results.get(i).activityInfo;
3644                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3645                        && caller.getClassName().equals(ainfo.name)) {
3646                    results.remove(i);
3647                    break;
3648                }
3649            }
3650        }
3651
3652        // If the caller didn't request filter information,
3653        // drop them now so we don't have to
3654        // marshall/unmarshall it.
3655        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3656            N = results.size();
3657            for (int i=0; i<N; i++) {
3658                results.get(i).filter = null;
3659            }
3660        }
3661
3662        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3663        return results;
3664    }
3665
3666    @Override
3667    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3668            int userId) {
3669        if (!sUserManager.exists(userId)) return Collections.emptyList();
3670        ComponentName comp = intent.getComponent();
3671        if (comp == null) {
3672            if (intent.getSelector() != null) {
3673                intent = intent.getSelector();
3674                comp = intent.getComponent();
3675            }
3676        }
3677        if (comp != null) {
3678            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3679            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3680            if (ai != null) {
3681                ResolveInfo ri = new ResolveInfo();
3682                ri.activityInfo = ai;
3683                list.add(ri);
3684            }
3685            return list;
3686        }
3687
3688        // reader
3689        synchronized (mPackages) {
3690            String pkgName = intent.getPackage();
3691            if (pkgName == null) {
3692                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3693            }
3694            final PackageParser.Package pkg = mPackages.get(pkgName);
3695            if (pkg != null) {
3696                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3697                        userId);
3698            }
3699            return null;
3700        }
3701    }
3702
3703    @Override
3704    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3705        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3706        if (!sUserManager.exists(userId)) return null;
3707        if (query != null) {
3708            if (query.size() >= 1) {
3709                // If there is more than one service with the same priority,
3710                // just arbitrarily pick the first one.
3711                return query.get(0);
3712            }
3713        }
3714        return null;
3715    }
3716
3717    @Override
3718    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3719            int userId) {
3720        if (!sUserManager.exists(userId)) return Collections.emptyList();
3721        ComponentName comp = intent.getComponent();
3722        if (comp == null) {
3723            if (intent.getSelector() != null) {
3724                intent = intent.getSelector();
3725                comp = intent.getComponent();
3726            }
3727        }
3728        if (comp != null) {
3729            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3730            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3731            if (si != null) {
3732                final ResolveInfo ri = new ResolveInfo();
3733                ri.serviceInfo = si;
3734                list.add(ri);
3735            }
3736            return list;
3737        }
3738
3739        // reader
3740        synchronized (mPackages) {
3741            String pkgName = intent.getPackage();
3742            if (pkgName == null) {
3743                return mServices.queryIntent(intent, resolvedType, flags, userId);
3744            }
3745            final PackageParser.Package pkg = mPackages.get(pkgName);
3746            if (pkg != null) {
3747                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3748                        userId);
3749            }
3750            return null;
3751        }
3752    }
3753
3754    @Override
3755    public List<ResolveInfo> queryIntentContentProviders(
3756            Intent intent, String resolvedType, int flags, int userId) {
3757        if (!sUserManager.exists(userId)) return Collections.emptyList();
3758        ComponentName comp = intent.getComponent();
3759        if (comp == null) {
3760            if (intent.getSelector() != null) {
3761                intent = intent.getSelector();
3762                comp = intent.getComponent();
3763            }
3764        }
3765        if (comp != null) {
3766            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3767            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3768            if (pi != null) {
3769                final ResolveInfo ri = new ResolveInfo();
3770                ri.providerInfo = pi;
3771                list.add(ri);
3772            }
3773            return list;
3774        }
3775
3776        // reader
3777        synchronized (mPackages) {
3778            String pkgName = intent.getPackage();
3779            if (pkgName == null) {
3780                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3781            }
3782            final PackageParser.Package pkg = mPackages.get(pkgName);
3783            if (pkg != null) {
3784                return mProviders.queryIntentForPackage(
3785                        intent, resolvedType, flags, pkg.providers, userId);
3786            }
3787            return null;
3788        }
3789    }
3790
3791    @Override
3792    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3793        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3794
3795        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3796
3797        // writer
3798        synchronized (mPackages) {
3799            ArrayList<PackageInfo> list;
3800            if (listUninstalled) {
3801                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3802                for (PackageSetting ps : mSettings.mPackages.values()) {
3803                    PackageInfo pi;
3804                    if (ps.pkg != null) {
3805                        pi = generatePackageInfo(ps.pkg, flags, userId);
3806                    } else {
3807                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3808                    }
3809                    if (pi != null) {
3810                        list.add(pi);
3811                    }
3812                }
3813            } else {
3814                list = new ArrayList<PackageInfo>(mPackages.size());
3815                for (PackageParser.Package p : mPackages.values()) {
3816                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3817                    if (pi != null) {
3818                        list.add(pi);
3819                    }
3820                }
3821            }
3822
3823            return new ParceledListSlice<PackageInfo>(list);
3824        }
3825    }
3826
3827    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3828            String[] permissions, boolean[] tmp, int flags, int userId) {
3829        int numMatch = 0;
3830        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3831        for (int i=0; i<permissions.length; i++) {
3832            if (gp.grantedPermissions.contains(permissions[i])) {
3833                tmp[i] = true;
3834                numMatch++;
3835            } else {
3836                tmp[i] = false;
3837            }
3838        }
3839        if (numMatch == 0) {
3840            return;
3841        }
3842        PackageInfo pi;
3843        if (ps.pkg != null) {
3844            pi = generatePackageInfo(ps.pkg, flags, userId);
3845        } else {
3846            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3847        }
3848        // The above might return null in cases of uninstalled apps or install-state
3849        // skew across users/profiles.
3850        if (pi != null) {
3851            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3852                if (numMatch == permissions.length) {
3853                    pi.requestedPermissions = permissions;
3854                } else {
3855                    pi.requestedPermissions = new String[numMatch];
3856                    numMatch = 0;
3857                    for (int i=0; i<permissions.length; i++) {
3858                        if (tmp[i]) {
3859                            pi.requestedPermissions[numMatch] = permissions[i];
3860                            numMatch++;
3861                        }
3862                    }
3863                }
3864            }
3865            list.add(pi);
3866        }
3867    }
3868
3869    @Override
3870    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3871            String[] permissions, int flags, int userId) {
3872        if (!sUserManager.exists(userId)) return null;
3873        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3874
3875        // writer
3876        synchronized (mPackages) {
3877            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3878            boolean[] tmpBools = new boolean[permissions.length];
3879            if (listUninstalled) {
3880                for (PackageSetting ps : mSettings.mPackages.values()) {
3881                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3882                }
3883            } else {
3884                for (PackageParser.Package pkg : mPackages.values()) {
3885                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3886                    if (ps != null) {
3887                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3888                                userId);
3889                    }
3890                }
3891            }
3892
3893            return new ParceledListSlice<PackageInfo>(list);
3894        }
3895    }
3896
3897    @Override
3898    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3899        if (!sUserManager.exists(userId)) return null;
3900        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3901
3902        // writer
3903        synchronized (mPackages) {
3904            ArrayList<ApplicationInfo> list;
3905            if (listUninstalled) {
3906                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3907                for (PackageSetting ps : mSettings.mPackages.values()) {
3908                    ApplicationInfo ai;
3909                    if (ps.pkg != null) {
3910                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3911                                ps.readUserState(userId), userId);
3912                    } else {
3913                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3914                    }
3915                    if (ai != null) {
3916                        list.add(ai);
3917                    }
3918                }
3919            } else {
3920                list = new ArrayList<ApplicationInfo>(mPackages.size());
3921                for (PackageParser.Package p : mPackages.values()) {
3922                    if (p.mExtras != null) {
3923                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3924                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3925                        if (ai != null) {
3926                            list.add(ai);
3927                        }
3928                    }
3929                }
3930            }
3931
3932            return new ParceledListSlice<ApplicationInfo>(list);
3933        }
3934    }
3935
3936    public List<ApplicationInfo> getPersistentApplications(int flags) {
3937        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3938
3939        // reader
3940        synchronized (mPackages) {
3941            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3942            final int userId = UserHandle.getCallingUserId();
3943            while (i.hasNext()) {
3944                final PackageParser.Package p = i.next();
3945                if (p.applicationInfo != null
3946                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3947                        && (!mSafeMode || isSystemApp(p))) {
3948                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3949                    if (ps != null) {
3950                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3951                                ps.readUserState(userId), userId);
3952                        if (ai != null) {
3953                            finalList.add(ai);
3954                        }
3955                    }
3956                }
3957            }
3958        }
3959
3960        return finalList;
3961    }
3962
3963    @Override
3964    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3965        if (!sUserManager.exists(userId)) return null;
3966        // reader
3967        synchronized (mPackages) {
3968            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3969            PackageSetting ps = provider != null
3970                    ? mSettings.mPackages.get(provider.owner.packageName)
3971                    : null;
3972            return ps != null
3973                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3974                    && (!mSafeMode || (provider.info.applicationInfo.flags
3975                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3976                    ? PackageParser.generateProviderInfo(provider, flags,
3977                            ps.readUserState(userId), userId)
3978                    : null;
3979        }
3980    }
3981
3982    /**
3983     * @deprecated
3984     */
3985    @Deprecated
3986    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3987        // reader
3988        synchronized (mPackages) {
3989            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3990                    .entrySet().iterator();
3991            final int userId = UserHandle.getCallingUserId();
3992            while (i.hasNext()) {
3993                Map.Entry<String, PackageParser.Provider> entry = i.next();
3994                PackageParser.Provider p = entry.getValue();
3995                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3996
3997                if (ps != null && p.syncable
3998                        && (!mSafeMode || (p.info.applicationInfo.flags
3999                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4000                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4001                            ps.readUserState(userId), userId);
4002                    if (info != null) {
4003                        outNames.add(entry.getKey());
4004                        outInfo.add(info);
4005                    }
4006                }
4007            }
4008        }
4009    }
4010
4011    @Override
4012    public List<ProviderInfo> queryContentProviders(String processName,
4013            int uid, int flags) {
4014        ArrayList<ProviderInfo> finalList = null;
4015        // reader
4016        synchronized (mPackages) {
4017            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4018            final int userId = processName != null ?
4019                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4020            while (i.hasNext()) {
4021                final PackageParser.Provider p = i.next();
4022                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4023                if (ps != null && p.info.authority != null
4024                        && (processName == null
4025                                || (p.info.processName.equals(processName)
4026                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4027                        && mSettings.isEnabledLPr(p.info, flags, userId)
4028                        && (!mSafeMode
4029                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4030                    if (finalList == null) {
4031                        finalList = new ArrayList<ProviderInfo>(3);
4032                    }
4033                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4034                            ps.readUserState(userId), userId);
4035                    if (info != null) {
4036                        finalList.add(info);
4037                    }
4038                }
4039            }
4040        }
4041
4042        if (finalList != null) {
4043            Collections.sort(finalList, mProviderInitOrderSorter);
4044        }
4045
4046        return finalList;
4047    }
4048
4049    @Override
4050    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4051            int flags) {
4052        // reader
4053        synchronized (mPackages) {
4054            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4055            return PackageParser.generateInstrumentationInfo(i, flags);
4056        }
4057    }
4058
4059    @Override
4060    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4061            int flags) {
4062        ArrayList<InstrumentationInfo> finalList =
4063            new ArrayList<InstrumentationInfo>();
4064
4065        // reader
4066        synchronized (mPackages) {
4067            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4068            while (i.hasNext()) {
4069                final PackageParser.Instrumentation p = i.next();
4070                if (targetPackage == null
4071                        || targetPackage.equals(p.info.targetPackage)) {
4072                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4073                            flags);
4074                    if (ii != null) {
4075                        finalList.add(ii);
4076                    }
4077                }
4078            }
4079        }
4080
4081        return finalList;
4082    }
4083
4084    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4085        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4086        if (overlays == null) {
4087            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4088            return;
4089        }
4090        for (PackageParser.Package opkg : overlays.values()) {
4091            // Not much to do if idmap fails: we already logged the error
4092            // and we certainly don't want to abort installation of pkg simply
4093            // because an overlay didn't fit properly. For these reasons,
4094            // ignore the return value of createIdmapForPackagePairLI.
4095            createIdmapForPackagePairLI(pkg, opkg);
4096        }
4097    }
4098
4099    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4100            PackageParser.Package opkg) {
4101        if (!opkg.mTrustedOverlay) {
4102            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4103                    opkg.baseCodePath + ": overlay not trusted");
4104            return false;
4105        }
4106        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4107        if (overlaySet == null) {
4108            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4109                    opkg.baseCodePath + " but target package has no known overlays");
4110            return false;
4111        }
4112        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4113        // TODO: generate idmap for split APKs
4114        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4115            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4116                    + opkg.baseCodePath);
4117            return false;
4118        }
4119        PackageParser.Package[] overlayArray =
4120            overlaySet.values().toArray(new PackageParser.Package[0]);
4121        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4122            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4123                return p1.mOverlayPriority - p2.mOverlayPriority;
4124            }
4125        };
4126        Arrays.sort(overlayArray, cmp);
4127
4128        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4129        int i = 0;
4130        for (PackageParser.Package p : overlayArray) {
4131            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4132        }
4133        return true;
4134    }
4135
4136    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4137        final File[] files = dir.listFiles();
4138        if (ArrayUtils.isEmpty(files)) {
4139            Log.d(TAG, "No files in app dir " + dir);
4140            return;
4141        }
4142
4143        if (DEBUG_PACKAGE_SCANNING) {
4144            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4145                    + " flags=0x" + Integer.toHexString(parseFlags));
4146        }
4147
4148        for (File file : files) {
4149            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4150                    && !PackageInstallerService.isStageName(file.getName());
4151            if (!isPackage) {
4152                // Ignore entries which are not packages
4153                continue;
4154            }
4155            try {
4156                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4157                        scanFlags, currentTime, null);
4158            } catch (PackageManagerException e) {
4159                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4160
4161                // Delete invalid userdata apps
4162                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4163                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4164                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4165                    if (file.isDirectory()) {
4166                        FileUtils.deleteContents(file);
4167                    }
4168                    file.delete();
4169                }
4170            }
4171        }
4172    }
4173
4174    private static File getSettingsProblemFile() {
4175        File dataDir = Environment.getDataDirectory();
4176        File systemDir = new File(dataDir, "system");
4177        File fname = new File(systemDir, "uiderrors.txt");
4178        return fname;
4179    }
4180
4181    static void reportSettingsProblem(int priority, String msg) {
4182        logCriticalInfo(priority, msg);
4183    }
4184
4185    static void logCriticalInfo(int priority, String msg) {
4186        Slog.println(priority, TAG, msg);
4187        EventLogTags.writePmCriticalInfo(msg);
4188        try {
4189            File fname = getSettingsProblemFile();
4190            FileOutputStream out = new FileOutputStream(fname, true);
4191            PrintWriter pw = new FastPrintWriter(out);
4192            SimpleDateFormat formatter = new SimpleDateFormat();
4193            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4194            pw.println(dateString + ": " + msg);
4195            pw.close();
4196            FileUtils.setPermissions(
4197                    fname.toString(),
4198                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4199                    -1, -1);
4200        } catch (java.io.IOException e) {
4201        }
4202    }
4203
4204    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4205            PackageParser.Package pkg, File srcFile, int parseFlags)
4206            throws PackageManagerException {
4207        if (ps != null
4208                && ps.codePath.equals(srcFile)
4209                && ps.timeStamp == srcFile.lastModified()
4210                && !isCompatSignatureUpdateNeeded(pkg)
4211                && !isRecoverSignatureUpdateNeeded(pkg)) {
4212            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4213            if (ps.signatures.mSignatures != null
4214                    && ps.signatures.mSignatures.length != 0
4215                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4216                // Optimization: reuse the existing cached certificates
4217                // if the package appears to be unchanged.
4218                pkg.mSignatures = ps.signatures.mSignatures;
4219                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4220                synchronized (mPackages) {
4221                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4222                }
4223                return;
4224            }
4225
4226            Slog.w(TAG, "PackageSetting for " + ps.name
4227                    + " is missing signatures.  Collecting certs again to recover them.");
4228        } else {
4229            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4230        }
4231
4232        try {
4233            pp.collectCertificates(pkg, parseFlags);
4234            pp.collectManifestDigest(pkg);
4235        } catch (PackageParserException e) {
4236            throw PackageManagerException.from(e);
4237        }
4238    }
4239
4240    /*
4241     *  Scan a package and return the newly parsed package.
4242     *  Returns null in case of errors and the error code is stored in mLastScanError
4243     */
4244    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4245            long currentTime, UserHandle user) throws PackageManagerException {
4246        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4247        parseFlags |= mDefParseFlags;
4248        PackageParser pp = new PackageParser();
4249        pp.setSeparateProcesses(mSeparateProcesses);
4250        pp.setOnlyCoreApps(mOnlyCore);
4251        pp.setDisplayMetrics(mMetrics);
4252
4253        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4254            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4255        }
4256
4257        final PackageParser.Package pkg;
4258        try {
4259            pkg = pp.parsePackage(scanFile, parseFlags);
4260        } catch (PackageParserException e) {
4261            throw PackageManagerException.from(e);
4262        }
4263
4264        PackageSetting ps = null;
4265        PackageSetting updatedPkg;
4266        // reader
4267        synchronized (mPackages) {
4268            // Look to see if we already know about this package.
4269            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4270            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4271                // This package has been renamed to its original name.  Let's
4272                // use that.
4273                ps = mSettings.peekPackageLPr(oldName);
4274            }
4275            // If there was no original package, see one for the real package name.
4276            if (ps == null) {
4277                ps = mSettings.peekPackageLPr(pkg.packageName);
4278            }
4279            // Check to see if this package could be hiding/updating a system
4280            // package.  Must look for it either under the original or real
4281            // package name depending on our state.
4282            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4283            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4284        }
4285        boolean updatedPkgBetter = false;
4286        // First check if this is a system package that may involve an update
4287        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4288            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
4289            // it needs to drop FLAG_PRIVILEGED.
4290            if (locationIsPrivileged(scanFile)) {
4291                updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4292            } else {
4293                updatedPkg.pkgFlags &= ~ApplicationInfo.FLAG_PRIVILEGED;
4294            }
4295
4296            if (ps != null && !ps.codePath.equals(scanFile)) {
4297                // The path has changed from what was last scanned...  check the
4298                // version of the new path against what we have stored to determine
4299                // what to do.
4300                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4301                if (pkg.mVersionCode <= ps.versionCode) {
4302                    // The system package has been updated and the code path does not match
4303                    // Ignore entry. Skip it.
4304                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
4305                            + " ignored: updated version " + ps.versionCode
4306                            + " better than this " + pkg.mVersionCode);
4307                    if (!updatedPkg.codePath.equals(scanFile)) {
4308                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4309                                + ps.name + " changing from " + updatedPkg.codePathString
4310                                + " to " + scanFile);
4311                        updatedPkg.codePath = scanFile;
4312                        updatedPkg.codePathString = scanFile.toString();
4313                        updatedPkg.resourcePath = scanFile;
4314                        updatedPkg.resourcePathString = scanFile.toString();
4315                    }
4316                    updatedPkg.pkg = pkg;
4317                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4318                } else {
4319                    // The current app on the system partition is better than
4320                    // what we have updated to on the data partition; switch
4321                    // back to the system partition version.
4322                    // At this point, its safely assumed that package installation for
4323                    // apps in system partition will go through. If not there won't be a working
4324                    // version of the app
4325                    // writer
4326                    synchronized (mPackages) {
4327                        // Just remove the loaded entries from package lists.
4328                        mPackages.remove(ps.name);
4329                    }
4330
4331                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4332                            + " reverting from " + ps.codePathString
4333                            + ": new version " + pkg.mVersionCode
4334                            + " better than installed " + ps.versionCode);
4335
4336                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4337                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4338                            getAppDexInstructionSets(ps));
4339                    synchronized (mInstallLock) {
4340                        args.cleanUpResourcesLI();
4341                    }
4342                    synchronized (mPackages) {
4343                        mSettings.enableSystemPackageLPw(ps.name);
4344                    }
4345                    updatedPkgBetter = true;
4346                }
4347            }
4348        }
4349
4350        if (updatedPkg != null) {
4351            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4352            // initially
4353            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4354
4355            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4356            // flag set initially
4357            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4358                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4359            }
4360        }
4361
4362        // Verify certificates against what was last scanned
4363        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4364
4365        /*
4366         * A new system app appeared, but we already had a non-system one of the
4367         * same name installed earlier.
4368         */
4369        boolean shouldHideSystemApp = false;
4370        if (updatedPkg == null && ps != null
4371                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4372            /*
4373             * Check to make sure the signatures match first. If they don't,
4374             * wipe the installed application and its data.
4375             */
4376            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4377                    != PackageManager.SIGNATURE_MATCH) {
4378                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
4379                        + " signatures don't match existing userdata copy; removing");
4380                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4381                ps = null;
4382            } else {
4383                /*
4384                 * If the newly-added system app is an older version than the
4385                 * already installed version, hide it. It will be scanned later
4386                 * and re-added like an update.
4387                 */
4388                if (pkg.mVersionCode <= ps.versionCode) {
4389                    shouldHideSystemApp = true;
4390                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
4391                            + " but new version " + pkg.mVersionCode + " better than installed "
4392                            + ps.versionCode + "; hiding system");
4393                } else {
4394                    /*
4395                     * The newly found system app is a newer version that the
4396                     * one previously installed. Simply remove the
4397                     * already-installed application and replace it with our own
4398                     * while keeping the application data.
4399                     */
4400                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4401                            + " reverting from " + ps.codePathString + ": new version "
4402                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
4403                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4404                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4405                            getAppDexInstructionSets(ps));
4406                    synchronized (mInstallLock) {
4407                        args.cleanUpResourcesLI();
4408                    }
4409                }
4410            }
4411        }
4412
4413        // The apk is forward locked (not public) if its code and resources
4414        // are kept in different files. (except for app in either system or
4415        // vendor path).
4416        // TODO grab this value from PackageSettings
4417        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4418            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4419                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4420            }
4421        }
4422
4423        // TODO: extend to support forward-locked splits
4424        String resourcePath = null;
4425        String baseResourcePath = null;
4426        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4427            if (ps != null && ps.resourcePathString != null) {
4428                resourcePath = ps.resourcePathString;
4429                baseResourcePath = ps.resourcePathString;
4430            } else {
4431                // Should not happen at all. Just log an error.
4432                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4433            }
4434        } else {
4435            resourcePath = pkg.codePath;
4436            baseResourcePath = pkg.baseCodePath;
4437        }
4438
4439        // Set application objects path explicitly.
4440        pkg.applicationInfo.setCodePath(pkg.codePath);
4441        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4442        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4443        pkg.applicationInfo.setResourcePath(resourcePath);
4444        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4445        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4446
4447        // Note that we invoke the following method only if we are about to unpack an application
4448        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4449                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4450
4451        /*
4452         * If the system app should be overridden by a previously installed
4453         * data, hide the system app now and let the /data/app scan pick it up
4454         * again.
4455         */
4456        if (shouldHideSystemApp) {
4457            synchronized (mPackages) {
4458                /*
4459                 * We have to grant systems permissions before we hide, because
4460                 * grantPermissions will assume the package update is trying to
4461                 * expand its permissions.
4462                 */
4463                grantPermissionsLPw(pkg, true, pkg.packageName);
4464                mSettings.disableSystemPackageLPw(pkg.packageName);
4465            }
4466        }
4467
4468        return scannedPkg;
4469    }
4470
4471    private static String fixProcessName(String defProcessName,
4472            String processName, int uid) {
4473        if (processName == null) {
4474            return defProcessName;
4475        }
4476        return processName;
4477    }
4478
4479    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4480            throws PackageManagerException {
4481        if (pkgSetting.signatures.mSignatures != null) {
4482            // Already existing package. Make sure signatures match
4483            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4484                    == PackageManager.SIGNATURE_MATCH;
4485            if (!match) {
4486                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4487                        == PackageManager.SIGNATURE_MATCH;
4488            }
4489            if (!match) {
4490                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
4491                        == PackageManager.SIGNATURE_MATCH;
4492            }
4493            if (!match) {
4494                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4495                        + pkg.packageName + " signatures do not match the "
4496                        + "previously installed version; ignoring!");
4497            }
4498        }
4499
4500        // Check for shared user signatures
4501        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4502            // Already existing package. Make sure signatures match
4503            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4504                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4505            if (!match) {
4506                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4507                        == PackageManager.SIGNATURE_MATCH;
4508            }
4509            if (!match) {
4510                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
4511                        == PackageManager.SIGNATURE_MATCH;
4512            }
4513            if (!match) {
4514                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4515                        "Package " + pkg.packageName
4516                        + " has no signatures that match those in shared user "
4517                        + pkgSetting.sharedUser.name + "; ignoring!");
4518            }
4519        }
4520    }
4521
4522    /**
4523     * Enforces that only the system UID or root's UID can call a method exposed
4524     * via Binder.
4525     *
4526     * @param message used as message if SecurityException is thrown
4527     * @throws SecurityException if the caller is not system or root
4528     */
4529    private static final void enforceSystemOrRoot(String message) {
4530        final int uid = Binder.getCallingUid();
4531        if (uid != Process.SYSTEM_UID && uid != 0) {
4532            throw new SecurityException(message);
4533        }
4534    }
4535
4536    @Override
4537    public void performBootDexOpt() {
4538        enforceSystemOrRoot("Only the system can request dexopt be performed");
4539
4540        // Before everything else, see whether we need to fstrim.
4541        try {
4542            IMountService ms = PackageHelper.getMountService();
4543            if (ms != null) {
4544                final long interval = android.provider.Settings.Global.getLong(
4545                        mContext.getContentResolver(),
4546                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
4547                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
4548                if (interval > 0) {
4549                    final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
4550                    if (timeSinceLast > interval) {
4551                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
4552                                + "; running immediately");
4553                        if (!isFirstBoot()) {
4554                            try {
4555                                ActivityManagerNative.getDefault().showBootMessage(
4556                                        mContext.getResources().getString(
4557                                                R.string.android_upgrading_fstrim), true);
4558                            } catch (RemoteException e) {
4559                            }
4560                        }
4561                        ms.runMaintenance();
4562                    }
4563                }
4564            } else {
4565                Slog.e(TAG, "Mount service unavailable!");
4566            }
4567        } catch (RemoteException e) {
4568            // Can't happen; MountService is local
4569        }
4570
4571        final ArraySet<PackageParser.Package> pkgs;
4572        synchronized (mPackages) {
4573            pkgs = mDeferredDexOpt;
4574            mDeferredDexOpt = null;
4575        }
4576
4577        if (pkgs != null) {
4578            // Sort apps by importance for dexopt ordering. Important apps are given more priority
4579            // in case the device runs out of space.
4580            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
4581            // Give priority to core apps.
4582            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4583                PackageParser.Package pkg = it.next();
4584                if (pkg.coreApp) {
4585                    if (DEBUG_DEXOPT) {
4586                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
4587                    }
4588                    sortedPkgs.add(pkg);
4589                    it.remove();
4590                }
4591            }
4592            // Give priority to system apps that listen for pre boot complete.
4593            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
4594            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
4595            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4596                PackageParser.Package pkg = it.next();
4597                if (pkgNames.contains(pkg.packageName)) {
4598                    if (DEBUG_DEXOPT) {
4599                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
4600                    }
4601                    sortedPkgs.add(pkg);
4602                    it.remove();
4603                }
4604            }
4605            // Give priority to system apps.
4606            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4607                PackageParser.Package pkg = it.next();
4608                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4609                    if (DEBUG_DEXOPT) {
4610                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
4611                    }
4612                    sortedPkgs.add(pkg);
4613                    it.remove();
4614                }
4615            }
4616            // Give priority to updated system apps.
4617            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4618                PackageParser.Package pkg = it.next();
4619                if (isUpdatedSystemApp(pkg)) {
4620                    if (DEBUG_DEXOPT) {
4621                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
4622                    }
4623                    sortedPkgs.add(pkg);
4624                    it.remove();
4625                }
4626            }
4627            // Give priority to apps that listen for boot complete.
4628            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
4629            pkgNames = getPackageNamesForIntent(intent);
4630            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4631                PackageParser.Package pkg = it.next();
4632                if (pkgNames.contains(pkg.packageName)) {
4633                    if (DEBUG_DEXOPT) {
4634                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
4635                    }
4636                    sortedPkgs.add(pkg);
4637                    it.remove();
4638                }
4639            }
4640            // Filter out packages that aren't recently used.
4641            filterRecentlyUsedApps(pkgs);
4642            // Add all remaining apps.
4643            for (PackageParser.Package pkg : pkgs) {
4644                if (DEBUG_DEXOPT) {
4645                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
4646                }
4647                sortedPkgs.add(pkg);
4648            }
4649
4650            // If we want to be lazy, filter everything that wasn't recently used.
4651            if (mLazyDexOpt) {
4652                filterRecentlyUsedApps(sortedPkgs);
4653            }
4654
4655            int i = 0;
4656            int total = sortedPkgs.size();
4657            File dataDir = Environment.getDataDirectory();
4658            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
4659            if (lowThreshold == 0) {
4660                throw new IllegalStateException("Invalid low memory threshold");
4661            }
4662            for (PackageParser.Package pkg : sortedPkgs) {
4663                long usableSpace = dataDir.getUsableSpace();
4664                if (usableSpace < lowThreshold) {
4665                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
4666                    break;
4667                }
4668                performBootDexOpt(pkg, ++i, total);
4669            }
4670        }
4671    }
4672
4673    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
4674        // Filter out packages that aren't recently used.
4675        //
4676        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4677        // should do a full dexopt.
4678        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4679            int total = pkgs.size();
4680            int skipped = 0;
4681            long now = System.currentTimeMillis();
4682            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4683                PackageParser.Package pkg = i.next();
4684                long then = pkg.mLastPackageUsageTimeInMills;
4685                if (then + mDexOptLRUThresholdInMills < now) {
4686                    if (DEBUG_DEXOPT) {
4687                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4688                              ((then == 0) ? "never" : new Date(then)));
4689                    }
4690                    i.remove();
4691                    skipped++;
4692                }
4693            }
4694            if (DEBUG_DEXOPT) {
4695                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4696            }
4697        }
4698    }
4699
4700    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
4701        List<ResolveInfo> ris = null;
4702        try {
4703            ris = AppGlobals.getPackageManager().queryIntentReceivers(
4704                    intent, null, 0, UserHandle.USER_OWNER);
4705        } catch (RemoteException e) {
4706        }
4707        ArraySet<String> pkgNames = new ArraySet<String>();
4708        if (ris != null) {
4709            for (ResolveInfo ri : ris) {
4710                pkgNames.add(ri.activityInfo.packageName);
4711            }
4712        }
4713        return pkgNames;
4714    }
4715
4716    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
4717        if (DEBUG_DEXOPT) {
4718            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
4719        }
4720        if (!isFirstBoot()) {
4721            try {
4722                ActivityManagerNative.getDefault().showBootMessage(
4723                        mContext.getResources().getString(R.string.android_upgrading_apk,
4724                                curr, total), true);
4725            } catch (RemoteException e) {
4726            }
4727        }
4728        PackageParser.Package p = pkg;
4729        synchronized (mInstallLock) {
4730            performDexOptLI(p, null /* instruction sets */, false /* force dex */,
4731                            false /* defer */, true /* include dependencies */);
4732        }
4733    }
4734
4735    @Override
4736    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4737        return performDexOpt(packageName, instructionSet, false);
4738    }
4739
4740    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4741        if (info.primaryCpuAbi == null) {
4742            return getPreferredInstructionSet();
4743        }
4744
4745        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4746    }
4747
4748    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4749        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4750        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4751        if (!dexopt && !updateUsage) {
4752            // We aren't going to dexopt or update usage, so bail early.
4753            return false;
4754        }
4755        PackageParser.Package p;
4756        final String targetInstructionSet;
4757        synchronized (mPackages) {
4758            p = mPackages.get(packageName);
4759            if (p == null) {
4760                return false;
4761            }
4762            if (updateUsage) {
4763                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4764            }
4765            mPackageUsage.write(false);
4766            if (!dexopt) {
4767                // We aren't going to dexopt, so bail early.
4768                return false;
4769            }
4770
4771            targetInstructionSet = instructionSet != null ? instructionSet :
4772                    getPrimaryInstructionSet(p.applicationInfo);
4773            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4774                return false;
4775            }
4776        }
4777
4778        synchronized (mInstallLock) {
4779            final String[] instructionSets = new String[] { targetInstructionSet };
4780            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4781                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4782        }
4783    }
4784
4785    public ArraySet<String> getPackagesThatNeedDexOpt() {
4786        ArraySet<String> pkgs = null;
4787        synchronized (mPackages) {
4788            for (PackageParser.Package p : mPackages.values()) {
4789                if (DEBUG_DEXOPT) {
4790                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4791                }
4792                if (!p.mDexOptPerformed.isEmpty()) {
4793                    continue;
4794                }
4795                if (pkgs == null) {
4796                    pkgs = new ArraySet<String>();
4797                }
4798                pkgs.add(p.packageName);
4799            }
4800        }
4801        return pkgs;
4802    }
4803
4804    public void shutdown() {
4805        mPackageUsage.write(true);
4806    }
4807
4808    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4809             boolean forceDex, boolean defer, ArraySet<String> done) {
4810        for (int i=0; i<libs.size(); i++) {
4811            PackageParser.Package libPkg;
4812            String libName;
4813            synchronized (mPackages) {
4814                libName = libs.get(i);
4815                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4816                if (lib != null && lib.apk != null) {
4817                    libPkg = mPackages.get(lib.apk);
4818                } else {
4819                    libPkg = null;
4820                }
4821            }
4822            if (libPkg != null && !done.contains(libName)) {
4823                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4824            }
4825        }
4826    }
4827
4828    static final int DEX_OPT_SKIPPED = 0;
4829    static final int DEX_OPT_PERFORMED = 1;
4830    static final int DEX_OPT_DEFERRED = 2;
4831    static final int DEX_OPT_FAILED = -1;
4832
4833    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4834            boolean forceDex, boolean defer, ArraySet<String> done) {
4835        final String[] instructionSets = targetInstructionSets != null ?
4836                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4837
4838        if (done != null) {
4839            done.add(pkg.packageName);
4840            if (pkg.usesLibraries != null) {
4841                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4842            }
4843            if (pkg.usesOptionalLibraries != null) {
4844                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4845            }
4846        }
4847
4848        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4849            return DEX_OPT_SKIPPED;
4850        }
4851
4852        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4853
4854        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4855        boolean performedDexOpt = false;
4856        // There are three basic cases here:
4857        // 1.) we need to dexopt, either because we are forced or it is needed
4858        // 2.) we are defering a needed dexopt
4859        // 3.) we are skipping an unneeded dexopt
4860        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4861        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4862            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4863                continue;
4864            }
4865
4866            for (String path : paths) {
4867                try {
4868                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4869                    // patckage or the one we find does not match the image checksum (i.e. it was
4870                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4871                    // odex file and it matches the checksum of the image but not its base address,
4872                    // meaning we need to move it.
4873                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4874                            pkg.packageName, dexCodeInstructionSet, defer);
4875                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4876                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4877                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4878                                + " vmSafeMode=" + vmSafeMode);
4879                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4880                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4881                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4882
4883                        if (ret < 0) {
4884                            // Don't bother running dexopt again if we failed, it will probably
4885                            // just result in an error again. Also, don't bother dexopting for other
4886                            // paths & ISAs.
4887                            return DEX_OPT_FAILED;
4888                        }
4889
4890                        performedDexOpt = true;
4891                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4892                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4893                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4894                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4895                                pkg.packageName, dexCodeInstructionSet);
4896
4897                        if (ret < 0) {
4898                            // Don't bother running patchoat again if we failed, it will probably
4899                            // just result in an error again. Also, don't bother dexopting for other
4900                            // paths & ISAs.
4901                            return DEX_OPT_FAILED;
4902                        }
4903
4904                        performedDexOpt = true;
4905                    }
4906
4907                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4908                    // paths and instruction sets. We'll deal with them all together when we process
4909                    // our list of deferred dexopts.
4910                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4911                        if (mDeferredDexOpt == null) {
4912                            mDeferredDexOpt = new ArraySet<PackageParser.Package>();
4913                        }
4914                        mDeferredDexOpt.add(pkg);
4915                        return DEX_OPT_DEFERRED;
4916                    }
4917                } catch (FileNotFoundException e) {
4918                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4919                    return DEX_OPT_FAILED;
4920                } catch (IOException e) {
4921                    Slog.w(TAG, "IOException reading apk: " + path, e);
4922                    return DEX_OPT_FAILED;
4923                } catch (StaleDexCacheError e) {
4924                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4925                    return DEX_OPT_FAILED;
4926                } catch (Exception e) {
4927                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4928                    return DEX_OPT_FAILED;
4929                }
4930            }
4931
4932            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4933            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4934            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4935            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4936            // it.
4937            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4938        }
4939
4940        // If we've gotten here, we're sure that no error occurred and that we haven't
4941        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4942        // we've skipped all of them because they are up to date. In both cases this
4943        // package doesn't need dexopt any longer.
4944        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4945    }
4946
4947    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4948        if (info.primaryCpuAbi != null) {
4949            if (info.secondaryCpuAbi != null) {
4950                return new String[] {
4951                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4952                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4953            } else {
4954                return new String[] {
4955                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4956            }
4957        }
4958
4959        return new String[] { getPreferredInstructionSet() };
4960    }
4961
4962    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4963        if (ps.primaryCpuAbiString != null) {
4964            if (ps.secondaryCpuAbiString != null) {
4965                return new String[] {
4966                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4967                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4968            } else {
4969                return new String[] {
4970                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4971            }
4972        }
4973
4974        return new String[] { getPreferredInstructionSet() };
4975    }
4976
4977    private static String getPreferredInstructionSet() {
4978        if (sPreferredInstructionSet == null) {
4979            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4980        }
4981
4982        return sPreferredInstructionSet;
4983    }
4984
4985    private static List<String> getAllInstructionSets() {
4986        final String[] allAbis = Build.SUPPORTED_ABIS;
4987        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4988
4989        for (String abi : allAbis) {
4990            final String instructionSet = VMRuntime.getInstructionSet(abi);
4991            if (!allInstructionSets.contains(instructionSet)) {
4992                allInstructionSets.add(instructionSet);
4993            }
4994        }
4995
4996        return allInstructionSets;
4997    }
4998
4999    /**
5000     * Returns the instruction set that should be used to compile dex code. In the presence of
5001     * a native bridge this might be different than the one shared libraries use.
5002     */
5003    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
5004        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
5005        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
5006    }
5007
5008    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
5009        ArraySet<String> dexCodeInstructionSets = new ArraySet<String>(instructionSets.length);
5010        for (String instructionSet : instructionSets) {
5011            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
5012        }
5013        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
5014    }
5015
5016    /**
5017     * Returns deduplicated list of supported instructions for dex code.
5018     */
5019    public static String[] getAllDexCodeInstructionSets() {
5020        String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length];
5021        for (int i = 0; i < supportedInstructionSets.length; i++) {
5022            String abi = Build.SUPPORTED_ABIS[i];
5023            supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi);
5024        }
5025        return getDexCodeInstructionSets(supportedInstructionSets);
5026    }
5027
5028    @Override
5029    public void forceDexOpt(String packageName) {
5030        enforceSystemOrRoot("forceDexOpt");
5031
5032        PackageParser.Package pkg;
5033        synchronized (mPackages) {
5034            pkg = mPackages.get(packageName);
5035            if (pkg == null) {
5036                throw new IllegalArgumentException("Missing package: " + packageName);
5037            }
5038        }
5039
5040        synchronized (mInstallLock) {
5041            final String[] instructionSets = new String[] {
5042                    getPrimaryInstructionSet(pkg.applicationInfo) };
5043            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
5044            if (res != DEX_OPT_PERFORMED) {
5045                throw new IllegalStateException("Failed to dexopt: " + res);
5046            }
5047        }
5048    }
5049
5050    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
5051                                boolean forceDex, boolean defer, boolean inclDependencies) {
5052        ArraySet<String> done;
5053        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
5054            done = new ArraySet<String>();
5055            done.add(pkg.packageName);
5056        } else {
5057            done = null;
5058        }
5059        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
5060    }
5061
5062    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5063        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5064            Slog.w(TAG, "Unable to update from " + oldPkg.name
5065                    + " to " + newPkg.packageName
5066                    + ": old package not in system partition");
5067            return false;
5068        } else if (mPackages.get(oldPkg.name) != null) {
5069            Slog.w(TAG, "Unable to update from " + oldPkg.name
5070                    + " to " + newPkg.packageName
5071                    + ": old package still exists");
5072            return false;
5073        }
5074        return true;
5075    }
5076
5077    File getDataPathForUser(int userId) {
5078        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
5079    }
5080
5081    private File getDataPathForPackage(String packageName, int userId) {
5082        /*
5083         * Until we fully support multiple users, return the directory we
5084         * previously would have. The PackageManagerTests will need to be
5085         * revised when this is changed back..
5086         */
5087        if (userId == 0) {
5088            return new File(mAppDataDir, packageName);
5089        } else {
5090            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
5091                + File.separator + packageName);
5092        }
5093    }
5094
5095    private int createDataDirsLI(String packageName, int uid, String seinfo) {
5096        int[] users = sUserManager.getUserIds();
5097        int res = mInstaller.install(packageName, uid, uid, seinfo);
5098        if (res < 0) {
5099            return res;
5100        }
5101        for (int user : users) {
5102            if (user != 0) {
5103                res = mInstaller.createUserData(packageName,
5104                        UserHandle.getUid(user, uid), user, seinfo);
5105                if (res < 0) {
5106                    return res;
5107                }
5108            }
5109        }
5110        return res;
5111    }
5112
5113    private int removeDataDirsLI(String packageName) {
5114        int[] users = sUserManager.getUserIds();
5115        int res = 0;
5116        for (int user : users) {
5117            int resInner = mInstaller.remove(packageName, user);
5118            if (resInner < 0) {
5119                res = resInner;
5120            }
5121        }
5122
5123        return res;
5124    }
5125
5126    private int deleteCodeCacheDirsLI(String packageName) {
5127        int[] users = sUserManager.getUserIds();
5128        int res = 0;
5129        for (int user : users) {
5130            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
5131            if (resInner < 0) {
5132                res = resInner;
5133            }
5134        }
5135        return res;
5136    }
5137
5138    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5139            PackageParser.Package changingLib) {
5140        if (file.path != null) {
5141            usesLibraryFiles.add(file.path);
5142            return;
5143        }
5144        PackageParser.Package p = mPackages.get(file.apk);
5145        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5146            // If we are doing this while in the middle of updating a library apk,
5147            // then we need to make sure to use that new apk for determining the
5148            // dependencies here.  (We haven't yet finished committing the new apk
5149            // to the package manager state.)
5150            if (p == null || p.packageName.equals(changingLib.packageName)) {
5151                p = changingLib;
5152            }
5153        }
5154        if (p != null) {
5155            usesLibraryFiles.addAll(p.getAllCodePaths());
5156        }
5157    }
5158
5159    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5160            PackageParser.Package changingLib) throws PackageManagerException {
5161        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5162            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5163            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5164            for (int i=0; i<N; i++) {
5165                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5166                if (file == null) {
5167                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5168                            "Package " + pkg.packageName + " requires unavailable shared library "
5169                            + pkg.usesLibraries.get(i) + "; failing!");
5170                }
5171                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5172            }
5173            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5174            for (int i=0; i<N; i++) {
5175                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5176                if (file == null) {
5177                    Slog.w(TAG, "Package " + pkg.packageName
5178                            + " desires unavailable shared library "
5179                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5180                } else {
5181                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5182                }
5183            }
5184            N = usesLibraryFiles.size();
5185            if (N > 0) {
5186                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5187            } else {
5188                pkg.usesLibraryFiles = null;
5189            }
5190        }
5191    }
5192
5193    private static boolean hasString(List<String> list, List<String> which) {
5194        if (list == null) {
5195            return false;
5196        }
5197        for (int i=list.size()-1; i>=0; i--) {
5198            for (int j=which.size()-1; j>=0; j--) {
5199                if (which.get(j).equals(list.get(i))) {
5200                    return true;
5201                }
5202            }
5203        }
5204        return false;
5205    }
5206
5207    private void updateAllSharedLibrariesLPw() {
5208        for (PackageParser.Package pkg : mPackages.values()) {
5209            try {
5210                updateSharedLibrariesLPw(pkg, null);
5211            } catch (PackageManagerException e) {
5212                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5213            }
5214        }
5215    }
5216
5217    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5218            PackageParser.Package changingPkg) {
5219        ArrayList<PackageParser.Package> res = null;
5220        for (PackageParser.Package pkg : mPackages.values()) {
5221            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5222                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5223                if (res == null) {
5224                    res = new ArrayList<PackageParser.Package>();
5225                }
5226                res.add(pkg);
5227                try {
5228                    updateSharedLibrariesLPw(pkg, changingPkg);
5229                } catch (PackageManagerException e) {
5230                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5231                }
5232            }
5233        }
5234        return res;
5235    }
5236
5237    /**
5238     * Derive the value of the {@code cpuAbiOverride} based on the provided
5239     * value and an optional stored value from the package settings.
5240     */
5241    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5242        String cpuAbiOverride = null;
5243
5244        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5245            cpuAbiOverride = null;
5246        } else if (abiOverride != null) {
5247            cpuAbiOverride = abiOverride;
5248        } else if (settings != null) {
5249            cpuAbiOverride = settings.cpuAbiOverrideString;
5250        }
5251
5252        return cpuAbiOverride;
5253    }
5254
5255    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5256            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5257        boolean success = false;
5258        try {
5259            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5260                    currentTime, user);
5261            success = true;
5262            return res;
5263        } finally {
5264            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5265                removeDataDirsLI(pkg.packageName);
5266            }
5267        }
5268    }
5269
5270    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5271            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5272        final File scanFile = new File(pkg.codePath);
5273        if (pkg.applicationInfo.getCodePath() == null ||
5274                pkg.applicationInfo.getResourcePath() == null) {
5275            // Bail out. The resource and code paths haven't been set.
5276            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5277                    "Code and resource paths haven't been set correctly");
5278        }
5279
5280        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5281            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5282        } else {
5283            // Only allow system apps to be flagged as core apps.
5284            pkg.coreApp = false;
5285        }
5286
5287        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5288            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5289        }
5290
5291        if (mCustomResolverComponentName != null &&
5292                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5293            setUpCustomResolverActivity(pkg);
5294        }
5295
5296        if (pkg.packageName.equals("android")) {
5297            synchronized (mPackages) {
5298                if (mAndroidApplication != null) {
5299                    Slog.w(TAG, "*************************************************");
5300                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5301                    Slog.w(TAG, " file=" + scanFile);
5302                    Slog.w(TAG, "*************************************************");
5303                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5304                            "Core android package being redefined.  Skipping.");
5305                }
5306
5307                // Set up information for our fall-back user intent resolution activity.
5308                mPlatformPackage = pkg;
5309                pkg.mVersionCode = mSdkVersion;
5310                mAndroidApplication = pkg.applicationInfo;
5311
5312                if (!mResolverReplaced) {
5313                    mResolveActivity.applicationInfo = mAndroidApplication;
5314                    mResolveActivity.name = ResolverActivity.class.getName();
5315                    mResolveActivity.packageName = mAndroidApplication.packageName;
5316                    mResolveActivity.processName = "system:ui";
5317                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5318                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5319                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5320                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5321                    mResolveActivity.exported = true;
5322                    mResolveActivity.enabled = true;
5323                    mResolveInfo.activityInfo = mResolveActivity;
5324                    mResolveInfo.priority = 0;
5325                    mResolveInfo.preferredOrder = 0;
5326                    mResolveInfo.match = 0;
5327                    mResolveComponentName = new ComponentName(
5328                            mAndroidApplication.packageName, mResolveActivity.name);
5329                }
5330            }
5331        }
5332
5333        if (DEBUG_PACKAGE_SCANNING) {
5334            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5335                Log.d(TAG, "Scanning package " + pkg.packageName);
5336        }
5337
5338        if (mPackages.containsKey(pkg.packageName)
5339                || mSharedLibraries.containsKey(pkg.packageName)) {
5340            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5341                    "Application package " + pkg.packageName
5342                    + " already installed.  Skipping duplicate.");
5343        }
5344
5345        // Initialize package source and resource directories
5346        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5347        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5348
5349        SharedUserSetting suid = null;
5350        PackageSetting pkgSetting = null;
5351
5352        if (!isSystemApp(pkg)) {
5353            // Only system apps can use these features.
5354            pkg.mOriginalPackages = null;
5355            pkg.mRealPackage = null;
5356            pkg.mAdoptPermissions = null;
5357        }
5358
5359        // writer
5360        synchronized (mPackages) {
5361            if (pkg.mSharedUserId != null) {
5362                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5363                if (suid == null) {
5364                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5365                            "Creating application package " + pkg.packageName
5366                            + " for shared user failed");
5367                }
5368                if (DEBUG_PACKAGE_SCANNING) {
5369                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5370                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5371                                + "): packages=" + suid.packages);
5372                }
5373            }
5374
5375            // Check if we are renaming from an original package name.
5376            PackageSetting origPackage = null;
5377            String realName = null;
5378            if (pkg.mOriginalPackages != null) {
5379                // This package may need to be renamed to a previously
5380                // installed name.  Let's check on that...
5381                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5382                if (pkg.mOriginalPackages.contains(renamed)) {
5383                    // This package had originally been installed as the
5384                    // original name, and we have already taken care of
5385                    // transitioning to the new one.  Just update the new
5386                    // one to continue using the old name.
5387                    realName = pkg.mRealPackage;
5388                    if (!pkg.packageName.equals(renamed)) {
5389                        // Callers into this function may have already taken
5390                        // care of renaming the package; only do it here if
5391                        // it is not already done.
5392                        pkg.setPackageName(renamed);
5393                    }
5394
5395                } else {
5396                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5397                        if ((origPackage = mSettings.peekPackageLPr(
5398                                pkg.mOriginalPackages.get(i))) != null) {
5399                            // We do have the package already installed under its
5400                            // original name...  should we use it?
5401                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5402                                // New package is not compatible with original.
5403                                origPackage = null;
5404                                continue;
5405                            } else if (origPackage.sharedUser != null) {
5406                                // Make sure uid is compatible between packages.
5407                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5408                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5409                                            + " to " + pkg.packageName + ": old uid "
5410                                            + origPackage.sharedUser.name
5411                                            + " differs from " + pkg.mSharedUserId);
5412                                    origPackage = null;
5413                                    continue;
5414                                }
5415                            } else {
5416                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5417                                        + pkg.packageName + " to old name " + origPackage.name);
5418                            }
5419                            break;
5420                        }
5421                    }
5422                }
5423            }
5424
5425            if (mTransferedPackages.contains(pkg.packageName)) {
5426                Slog.w(TAG, "Package " + pkg.packageName
5427                        + " was transferred to another, but its .apk remains");
5428            }
5429
5430            // Just create the setting, don't add it yet. For already existing packages
5431            // the PkgSetting exists already and doesn't have to be created.
5432            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5433                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5434                    pkg.applicationInfo.primaryCpuAbi,
5435                    pkg.applicationInfo.secondaryCpuAbi,
5436                    pkg.applicationInfo.flags, user, false);
5437            if (pkgSetting == null) {
5438                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5439                        "Creating application package " + pkg.packageName + " failed");
5440            }
5441
5442            if (pkgSetting.origPackage != null) {
5443                // If we are first transitioning from an original package,
5444                // fix up the new package's name now.  We need to do this after
5445                // looking up the package under its new name, so getPackageLP
5446                // can take care of fiddling things correctly.
5447                pkg.setPackageName(origPackage.name);
5448
5449                // File a report about this.
5450                String msg = "New package " + pkgSetting.realName
5451                        + " renamed to replace old package " + pkgSetting.name;
5452                reportSettingsProblem(Log.WARN, msg);
5453
5454                // Make a note of it.
5455                mTransferedPackages.add(origPackage.name);
5456
5457                // No longer need to retain this.
5458                pkgSetting.origPackage = null;
5459            }
5460
5461            if (realName != null) {
5462                // Make a note of it.
5463                mTransferedPackages.add(pkg.packageName);
5464            }
5465
5466            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5467                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5468            }
5469
5470            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5471                // Check all shared libraries and map to their actual file path.
5472                // We only do this here for apps not on a system dir, because those
5473                // are the only ones that can fail an install due to this.  We
5474                // will take care of the system apps by updating all of their
5475                // library paths after the scan is done.
5476                updateSharedLibrariesLPw(pkg, null);
5477            }
5478
5479            if (mFoundPolicyFile) {
5480                SELinuxMMAC.assignSeinfoValue(pkg);
5481            }
5482
5483            pkg.applicationInfo.uid = pkgSetting.appId;
5484            pkg.mExtras = pkgSetting;
5485            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5486                try {
5487                    verifySignaturesLP(pkgSetting, pkg);
5488                    // We just determined the app is signed correctly, so bring
5489                    // over the latest parsed certs.
5490                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5491                } catch (PackageManagerException e) {
5492                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5493                        throw e;
5494                    }
5495                    // The signature has changed, but this package is in the system
5496                    // image...  let's recover!
5497                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5498                    // However...  if this package is part of a shared user, but it
5499                    // doesn't match the signature of the shared user, let's fail.
5500                    // What this means is that you can't change the signatures
5501                    // associated with an overall shared user, which doesn't seem all
5502                    // that unreasonable.
5503                    if (pkgSetting.sharedUser != null) {
5504                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5505                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5506                            throw new PackageManagerException(
5507                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5508                                            "Signature mismatch for shared user : "
5509                                            + pkgSetting.sharedUser);
5510                        }
5511                    }
5512                    // File a report about this.
5513                    String msg = "System package " + pkg.packageName
5514                        + " signature changed; retaining data.";
5515                    reportSettingsProblem(Log.WARN, msg);
5516                }
5517            } else {
5518                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5519                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5520                            + pkg.packageName + " upgrade keys do not match the "
5521                            + "previously installed version");
5522                } else {
5523                    // We just determined the app is signed correctly, so bring
5524                    // over the latest parsed certs.
5525                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5526                }
5527            }
5528            // Verify that this new package doesn't have any content providers
5529            // that conflict with existing packages.  Only do this if the
5530            // package isn't already installed, since we don't want to break
5531            // things that are installed.
5532            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5533                final int N = pkg.providers.size();
5534                int i;
5535                for (i=0; i<N; i++) {
5536                    PackageParser.Provider p = pkg.providers.get(i);
5537                    if (p.info.authority != null) {
5538                        String names[] = p.info.authority.split(";");
5539                        for (int j = 0; j < names.length; j++) {
5540                            if (mProvidersByAuthority.containsKey(names[j])) {
5541                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5542                                final String otherPackageName =
5543                                        ((other != null && other.getComponentName() != null) ?
5544                                                other.getComponentName().getPackageName() : "?");
5545                                throw new PackageManagerException(
5546                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5547                                                "Can't install because provider name " + names[j]
5548                                                + " (in package " + pkg.applicationInfo.packageName
5549                                                + ") is already used by " + otherPackageName);
5550                            }
5551                        }
5552                    }
5553                }
5554            }
5555
5556            if (pkg.mAdoptPermissions != null) {
5557                // This package wants to adopt ownership of permissions from
5558                // another package.
5559                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5560                    final String origName = pkg.mAdoptPermissions.get(i);
5561                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5562                    if (orig != null) {
5563                        if (verifyPackageUpdateLPr(orig, pkg)) {
5564                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5565                                    + pkg.packageName);
5566                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5567                        }
5568                    }
5569                }
5570            }
5571        }
5572
5573        final String pkgName = pkg.packageName;
5574
5575        final long scanFileTime = scanFile.lastModified();
5576        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5577        pkg.applicationInfo.processName = fixProcessName(
5578                pkg.applicationInfo.packageName,
5579                pkg.applicationInfo.processName,
5580                pkg.applicationInfo.uid);
5581
5582        File dataPath;
5583        if (mPlatformPackage == pkg) {
5584            // The system package is special.
5585            dataPath = new File(Environment.getDataDirectory(), "system");
5586
5587            pkg.applicationInfo.dataDir = dataPath.getPath();
5588
5589        } else {
5590            // This is a normal package, need to make its data directory.
5591            dataPath = getDataPathForPackage(pkg.packageName, 0);
5592
5593            boolean uidError = false;
5594            if (dataPath.exists()) {
5595                int currentUid = 0;
5596                try {
5597                    StructStat stat = Os.stat(dataPath.getPath());
5598                    currentUid = stat.st_uid;
5599                } catch (ErrnoException e) {
5600                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5601                }
5602
5603                // If we have mismatched owners for the data path, we have a problem.
5604                if (currentUid != pkg.applicationInfo.uid) {
5605                    boolean recovered = false;
5606                    if (currentUid == 0) {
5607                        // The directory somehow became owned by root.  Wow.
5608                        // This is probably because the system was stopped while
5609                        // installd was in the middle of messing with its libs
5610                        // directory.  Ask installd to fix that.
5611                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5612                                pkg.applicationInfo.uid);
5613                        if (ret >= 0) {
5614                            recovered = true;
5615                            String msg = "Package " + pkg.packageName
5616                                    + " unexpectedly changed to uid 0; recovered to " +
5617                                    + pkg.applicationInfo.uid;
5618                            reportSettingsProblem(Log.WARN, msg);
5619                        }
5620                    }
5621                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5622                            || (scanFlags&SCAN_BOOTING) != 0)) {
5623                        // If this is a system app, we can at least delete its
5624                        // current data so the application will still work.
5625                        int ret = removeDataDirsLI(pkgName);
5626                        if (ret >= 0) {
5627                            // TODO: Kill the processes first
5628                            // Old data gone!
5629                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5630                                    ? "System package " : "Third party package ";
5631                            String msg = prefix + pkg.packageName
5632                                    + " has changed from uid: "
5633                                    + currentUid + " to "
5634                                    + pkg.applicationInfo.uid + "; old data erased";
5635                            reportSettingsProblem(Log.WARN, msg);
5636                            recovered = true;
5637
5638                            // And now re-install the app.
5639                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5640                                                   pkg.applicationInfo.seinfo);
5641                            if (ret == -1) {
5642                                // Ack should not happen!
5643                                msg = prefix + pkg.packageName
5644                                        + " could not have data directory re-created after delete.";
5645                                reportSettingsProblem(Log.WARN, msg);
5646                                throw new PackageManagerException(
5647                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5648                            }
5649                        }
5650                        if (!recovered) {
5651                            mHasSystemUidErrors = true;
5652                        }
5653                    } else if (!recovered) {
5654                        // If we allow this install to proceed, we will be broken.
5655                        // Abort, abort!
5656                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5657                                "scanPackageLI");
5658                    }
5659                    if (!recovered) {
5660                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5661                            + pkg.applicationInfo.uid + "/fs_"
5662                            + currentUid;
5663                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5664                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5665                        String msg = "Package " + pkg.packageName
5666                                + " has mismatched uid: "
5667                                + currentUid + " on disk, "
5668                                + pkg.applicationInfo.uid + " in settings";
5669                        // writer
5670                        synchronized (mPackages) {
5671                            mSettings.mReadMessages.append(msg);
5672                            mSettings.mReadMessages.append('\n');
5673                            uidError = true;
5674                            if (!pkgSetting.uidError) {
5675                                reportSettingsProblem(Log.ERROR, msg);
5676                            }
5677                        }
5678                    }
5679                }
5680                pkg.applicationInfo.dataDir = dataPath.getPath();
5681                if (mShouldRestoreconData) {
5682                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5683                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5684                                pkg.applicationInfo.uid);
5685                }
5686            } else {
5687                if (DEBUG_PACKAGE_SCANNING) {
5688                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5689                        Log.v(TAG, "Want this data dir: " + dataPath);
5690                }
5691                //invoke installer to do the actual installation
5692                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5693                                           pkg.applicationInfo.seinfo);
5694                if (ret < 0) {
5695                    // Error from installer
5696                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5697                            "Unable to create data dirs [errorCode=" + ret + "]");
5698                }
5699
5700                if (dataPath.exists()) {
5701                    pkg.applicationInfo.dataDir = dataPath.getPath();
5702                } else {
5703                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5704                    pkg.applicationInfo.dataDir = null;
5705                }
5706            }
5707
5708            pkgSetting.uidError = uidError;
5709        }
5710
5711        final String path = scanFile.getPath();
5712        final String codePath = pkg.applicationInfo.getCodePath();
5713        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5714        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5715            setBundledAppAbisAndRoots(pkg, pkgSetting);
5716
5717            // If we haven't found any native libraries for the app, check if it has
5718            // renderscript code. We'll need to force the app to 32 bit if it has
5719            // renderscript bitcode.
5720            if (pkg.applicationInfo.primaryCpuAbi == null
5721                    && pkg.applicationInfo.secondaryCpuAbi == null
5722                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5723                NativeLibraryHelper.Handle handle = null;
5724                try {
5725                    handle = NativeLibraryHelper.Handle.create(scanFile);
5726                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5727                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5728                    }
5729                } catch (IOException ioe) {
5730                    Slog.w(TAG, "Error scanning system app : " + ioe);
5731                } finally {
5732                    IoUtils.closeQuietly(handle);
5733                }
5734            }
5735
5736            setNativeLibraryPaths(pkg);
5737        } else {
5738            // TODO: We can probably be smarter about this stuff. For installed apps,
5739            // we can calculate this information at install time once and for all. For
5740            // system apps, we can probably assume that this information doesn't change
5741            // after the first boot scan. As things stand, we do lots of unnecessary work.
5742
5743            // Give ourselves some initial paths; we'll come back for another
5744            // pass once we've determined ABI below.
5745            setNativeLibraryPaths(pkg);
5746
5747            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5748            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5749            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5750
5751            NativeLibraryHelper.Handle handle = null;
5752            try {
5753                handle = NativeLibraryHelper.Handle.create(scanFile);
5754                // TODO(multiArch): This can be null for apps that didn't go through the
5755                // usual installation process. We can calculate it again, like we
5756                // do during install time.
5757                //
5758                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5759                // unnecessary.
5760                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5761
5762                // Null out the abis so that they can be recalculated.
5763                pkg.applicationInfo.primaryCpuAbi = null;
5764                pkg.applicationInfo.secondaryCpuAbi = null;
5765                if (isMultiArch(pkg.applicationInfo)) {
5766                    // Warn if we've set an abiOverride for multi-lib packages..
5767                    // By definition, we need to copy both 32 and 64 bit libraries for
5768                    // such packages.
5769                    if (pkg.cpuAbiOverride != null
5770                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5771                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5772                    }
5773
5774                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5775                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5776                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5777                        if (isAsec) {
5778                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5779                        } else {
5780                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5781                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5782                                    useIsaSpecificSubdirs);
5783                        }
5784                    }
5785
5786                    maybeThrowExceptionForMultiArchCopy(
5787                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5788
5789                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5790                        if (isAsec) {
5791                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5792                        } else {
5793                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5794                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5795                                    useIsaSpecificSubdirs);
5796                        }
5797                    }
5798
5799                    maybeThrowExceptionForMultiArchCopy(
5800                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5801
5802                    if (abi64 >= 0) {
5803                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5804                    }
5805
5806                    if (abi32 >= 0) {
5807                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5808                        if (abi64 >= 0) {
5809                            pkg.applicationInfo.secondaryCpuAbi = abi;
5810                        } else {
5811                            pkg.applicationInfo.primaryCpuAbi = abi;
5812                        }
5813                    }
5814                } else {
5815                    String[] abiList = (cpuAbiOverride != null) ?
5816                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5817
5818                    // Enable gross and lame hacks for apps that are built with old
5819                    // SDK tools. We must scan their APKs for renderscript bitcode and
5820                    // not launch them if it's present. Don't bother checking on devices
5821                    // that don't have 64 bit support.
5822                    boolean needsRenderScriptOverride = false;
5823                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5824                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5825                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5826                        needsRenderScriptOverride = true;
5827                    }
5828
5829                    final int copyRet;
5830                    if (isAsec) {
5831                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5832                    } else {
5833                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5834                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5835                    }
5836
5837                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5838                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5839                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5840                    }
5841
5842                    if (copyRet >= 0) {
5843                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5844                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5845                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5846                    } else if (needsRenderScriptOverride) {
5847                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5848                    }
5849                }
5850            } catch (IOException ioe) {
5851                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5852            } finally {
5853                IoUtils.closeQuietly(handle);
5854            }
5855
5856            // Now that we've calculated the ABIs and determined if it's an internal app,
5857            // we will go ahead and populate the nativeLibraryPath.
5858            setNativeLibraryPaths(pkg);
5859
5860            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5861            final int[] userIds = sUserManager.getUserIds();
5862            synchronized (mInstallLock) {
5863                // Create a native library symlink only if we have native libraries
5864                // and if the native libraries are 32 bit libraries. We do not provide
5865                // this symlink for 64 bit libraries.
5866                if (pkg.applicationInfo.primaryCpuAbi != null &&
5867                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5868                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5869                    for (int userId : userIds) {
5870                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5871                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5872                                    "Failed linking native library dir (user=" + userId + ")");
5873                        }
5874                    }
5875                }
5876            }
5877        }
5878
5879        // This is a special case for the "system" package, where the ABI is
5880        // dictated by the zygote configuration (and init.rc). We should keep track
5881        // of this ABI so that we can deal with "normal" applications that run under
5882        // the same UID correctly.
5883        if (mPlatformPackage == pkg) {
5884            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5885                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5886        }
5887
5888        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5889        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5890        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5891        // Copy the derived override back to the parsed package, so that we can
5892        // update the package settings accordingly.
5893        pkg.cpuAbiOverride = cpuAbiOverride;
5894
5895        if (DEBUG_ABI_SELECTION) {
5896            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5897                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5898                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5899        }
5900
5901        // Push the derived path down into PackageSettings so we know what to
5902        // clean up at uninstall time.
5903        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5904
5905        if (DEBUG_ABI_SELECTION) {
5906            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5907                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5908                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5909        }
5910
5911        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5912            // We don't do this here during boot because we can do it all
5913            // at once after scanning all existing packages.
5914            //
5915            // We also do this *before* we perform dexopt on this package, so that
5916            // we can avoid redundant dexopts, and also to make sure we've got the
5917            // code and package path correct.
5918            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5919                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5920        }
5921
5922        if ((scanFlags & SCAN_NO_DEX) == 0) {
5923            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5924                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5925                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5926            }
5927        }
5928
5929        if (mFactoryTest && pkg.requestedPermissions.contains(
5930                android.Manifest.permission.FACTORY_TEST)) {
5931            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5932        }
5933
5934        ArrayList<PackageParser.Package> clientLibPkgs = null;
5935
5936        // writer
5937        synchronized (mPackages) {
5938            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5939                // Only system apps can add new shared libraries.
5940                if (pkg.libraryNames != null) {
5941                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5942                        String name = pkg.libraryNames.get(i);
5943                        boolean allowed = false;
5944                        if (isUpdatedSystemApp(pkg)) {
5945                            // New library entries can only be added through the
5946                            // system image.  This is important to get rid of a lot
5947                            // of nasty edge cases: for example if we allowed a non-
5948                            // system update of the app to add a library, then uninstalling
5949                            // the update would make the library go away, and assumptions
5950                            // we made such as through app install filtering would now
5951                            // have allowed apps on the device which aren't compatible
5952                            // with it.  Better to just have the restriction here, be
5953                            // conservative, and create many fewer cases that can negatively
5954                            // impact the user experience.
5955                            final PackageSetting sysPs = mSettings
5956                                    .getDisabledSystemPkgLPr(pkg.packageName);
5957                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5958                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5959                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5960                                        allowed = true;
5961                                        allowed = true;
5962                                        break;
5963                                    }
5964                                }
5965                            }
5966                        } else {
5967                            allowed = true;
5968                        }
5969                        if (allowed) {
5970                            if (!mSharedLibraries.containsKey(name)) {
5971                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5972                            } else if (!name.equals(pkg.packageName)) {
5973                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5974                                        + name + " already exists; skipping");
5975                            }
5976                        } else {
5977                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5978                                    + name + " that is not declared on system image; skipping");
5979                        }
5980                    }
5981                    if ((scanFlags&SCAN_BOOTING) == 0) {
5982                        // If we are not booting, we need to update any applications
5983                        // that are clients of our shared library.  If we are booting,
5984                        // this will all be done once the scan is complete.
5985                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5986                    }
5987                }
5988            }
5989        }
5990
5991        // We also need to dexopt any apps that are dependent on this library.  Note that
5992        // if these fail, we should abort the install since installing the library will
5993        // result in some apps being broken.
5994        if (clientLibPkgs != null) {
5995            if ((scanFlags & SCAN_NO_DEX) == 0) {
5996                for (int i = 0; i < clientLibPkgs.size(); i++) {
5997                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5998                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
5999                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
6000                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6001                                "scanPackageLI failed to dexopt clientLibPkgs");
6002                    }
6003                }
6004            }
6005        }
6006
6007        // Request the ActivityManager to kill the process(only for existing packages)
6008        // so that we do not end up in a confused state while the user is still using the older
6009        // version of the application while the new one gets installed.
6010        if ((scanFlags & SCAN_REPLACING) != 0) {
6011            killApplication(pkg.applicationInfo.packageName,
6012                        pkg.applicationInfo.uid, "update pkg");
6013        }
6014
6015        // Also need to kill any apps that are dependent on the library.
6016        if (clientLibPkgs != null) {
6017            for (int i=0; i<clientLibPkgs.size(); i++) {
6018                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6019                killApplication(clientPkg.applicationInfo.packageName,
6020                        clientPkg.applicationInfo.uid, "update lib");
6021            }
6022        }
6023
6024        // writer
6025        synchronized (mPackages) {
6026            // We don't expect installation to fail beyond this point
6027
6028            // Add the new setting to mSettings
6029            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6030            // Add the new setting to mPackages
6031            mPackages.put(pkg.applicationInfo.packageName, pkg);
6032            // Make sure we don't accidentally delete its data.
6033            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6034            while (iter.hasNext()) {
6035                PackageCleanItem item = iter.next();
6036                if (pkgName.equals(item.packageName)) {
6037                    iter.remove();
6038                }
6039            }
6040
6041            // Take care of first install / last update times.
6042            if (currentTime != 0) {
6043                if (pkgSetting.firstInstallTime == 0) {
6044                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6045                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6046                    pkgSetting.lastUpdateTime = currentTime;
6047                }
6048            } else if (pkgSetting.firstInstallTime == 0) {
6049                // We need *something*.  Take time time stamp of the file.
6050                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6051            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6052                if (scanFileTime != pkgSetting.timeStamp) {
6053                    // A package on the system image has changed; consider this
6054                    // to be an update.
6055                    pkgSetting.lastUpdateTime = scanFileTime;
6056                }
6057            }
6058
6059            // Add the package's KeySets to the global KeySetManagerService
6060            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6061            try {
6062                // Old KeySetData no longer valid.
6063                ksms.removeAppKeySetDataLPw(pkg.packageName);
6064                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6065                if (pkg.mKeySetMapping != null) {
6066                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
6067                            pkg.mKeySetMapping.entrySet()) {
6068                        if (entry.getValue() != null) {
6069                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
6070                                                          entry.getValue(), entry.getKey());
6071                        }
6072                    }
6073                    if (pkg.mUpgradeKeySets != null) {
6074                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
6075                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
6076                        }
6077                    }
6078                }
6079            } catch (NullPointerException e) {
6080                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6081            } catch (IllegalArgumentException e) {
6082                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6083            }
6084
6085            int N = pkg.providers.size();
6086            StringBuilder r = null;
6087            int i;
6088            for (i=0; i<N; i++) {
6089                PackageParser.Provider p = pkg.providers.get(i);
6090                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6091                        p.info.processName, pkg.applicationInfo.uid);
6092                mProviders.addProvider(p);
6093                p.syncable = p.info.isSyncable;
6094                if (p.info.authority != null) {
6095                    String names[] = p.info.authority.split(";");
6096                    p.info.authority = null;
6097                    for (int j = 0; j < names.length; j++) {
6098                        if (j == 1 && p.syncable) {
6099                            // We only want the first authority for a provider to possibly be
6100                            // syncable, so if we already added this provider using a different
6101                            // authority clear the syncable flag. We copy the provider before
6102                            // changing it because the mProviders object contains a reference
6103                            // to a provider that we don't want to change.
6104                            // Only do this for the second authority since the resulting provider
6105                            // object can be the same for all future authorities for this provider.
6106                            p = new PackageParser.Provider(p);
6107                            p.syncable = false;
6108                        }
6109                        if (!mProvidersByAuthority.containsKey(names[j])) {
6110                            mProvidersByAuthority.put(names[j], p);
6111                            if (p.info.authority == null) {
6112                                p.info.authority = names[j];
6113                            } else {
6114                                p.info.authority = p.info.authority + ";" + names[j];
6115                            }
6116                            if (DEBUG_PACKAGE_SCANNING) {
6117                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6118                                    Log.d(TAG, "Registered content provider: " + names[j]
6119                                            + ", className = " + p.info.name + ", isSyncable = "
6120                                            + p.info.isSyncable);
6121                            }
6122                        } else {
6123                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6124                            Slog.w(TAG, "Skipping provider name " + names[j] +
6125                                    " (in package " + pkg.applicationInfo.packageName +
6126                                    "): name already used by "
6127                                    + ((other != null && other.getComponentName() != null)
6128                                            ? other.getComponentName().getPackageName() : "?"));
6129                        }
6130                    }
6131                }
6132                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6133                    if (r == null) {
6134                        r = new StringBuilder(256);
6135                    } else {
6136                        r.append(' ');
6137                    }
6138                    r.append(p.info.name);
6139                }
6140            }
6141            if (r != null) {
6142                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6143            }
6144
6145            N = pkg.services.size();
6146            r = null;
6147            for (i=0; i<N; i++) {
6148                PackageParser.Service s = pkg.services.get(i);
6149                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6150                        s.info.processName, pkg.applicationInfo.uid);
6151                mServices.addService(s);
6152                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6153                    if (r == null) {
6154                        r = new StringBuilder(256);
6155                    } else {
6156                        r.append(' ');
6157                    }
6158                    r.append(s.info.name);
6159                }
6160            }
6161            if (r != null) {
6162                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6163            }
6164
6165            N = pkg.receivers.size();
6166            r = null;
6167            for (i=0; i<N; i++) {
6168                PackageParser.Activity a = pkg.receivers.get(i);
6169                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6170                        a.info.processName, pkg.applicationInfo.uid);
6171                mReceivers.addActivity(a, "receiver");
6172                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6173                    if (r == null) {
6174                        r = new StringBuilder(256);
6175                    } else {
6176                        r.append(' ');
6177                    }
6178                    r.append(a.info.name);
6179                }
6180            }
6181            if (r != null) {
6182                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6183            }
6184
6185            N = pkg.activities.size();
6186            r = null;
6187            for (i=0; i<N; i++) {
6188                PackageParser.Activity a = pkg.activities.get(i);
6189                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6190                        a.info.processName, pkg.applicationInfo.uid);
6191                mActivities.addActivity(a, "activity");
6192                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6193                    if (r == null) {
6194                        r = new StringBuilder(256);
6195                    } else {
6196                        r.append(' ');
6197                    }
6198                    r.append(a.info.name);
6199                }
6200            }
6201            if (r != null) {
6202                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6203            }
6204
6205            N = pkg.permissionGroups.size();
6206            r = null;
6207            for (i=0; i<N; i++) {
6208                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6209                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6210                if (cur == null) {
6211                    mPermissionGroups.put(pg.info.name, pg);
6212                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6213                        if (r == null) {
6214                            r = new StringBuilder(256);
6215                        } else {
6216                            r.append(' ');
6217                        }
6218                        r.append(pg.info.name);
6219                    }
6220                } else {
6221                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6222                            + pg.info.packageName + " ignored: original from "
6223                            + cur.info.packageName);
6224                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6225                        if (r == null) {
6226                            r = new StringBuilder(256);
6227                        } else {
6228                            r.append(' ');
6229                        }
6230                        r.append("DUP:");
6231                        r.append(pg.info.name);
6232                    }
6233                }
6234            }
6235            if (r != null) {
6236                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6237            }
6238
6239            N = pkg.permissions.size();
6240            r = null;
6241            for (i=0; i<N; i++) {
6242                PackageParser.Permission p = pkg.permissions.get(i);
6243                ArrayMap<String, BasePermission> permissionMap =
6244                        p.tree ? mSettings.mPermissionTrees
6245                        : mSettings.mPermissions;
6246                p.group = mPermissionGroups.get(p.info.group);
6247                if (p.info.group == null || p.group != null) {
6248                    BasePermission bp = permissionMap.get(p.info.name);
6249
6250                    // Allow system apps to redefine non-system permissions
6251                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6252                        final boolean currentOwnerIsSystem = (bp.perm != null
6253                                && isSystemApp(bp.perm.owner));
6254                        if (isSystemApp(p.owner)) {
6255                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6256                                // It's a built-in permission and no owner, take ownership now
6257                                bp.packageSetting = pkgSetting;
6258                                bp.perm = p;
6259                                bp.uid = pkg.applicationInfo.uid;
6260                                bp.sourcePackage = p.info.packageName;
6261                            } else if (!currentOwnerIsSystem) {
6262                                String msg = "New decl " + p.owner + " of permission  "
6263                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6264                                reportSettingsProblem(Log.WARN, msg);
6265                                bp = null;
6266                            }
6267                        }
6268                    }
6269
6270                    if (bp == null) {
6271                        bp = new BasePermission(p.info.name, p.info.packageName,
6272                                BasePermission.TYPE_NORMAL);
6273                        permissionMap.put(p.info.name, bp);
6274                    }
6275
6276                    if (bp.perm == null) {
6277                        if (bp.sourcePackage == null
6278                                || bp.sourcePackage.equals(p.info.packageName)) {
6279                            BasePermission tree = findPermissionTreeLP(p.info.name);
6280                            if (tree == null
6281                                    || tree.sourcePackage.equals(p.info.packageName)) {
6282                                bp.packageSetting = pkgSetting;
6283                                bp.perm = p;
6284                                bp.uid = pkg.applicationInfo.uid;
6285                                bp.sourcePackage = p.info.packageName;
6286                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6287                                    if (r == null) {
6288                                        r = new StringBuilder(256);
6289                                    } else {
6290                                        r.append(' ');
6291                                    }
6292                                    r.append(p.info.name);
6293                                }
6294                            } else {
6295                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6296                                        + p.info.packageName + " ignored: base tree "
6297                                        + tree.name + " is from package "
6298                                        + tree.sourcePackage);
6299                            }
6300                        } else {
6301                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6302                                    + p.info.packageName + " ignored: original from "
6303                                    + bp.sourcePackage);
6304                        }
6305                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6306                        if (r == null) {
6307                            r = new StringBuilder(256);
6308                        } else {
6309                            r.append(' ');
6310                        }
6311                        r.append("DUP:");
6312                        r.append(p.info.name);
6313                    }
6314                    if (bp.perm == p) {
6315                        bp.protectionLevel = p.info.protectionLevel;
6316                    }
6317                } else {
6318                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6319                            + p.info.packageName + " ignored: no group "
6320                            + p.group);
6321                }
6322            }
6323            if (r != null) {
6324                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6325            }
6326
6327            N = pkg.instrumentation.size();
6328            r = null;
6329            for (i=0; i<N; i++) {
6330                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6331                a.info.packageName = pkg.applicationInfo.packageName;
6332                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6333                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6334                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6335                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6336                a.info.dataDir = pkg.applicationInfo.dataDir;
6337
6338                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6339                // need other information about the application, like the ABI and what not ?
6340                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6341                mInstrumentation.put(a.getComponentName(), a);
6342                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6343                    if (r == null) {
6344                        r = new StringBuilder(256);
6345                    } else {
6346                        r.append(' ');
6347                    }
6348                    r.append(a.info.name);
6349                }
6350            }
6351            if (r != null) {
6352                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6353            }
6354
6355            if (pkg.protectedBroadcasts != null) {
6356                N = pkg.protectedBroadcasts.size();
6357                for (i=0; i<N; i++) {
6358                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6359                }
6360            }
6361
6362            pkgSetting.setTimeStamp(scanFileTime);
6363
6364            // Create idmap files for pairs of (packages, overlay packages).
6365            // Note: "android", ie framework-res.apk, is handled by native layers.
6366            if (pkg.mOverlayTarget != null) {
6367                // This is an overlay package.
6368                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6369                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6370                        mOverlays.put(pkg.mOverlayTarget,
6371                                new ArrayMap<String, PackageParser.Package>());
6372                    }
6373                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6374                    map.put(pkg.packageName, pkg);
6375                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6376                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6377                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6378                                "scanPackageLI failed to createIdmap");
6379                    }
6380                }
6381            } else if (mOverlays.containsKey(pkg.packageName) &&
6382                    !pkg.packageName.equals("android")) {
6383                // This is a regular package, with one or more known overlay packages.
6384                createIdmapsForPackageLI(pkg);
6385            }
6386        }
6387
6388        return pkg;
6389    }
6390
6391    /**
6392     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6393     * i.e, so that all packages can be run inside a single process if required.
6394     *
6395     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6396     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6397     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6398     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6399     * updating a package that belongs to a shared user.
6400     *
6401     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6402     * adds unnecessary complexity.
6403     */
6404    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6405            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6406        String requiredInstructionSet = null;
6407        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6408            requiredInstructionSet = VMRuntime.getInstructionSet(
6409                     scannedPackage.applicationInfo.primaryCpuAbi);
6410        }
6411
6412        PackageSetting requirer = null;
6413        for (PackageSetting ps : packagesForUser) {
6414            // If packagesForUser contains scannedPackage, we skip it. This will happen
6415            // when scannedPackage is an update of an existing package. Without this check,
6416            // we will never be able to change the ABI of any package belonging to a shared
6417            // user, even if it's compatible with other packages.
6418            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6419                if (ps.primaryCpuAbiString == null) {
6420                    continue;
6421                }
6422
6423                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6424                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6425                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6426                    // this but there's not much we can do.
6427                    String errorMessage = "Instruction set mismatch, "
6428                            + ((requirer == null) ? "[caller]" : requirer)
6429                            + " requires " + requiredInstructionSet + " whereas " + ps
6430                            + " requires " + instructionSet;
6431                    Slog.w(TAG, errorMessage);
6432                }
6433
6434                if (requiredInstructionSet == null) {
6435                    requiredInstructionSet = instructionSet;
6436                    requirer = ps;
6437                }
6438            }
6439        }
6440
6441        if (requiredInstructionSet != null) {
6442            String adjustedAbi;
6443            if (requirer != null) {
6444                // requirer != null implies that either scannedPackage was null or that scannedPackage
6445                // did not require an ABI, in which case we have to adjust scannedPackage to match
6446                // the ABI of the set (which is the same as requirer's ABI)
6447                adjustedAbi = requirer.primaryCpuAbiString;
6448                if (scannedPackage != null) {
6449                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6450                }
6451            } else {
6452                // requirer == null implies that we're updating all ABIs in the set to
6453                // match scannedPackage.
6454                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6455            }
6456
6457            for (PackageSetting ps : packagesForUser) {
6458                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6459                    if (ps.primaryCpuAbiString != null) {
6460                        continue;
6461                    }
6462
6463                    ps.primaryCpuAbiString = adjustedAbi;
6464                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6465                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6466                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6467
6468                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6469                                deferDexOpt, true) == DEX_OPT_FAILED) {
6470                            ps.primaryCpuAbiString = null;
6471                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6472                            return;
6473                        } else {
6474                            mInstaller.rmdex(ps.codePathString,
6475                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6476                        }
6477                    }
6478                }
6479            }
6480        }
6481    }
6482
6483    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6484        synchronized (mPackages) {
6485            mResolverReplaced = true;
6486            // Set up information for custom user intent resolution activity.
6487            mResolveActivity.applicationInfo = pkg.applicationInfo;
6488            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6489            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6490            mResolveActivity.processName = pkg.applicationInfo.packageName;
6491            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6492            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6493                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6494            mResolveActivity.theme = 0;
6495            mResolveActivity.exported = true;
6496            mResolveActivity.enabled = true;
6497            mResolveInfo.activityInfo = mResolveActivity;
6498            mResolveInfo.priority = 0;
6499            mResolveInfo.preferredOrder = 0;
6500            mResolveInfo.match = 0;
6501            mResolveComponentName = mCustomResolverComponentName;
6502            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6503                    mResolveComponentName);
6504        }
6505    }
6506
6507    private static String calculateBundledApkRoot(final String codePathString) {
6508        final File codePath = new File(codePathString);
6509        final File codeRoot;
6510        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6511            codeRoot = Environment.getRootDirectory();
6512        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6513            codeRoot = Environment.getOemDirectory();
6514        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6515            codeRoot = Environment.getVendorDirectory();
6516        } else {
6517            // Unrecognized code path; take its top real segment as the apk root:
6518            // e.g. /something/app/blah.apk => /something
6519            try {
6520                File f = codePath.getCanonicalFile();
6521                File parent = f.getParentFile();    // non-null because codePath is a file
6522                File tmp;
6523                while ((tmp = parent.getParentFile()) != null) {
6524                    f = parent;
6525                    parent = tmp;
6526                }
6527                codeRoot = f;
6528                Slog.w(TAG, "Unrecognized code path "
6529                        + codePath + " - using " + codeRoot);
6530            } catch (IOException e) {
6531                // Can't canonicalize the code path -- shenanigans?
6532                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6533                return Environment.getRootDirectory().getPath();
6534            }
6535        }
6536        return codeRoot.getPath();
6537    }
6538
6539    /**
6540     * Derive and set the location of native libraries for the given package,
6541     * which varies depending on where and how the package was installed.
6542     */
6543    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6544        final ApplicationInfo info = pkg.applicationInfo;
6545        final String codePath = pkg.codePath;
6546        final File codeFile = new File(codePath);
6547        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6548        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6549
6550        info.nativeLibraryRootDir = null;
6551        info.nativeLibraryRootRequiresIsa = false;
6552        info.nativeLibraryDir = null;
6553        info.secondaryNativeLibraryDir = null;
6554
6555        if (isApkFile(codeFile)) {
6556            // Monolithic install
6557            if (bundledApp) {
6558                // If "/system/lib64/apkname" exists, assume that is the per-package
6559                // native library directory to use; otherwise use "/system/lib/apkname".
6560                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6561                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6562                        getPrimaryInstructionSet(info));
6563
6564                // This is a bundled system app so choose the path based on the ABI.
6565                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6566                // is just the default path.
6567                final String apkName = deriveCodePathName(codePath);
6568                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6569                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6570                        apkName).getAbsolutePath();
6571
6572                if (info.secondaryCpuAbi != null) {
6573                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6574                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6575                            secondaryLibDir, apkName).getAbsolutePath();
6576                }
6577            } else if (asecApp) {
6578                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6579                        .getAbsolutePath();
6580            } else {
6581                final String apkName = deriveCodePathName(codePath);
6582                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6583                        .getAbsolutePath();
6584            }
6585
6586            info.nativeLibraryRootRequiresIsa = false;
6587            info.nativeLibraryDir = info.nativeLibraryRootDir;
6588        } else {
6589            // Cluster install
6590            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6591            info.nativeLibraryRootRequiresIsa = true;
6592
6593            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6594                    getPrimaryInstructionSet(info)).getAbsolutePath();
6595
6596            if (info.secondaryCpuAbi != null) {
6597                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6598                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6599            }
6600        }
6601    }
6602
6603    /**
6604     * Calculate the abis and roots for a bundled app. These can uniquely
6605     * be determined from the contents of the system partition, i.e whether
6606     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6607     * of this information, and instead assume that the system was built
6608     * sensibly.
6609     */
6610    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6611                                           PackageSetting pkgSetting) {
6612        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6613
6614        // If "/system/lib64/apkname" exists, assume that is the per-package
6615        // native library directory to use; otherwise use "/system/lib/apkname".
6616        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6617        setBundledAppAbi(pkg, apkRoot, apkName);
6618        // pkgSetting might be null during rescan following uninstall of updates
6619        // to a bundled app, so accommodate that possibility.  The settings in
6620        // that case will be established later from the parsed package.
6621        //
6622        // If the settings aren't null, sync them up with what we've just derived.
6623        // note that apkRoot isn't stored in the package settings.
6624        if (pkgSetting != null) {
6625            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6626            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6627        }
6628    }
6629
6630    /**
6631     * Deduces the ABI of a bundled app and sets the relevant fields on the
6632     * parsed pkg object.
6633     *
6634     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6635     *        under which system libraries are installed.
6636     * @param apkName the name of the installed package.
6637     */
6638    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6639        final File codeFile = new File(pkg.codePath);
6640
6641        final boolean has64BitLibs;
6642        final boolean has32BitLibs;
6643        if (isApkFile(codeFile)) {
6644            // Monolithic install
6645            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6646            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6647        } else {
6648            // Cluster install
6649            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6650            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6651                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6652                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6653                has64BitLibs = (new File(rootDir, isa)).exists();
6654            } else {
6655                has64BitLibs = false;
6656            }
6657            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6658                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6659                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6660                has32BitLibs = (new File(rootDir, isa)).exists();
6661            } else {
6662                has32BitLibs = false;
6663            }
6664        }
6665
6666        if (has64BitLibs && !has32BitLibs) {
6667            // The package has 64 bit libs, but not 32 bit libs. Its primary
6668            // ABI should be 64 bit. We can safely assume here that the bundled
6669            // native libraries correspond to the most preferred ABI in the list.
6670
6671            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6672            pkg.applicationInfo.secondaryCpuAbi = null;
6673        } else if (has32BitLibs && !has64BitLibs) {
6674            // The package has 32 bit libs but not 64 bit libs. Its primary
6675            // ABI should be 32 bit.
6676
6677            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6678            pkg.applicationInfo.secondaryCpuAbi = null;
6679        } else if (has32BitLibs && has64BitLibs) {
6680            // The application has both 64 and 32 bit bundled libraries. We check
6681            // here that the app declares multiArch support, and warn if it doesn't.
6682            //
6683            // We will be lenient here and record both ABIs. The primary will be the
6684            // ABI that's higher on the list, i.e, a device that's configured to prefer
6685            // 64 bit apps will see a 64 bit primary ABI,
6686
6687            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6688                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6689            }
6690
6691            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6692                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6693                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6694            } else {
6695                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6696                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6697            }
6698        } else {
6699            pkg.applicationInfo.primaryCpuAbi = null;
6700            pkg.applicationInfo.secondaryCpuAbi = null;
6701        }
6702    }
6703
6704    private void killApplication(String pkgName, int appId, String reason) {
6705        // Request the ActivityManager to kill the process(only for existing packages)
6706        // so that we do not end up in a confused state while the user is still using the older
6707        // version of the application while the new one gets installed.
6708        IActivityManager am = ActivityManagerNative.getDefault();
6709        if (am != null) {
6710            try {
6711                am.killApplicationWithAppId(pkgName, appId, reason);
6712            } catch (RemoteException e) {
6713            }
6714        }
6715    }
6716
6717    void removePackageLI(PackageSetting ps, boolean chatty) {
6718        if (DEBUG_INSTALL) {
6719            if (chatty)
6720                Log.d(TAG, "Removing package " + ps.name);
6721        }
6722
6723        // writer
6724        synchronized (mPackages) {
6725            mPackages.remove(ps.name);
6726            final PackageParser.Package pkg = ps.pkg;
6727            if (pkg != null) {
6728                cleanPackageDataStructuresLILPw(pkg, chatty);
6729            }
6730        }
6731    }
6732
6733    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6734        if (DEBUG_INSTALL) {
6735            if (chatty)
6736                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6737        }
6738
6739        // writer
6740        synchronized (mPackages) {
6741            mPackages.remove(pkg.applicationInfo.packageName);
6742            cleanPackageDataStructuresLILPw(pkg, chatty);
6743        }
6744    }
6745
6746    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6747        int N = pkg.providers.size();
6748        StringBuilder r = null;
6749        int i;
6750        for (i=0; i<N; i++) {
6751            PackageParser.Provider p = pkg.providers.get(i);
6752            mProviders.removeProvider(p);
6753            if (p.info.authority == null) {
6754
6755                /* There was another ContentProvider with this authority when
6756                 * this app was installed so this authority is null,
6757                 * Ignore it as we don't have to unregister the provider.
6758                 */
6759                continue;
6760            }
6761            String names[] = p.info.authority.split(";");
6762            for (int j = 0; j < names.length; j++) {
6763                if (mProvidersByAuthority.get(names[j]) == p) {
6764                    mProvidersByAuthority.remove(names[j]);
6765                    if (DEBUG_REMOVE) {
6766                        if (chatty)
6767                            Log.d(TAG, "Unregistered content provider: " + names[j]
6768                                    + ", className = " + p.info.name + ", isSyncable = "
6769                                    + p.info.isSyncable);
6770                    }
6771                }
6772            }
6773            if (DEBUG_REMOVE && chatty) {
6774                if (r == null) {
6775                    r = new StringBuilder(256);
6776                } else {
6777                    r.append(' ');
6778                }
6779                r.append(p.info.name);
6780            }
6781        }
6782        if (r != null) {
6783            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6784        }
6785
6786        N = pkg.services.size();
6787        r = null;
6788        for (i=0; i<N; i++) {
6789            PackageParser.Service s = pkg.services.get(i);
6790            mServices.removeService(s);
6791            if (chatty) {
6792                if (r == null) {
6793                    r = new StringBuilder(256);
6794                } else {
6795                    r.append(' ');
6796                }
6797                r.append(s.info.name);
6798            }
6799        }
6800        if (r != null) {
6801            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6802        }
6803
6804        N = pkg.receivers.size();
6805        r = null;
6806        for (i=0; i<N; i++) {
6807            PackageParser.Activity a = pkg.receivers.get(i);
6808            mReceivers.removeActivity(a, "receiver");
6809            if (DEBUG_REMOVE && chatty) {
6810                if (r == null) {
6811                    r = new StringBuilder(256);
6812                } else {
6813                    r.append(' ');
6814                }
6815                r.append(a.info.name);
6816            }
6817        }
6818        if (r != null) {
6819            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6820        }
6821
6822        N = pkg.activities.size();
6823        r = null;
6824        for (i=0; i<N; i++) {
6825            PackageParser.Activity a = pkg.activities.get(i);
6826            mActivities.removeActivity(a, "activity");
6827            if (DEBUG_REMOVE && chatty) {
6828                if (r == null) {
6829                    r = new StringBuilder(256);
6830                } else {
6831                    r.append(' ');
6832                }
6833                r.append(a.info.name);
6834            }
6835        }
6836        if (r != null) {
6837            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6838        }
6839
6840        N = pkg.permissions.size();
6841        r = null;
6842        for (i=0; i<N; i++) {
6843            PackageParser.Permission p = pkg.permissions.get(i);
6844            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6845            if (bp == null) {
6846                bp = mSettings.mPermissionTrees.get(p.info.name);
6847            }
6848            if (bp != null && bp.perm == p) {
6849                bp.perm = null;
6850                if (DEBUG_REMOVE && chatty) {
6851                    if (r == null) {
6852                        r = new StringBuilder(256);
6853                    } else {
6854                        r.append(' ');
6855                    }
6856                    r.append(p.info.name);
6857                }
6858            }
6859            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6860                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6861                if (appOpPerms != null) {
6862                    appOpPerms.remove(pkg.packageName);
6863                }
6864            }
6865        }
6866        if (r != null) {
6867            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6868        }
6869
6870        N = pkg.requestedPermissions.size();
6871        r = null;
6872        for (i=0; i<N; i++) {
6873            String perm = pkg.requestedPermissions.get(i);
6874            BasePermission bp = mSettings.mPermissions.get(perm);
6875            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6876                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6877                if (appOpPerms != null) {
6878                    appOpPerms.remove(pkg.packageName);
6879                    if (appOpPerms.isEmpty()) {
6880                        mAppOpPermissionPackages.remove(perm);
6881                    }
6882                }
6883            }
6884        }
6885        if (r != null) {
6886            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6887        }
6888
6889        N = pkg.instrumentation.size();
6890        r = null;
6891        for (i=0; i<N; i++) {
6892            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6893            mInstrumentation.remove(a.getComponentName());
6894            if (DEBUG_REMOVE && chatty) {
6895                if (r == null) {
6896                    r = new StringBuilder(256);
6897                } else {
6898                    r.append(' ');
6899                }
6900                r.append(a.info.name);
6901            }
6902        }
6903        if (r != null) {
6904            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6905        }
6906
6907        r = null;
6908        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6909            // Only system apps can hold shared libraries.
6910            if (pkg.libraryNames != null) {
6911                for (i=0; i<pkg.libraryNames.size(); i++) {
6912                    String name = pkg.libraryNames.get(i);
6913                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6914                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6915                        mSharedLibraries.remove(name);
6916                        if (DEBUG_REMOVE && chatty) {
6917                            if (r == null) {
6918                                r = new StringBuilder(256);
6919                            } else {
6920                                r.append(' ');
6921                            }
6922                            r.append(name);
6923                        }
6924                    }
6925                }
6926            }
6927        }
6928        if (r != null) {
6929            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6930        }
6931    }
6932
6933    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6934        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6935            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6936                return true;
6937            }
6938        }
6939        return false;
6940    }
6941
6942    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6943    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6944    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6945
6946    private void updatePermissionsLPw(String changingPkg,
6947            PackageParser.Package pkgInfo, int flags) {
6948        // Make sure there are no dangling permission trees.
6949        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6950        while (it.hasNext()) {
6951            final BasePermission bp = it.next();
6952            if (bp.packageSetting == null) {
6953                // We may not yet have parsed the package, so just see if
6954                // we still know about its settings.
6955                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6956            }
6957            if (bp.packageSetting == null) {
6958                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6959                        + " from package " + bp.sourcePackage);
6960                it.remove();
6961            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6962                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6963                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6964                            + " from package " + bp.sourcePackage);
6965                    flags |= UPDATE_PERMISSIONS_ALL;
6966                    it.remove();
6967                }
6968            }
6969        }
6970
6971        // Make sure all dynamic permissions have been assigned to a package,
6972        // and make sure there are no dangling permissions.
6973        it = mSettings.mPermissions.values().iterator();
6974        while (it.hasNext()) {
6975            final BasePermission bp = it.next();
6976            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6977                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6978                        + bp.name + " pkg=" + bp.sourcePackage
6979                        + " info=" + bp.pendingInfo);
6980                if (bp.packageSetting == null && bp.pendingInfo != null) {
6981                    final BasePermission tree = findPermissionTreeLP(bp.name);
6982                    if (tree != null && tree.perm != null) {
6983                        bp.packageSetting = tree.packageSetting;
6984                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6985                                new PermissionInfo(bp.pendingInfo));
6986                        bp.perm.info.packageName = tree.perm.info.packageName;
6987                        bp.perm.info.name = bp.name;
6988                        bp.uid = tree.uid;
6989                    }
6990                }
6991            }
6992            if (bp.packageSetting == null) {
6993                // We may not yet have parsed the package, so just see if
6994                // we still know about its settings.
6995                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6996            }
6997            if (bp.packageSetting == null) {
6998                Slog.w(TAG, "Removing dangling permission: " + bp.name
6999                        + " from package " + bp.sourcePackage);
7000                it.remove();
7001            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7002                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7003                    Slog.i(TAG, "Removing old permission: " + bp.name
7004                            + " from package " + bp.sourcePackage);
7005                    flags |= UPDATE_PERMISSIONS_ALL;
7006                    it.remove();
7007                }
7008            }
7009        }
7010
7011        // Now update the permissions for all packages, in particular
7012        // replace the granted permissions of the system packages.
7013        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7014            for (PackageParser.Package pkg : mPackages.values()) {
7015                if (pkg != pkgInfo) {
7016                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7017                            changingPkg);
7018                }
7019            }
7020        }
7021
7022        if (pkgInfo != null) {
7023            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7024        }
7025    }
7026
7027    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7028            String packageOfInterest) {
7029        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7030        if (ps == null) {
7031            return;
7032        }
7033        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
7034        ArraySet<String> origPermissions = gp.grantedPermissions;
7035        boolean changedPermission = false;
7036
7037        if (replace) {
7038            ps.permissionsFixed = false;
7039            if (gp == ps) {
7040                origPermissions = new ArraySet<String>(gp.grantedPermissions);
7041                gp.grantedPermissions.clear();
7042                gp.gids = mGlobalGids;
7043            }
7044        }
7045
7046        if (gp.gids == null) {
7047            gp.gids = mGlobalGids;
7048        }
7049
7050        final int N = pkg.requestedPermissions.size();
7051        for (int i=0; i<N; i++) {
7052            final String name = pkg.requestedPermissions.get(i);
7053            final boolean required = pkg.requestedPermissionsRequired.get(i);
7054            final BasePermission bp = mSettings.mPermissions.get(name);
7055            if (DEBUG_INSTALL) {
7056                if (gp != ps) {
7057                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7058                }
7059            }
7060
7061            if (bp == null || bp.packageSetting == null) {
7062                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7063                    Slog.w(TAG, "Unknown permission " + name
7064                            + " in package " + pkg.packageName);
7065                }
7066                continue;
7067            }
7068
7069            final String perm = bp.name;
7070            boolean allowed;
7071            boolean allowedSig = false;
7072            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7073                // Keep track of app op permissions.
7074                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7075                if (pkgs == null) {
7076                    pkgs = new ArraySet<>();
7077                    mAppOpPermissionPackages.put(bp.name, pkgs);
7078                }
7079                pkgs.add(pkg.packageName);
7080            }
7081            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7082            if (level == PermissionInfo.PROTECTION_NORMAL
7083                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
7084                // We grant a normal or dangerous permission if any of the following
7085                // are true:
7086                // 1) The permission is required
7087                // 2) The permission is optional, but was granted in the past
7088                // 3) The permission is optional, but was requested by an
7089                //    app in /system (not /data)
7090                //
7091                // Otherwise, reject the permission.
7092                allowed = (required || origPermissions.contains(perm)
7093                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
7094            } else if (bp.packageSetting == null) {
7095                // This permission is invalid; skip it.
7096                allowed = false;
7097            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
7098                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
7099                if (allowed) {
7100                    allowedSig = true;
7101                }
7102            } else {
7103                allowed = false;
7104            }
7105            if (DEBUG_INSTALL) {
7106                if (gp != ps) {
7107                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7108                }
7109            }
7110            if (allowed) {
7111                if (!isSystemApp(ps) && ps.permissionsFixed) {
7112                    // If this is an existing, non-system package, then
7113                    // we can't add any new permissions to it.
7114                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
7115                        // Except...  if this is a permission that was added
7116                        // to the platform (note: need to only do this when
7117                        // updating the platform).
7118                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
7119                    }
7120                }
7121                if (allowed) {
7122                    if (!gp.grantedPermissions.contains(perm)) {
7123                        changedPermission = true;
7124                        gp.grantedPermissions.add(perm);
7125                        gp.gids = appendInts(gp.gids, bp.gids);
7126                    } else if (!ps.haveGids) {
7127                        gp.gids = appendInts(gp.gids, bp.gids);
7128                    }
7129                } else {
7130                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7131                        Slog.w(TAG, "Not granting permission " + perm
7132                                + " to package " + pkg.packageName
7133                                + " because it was previously installed without");
7134                    }
7135                }
7136            } else {
7137                if (gp.grantedPermissions.remove(perm)) {
7138                    changedPermission = true;
7139                    gp.gids = removeInts(gp.gids, bp.gids);
7140                    Slog.i(TAG, "Un-granting permission " + perm
7141                            + " from package " + pkg.packageName
7142                            + " (protectionLevel=" + bp.protectionLevel
7143                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7144                            + ")");
7145                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7146                    // Don't print warning for app op permissions, since it is fine for them
7147                    // not to be granted, there is a UI for the user to decide.
7148                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7149                        Slog.w(TAG, "Not granting permission " + perm
7150                                + " to package " + pkg.packageName
7151                                + " (protectionLevel=" + bp.protectionLevel
7152                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7153                                + ")");
7154                    }
7155                }
7156            }
7157        }
7158
7159        if ((changedPermission || replace) && !ps.permissionsFixed &&
7160                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7161            // This is the first that we have heard about this package, so the
7162            // permissions we have now selected are fixed until explicitly
7163            // changed.
7164            ps.permissionsFixed = true;
7165        }
7166        ps.haveGids = true;
7167    }
7168
7169    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7170        boolean allowed = false;
7171        final int NP = PackageParser.NEW_PERMISSIONS.length;
7172        for (int ip=0; ip<NP; ip++) {
7173            final PackageParser.NewPermissionInfo npi
7174                    = PackageParser.NEW_PERMISSIONS[ip];
7175            if (npi.name.equals(perm)
7176                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7177                allowed = true;
7178                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7179                        + pkg.packageName);
7180                break;
7181            }
7182        }
7183        return allowed;
7184    }
7185
7186    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7187                                          BasePermission bp, ArraySet<String> origPermissions) {
7188        boolean allowed;
7189        allowed = (compareSignatures(
7190                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7191                        == PackageManager.SIGNATURE_MATCH)
7192                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7193                        == PackageManager.SIGNATURE_MATCH);
7194        if (!allowed && (bp.protectionLevel
7195                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7196            if (isSystemApp(pkg)) {
7197                // For updated system applications, a system permission
7198                // is granted only if it had been defined by the original application.
7199                if (isUpdatedSystemApp(pkg)) {
7200                    final PackageSetting sysPs = mSettings
7201                            .getDisabledSystemPkgLPr(pkg.packageName);
7202                    final GrantedPermissions origGp = sysPs.sharedUser != null
7203                            ? sysPs.sharedUser : sysPs;
7204
7205                    if (origGp.grantedPermissions.contains(perm)) {
7206                        // If the original was granted this permission, we take
7207                        // that grant decision as read and propagate it to the
7208                        // update.
7209                        if (sysPs.isPrivileged()) {
7210                            allowed = true;
7211                        }
7212                    } else {
7213                        // The system apk may have been updated with an older
7214                        // version of the one on the data partition, but which
7215                        // granted a new system permission that it didn't have
7216                        // before.  In this case we do want to allow the app to
7217                        // now get the new permission if the ancestral apk is
7218                        // privileged to get it.
7219                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7220                            for (int j=0;
7221                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7222                                if (perm.equals(
7223                                        sysPs.pkg.requestedPermissions.get(j))) {
7224                                    allowed = true;
7225                                    break;
7226                                }
7227                            }
7228                        }
7229                    }
7230                } else {
7231                    allowed = isPrivilegedApp(pkg);
7232                }
7233            }
7234        }
7235        if (!allowed && (bp.protectionLevel
7236                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7237            // For development permissions, a development permission
7238            // is granted only if it was already granted.
7239            allowed = origPermissions.contains(perm);
7240        }
7241        return allowed;
7242    }
7243
7244    final class ActivityIntentResolver
7245            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7246        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7247                boolean defaultOnly, int userId) {
7248            if (!sUserManager.exists(userId)) return null;
7249            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7250            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7251        }
7252
7253        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7254                int userId) {
7255            if (!sUserManager.exists(userId)) return null;
7256            mFlags = flags;
7257            return super.queryIntent(intent, resolvedType,
7258                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7259        }
7260
7261        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7262                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7263            if (!sUserManager.exists(userId)) return null;
7264            if (packageActivities == null) {
7265                return null;
7266            }
7267            mFlags = flags;
7268            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7269            final int N = packageActivities.size();
7270            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7271                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7272
7273            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7274            for (int i = 0; i < N; ++i) {
7275                intentFilters = packageActivities.get(i).intents;
7276                if (intentFilters != null && intentFilters.size() > 0) {
7277                    PackageParser.ActivityIntentInfo[] array =
7278                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7279                    intentFilters.toArray(array);
7280                    listCut.add(array);
7281                }
7282            }
7283            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7284        }
7285
7286        public final void addActivity(PackageParser.Activity a, String type) {
7287            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7288            mActivities.put(a.getComponentName(), a);
7289            if (DEBUG_SHOW_INFO)
7290                Log.v(
7291                TAG, "  " + type + " " +
7292                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7293            if (DEBUG_SHOW_INFO)
7294                Log.v(TAG, "    Class=" + a.info.name);
7295            final int NI = a.intents.size();
7296            for (int j=0; j<NI; j++) {
7297                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7298                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7299                    intent.setPriority(0);
7300                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7301                            + a.className + " with priority > 0, forcing to 0");
7302                }
7303                if (DEBUG_SHOW_INFO) {
7304                    Log.v(TAG, "    IntentFilter:");
7305                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7306                }
7307                if (!intent.debugCheck()) {
7308                    Log.w(TAG, "==> For Activity " + a.info.name);
7309                }
7310                addFilter(intent);
7311            }
7312        }
7313
7314        public final void removeActivity(PackageParser.Activity a, String type) {
7315            mActivities.remove(a.getComponentName());
7316            if (DEBUG_SHOW_INFO) {
7317                Log.v(TAG, "  " + type + " "
7318                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7319                                : a.info.name) + ":");
7320                Log.v(TAG, "    Class=" + a.info.name);
7321            }
7322            final int NI = a.intents.size();
7323            for (int j=0; j<NI; j++) {
7324                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7325                if (DEBUG_SHOW_INFO) {
7326                    Log.v(TAG, "    IntentFilter:");
7327                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7328                }
7329                removeFilter(intent);
7330            }
7331        }
7332
7333        @Override
7334        protected boolean allowFilterResult(
7335                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7336            ActivityInfo filterAi = filter.activity.info;
7337            for (int i=dest.size()-1; i>=0; i--) {
7338                ActivityInfo destAi = dest.get(i).activityInfo;
7339                if (destAi.name == filterAi.name
7340                        && destAi.packageName == filterAi.packageName) {
7341                    return false;
7342                }
7343            }
7344            return true;
7345        }
7346
7347        @Override
7348        protected ActivityIntentInfo[] newArray(int size) {
7349            return new ActivityIntentInfo[size];
7350        }
7351
7352        @Override
7353        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7354            if (!sUserManager.exists(userId)) return true;
7355            PackageParser.Package p = filter.activity.owner;
7356            if (p != null) {
7357                PackageSetting ps = (PackageSetting)p.mExtras;
7358                if (ps != null) {
7359                    // System apps are never considered stopped for purposes of
7360                    // filtering, because there may be no way for the user to
7361                    // actually re-launch them.
7362                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7363                            && ps.getStopped(userId);
7364                }
7365            }
7366            return false;
7367        }
7368
7369        @Override
7370        protected boolean isPackageForFilter(String packageName,
7371                PackageParser.ActivityIntentInfo info) {
7372            return packageName.equals(info.activity.owner.packageName);
7373        }
7374
7375        @Override
7376        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7377                int match, int userId) {
7378            if (!sUserManager.exists(userId)) return null;
7379            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7380                return null;
7381            }
7382            final PackageParser.Activity activity = info.activity;
7383            if (mSafeMode && (activity.info.applicationInfo.flags
7384                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7385                return null;
7386            }
7387            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7388            if (ps == null) {
7389                return null;
7390            }
7391            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7392                    ps.readUserState(userId), userId);
7393            if (ai == null) {
7394                return null;
7395            }
7396            final ResolveInfo res = new ResolveInfo();
7397            res.activityInfo = ai;
7398            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7399                res.filter = info;
7400            }
7401            res.priority = info.getPriority();
7402            res.preferredOrder = activity.owner.mPreferredOrder;
7403            //System.out.println("Result: " + res.activityInfo.className +
7404            //                   " = " + res.priority);
7405            res.match = match;
7406            res.isDefault = info.hasDefault;
7407            res.labelRes = info.labelRes;
7408            res.nonLocalizedLabel = info.nonLocalizedLabel;
7409            if (userNeedsBadging(userId)) {
7410                res.noResourceId = true;
7411            } else {
7412                res.icon = info.icon;
7413            }
7414            res.system = isSystemApp(res.activityInfo.applicationInfo);
7415            return res;
7416        }
7417
7418        @Override
7419        protected void sortResults(List<ResolveInfo> results) {
7420            Collections.sort(results, mResolvePrioritySorter);
7421        }
7422
7423        @Override
7424        protected void dumpFilter(PrintWriter out, String prefix,
7425                PackageParser.ActivityIntentInfo filter) {
7426            out.print(prefix); out.print(
7427                    Integer.toHexString(System.identityHashCode(filter.activity)));
7428                    out.print(' ');
7429                    filter.activity.printComponentShortName(out);
7430                    out.print(" filter ");
7431                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7432        }
7433
7434        @Override
7435        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7436            return filter.activity;
7437        }
7438
7439        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7440            PackageParser.Activity activity = (PackageParser.Activity)label;
7441            out.print(prefix); out.print(
7442                    Integer.toHexString(System.identityHashCode(activity)));
7443                    out.print(' ');
7444                    activity.printComponentShortName(out);
7445            if (count > 1) {
7446                out.print(" ("); out.print(count); out.print(" filters)");
7447            }
7448            out.println();
7449        }
7450
7451//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7452//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7453//            final List<ResolveInfo> retList = Lists.newArrayList();
7454//            while (i.hasNext()) {
7455//                final ResolveInfo resolveInfo = i.next();
7456//                if (isEnabledLP(resolveInfo.activityInfo)) {
7457//                    retList.add(resolveInfo);
7458//                }
7459//            }
7460//            return retList;
7461//        }
7462
7463        // Keys are String (activity class name), values are Activity.
7464        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
7465                = new ArrayMap<ComponentName, PackageParser.Activity>();
7466        private int mFlags;
7467    }
7468
7469    private final class ServiceIntentResolver
7470            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7471        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7472                boolean defaultOnly, int userId) {
7473            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7474            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7475        }
7476
7477        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7478                int userId) {
7479            if (!sUserManager.exists(userId)) return null;
7480            mFlags = flags;
7481            return super.queryIntent(intent, resolvedType,
7482                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7483        }
7484
7485        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7486                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7487            if (!sUserManager.exists(userId)) return null;
7488            if (packageServices == null) {
7489                return null;
7490            }
7491            mFlags = flags;
7492            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7493            final int N = packageServices.size();
7494            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7495                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7496
7497            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7498            for (int i = 0; i < N; ++i) {
7499                intentFilters = packageServices.get(i).intents;
7500                if (intentFilters != null && intentFilters.size() > 0) {
7501                    PackageParser.ServiceIntentInfo[] array =
7502                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7503                    intentFilters.toArray(array);
7504                    listCut.add(array);
7505                }
7506            }
7507            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7508        }
7509
7510        public final void addService(PackageParser.Service s) {
7511            mServices.put(s.getComponentName(), s);
7512            if (DEBUG_SHOW_INFO) {
7513                Log.v(TAG, "  "
7514                        + (s.info.nonLocalizedLabel != null
7515                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7516                Log.v(TAG, "    Class=" + s.info.name);
7517            }
7518            final int NI = s.intents.size();
7519            int j;
7520            for (j=0; j<NI; j++) {
7521                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7522                if (DEBUG_SHOW_INFO) {
7523                    Log.v(TAG, "    IntentFilter:");
7524                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7525                }
7526                if (!intent.debugCheck()) {
7527                    Log.w(TAG, "==> For Service " + s.info.name);
7528                }
7529                addFilter(intent);
7530            }
7531        }
7532
7533        public final void removeService(PackageParser.Service s) {
7534            mServices.remove(s.getComponentName());
7535            if (DEBUG_SHOW_INFO) {
7536                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7537                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7538                Log.v(TAG, "    Class=" + s.info.name);
7539            }
7540            final int NI = s.intents.size();
7541            int j;
7542            for (j=0; j<NI; j++) {
7543                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7544                if (DEBUG_SHOW_INFO) {
7545                    Log.v(TAG, "    IntentFilter:");
7546                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7547                }
7548                removeFilter(intent);
7549            }
7550        }
7551
7552        @Override
7553        protected boolean allowFilterResult(
7554                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7555            ServiceInfo filterSi = filter.service.info;
7556            for (int i=dest.size()-1; i>=0; i--) {
7557                ServiceInfo destAi = dest.get(i).serviceInfo;
7558                if (destAi.name == filterSi.name
7559                        && destAi.packageName == filterSi.packageName) {
7560                    return false;
7561                }
7562            }
7563            return true;
7564        }
7565
7566        @Override
7567        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7568            return new PackageParser.ServiceIntentInfo[size];
7569        }
7570
7571        @Override
7572        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7573            if (!sUserManager.exists(userId)) return true;
7574            PackageParser.Package p = filter.service.owner;
7575            if (p != null) {
7576                PackageSetting ps = (PackageSetting)p.mExtras;
7577                if (ps != null) {
7578                    // System apps are never considered stopped for purposes of
7579                    // filtering, because there may be no way for the user to
7580                    // actually re-launch them.
7581                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7582                            && ps.getStopped(userId);
7583                }
7584            }
7585            return false;
7586        }
7587
7588        @Override
7589        protected boolean isPackageForFilter(String packageName,
7590                PackageParser.ServiceIntentInfo info) {
7591            return packageName.equals(info.service.owner.packageName);
7592        }
7593
7594        @Override
7595        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7596                int match, int userId) {
7597            if (!sUserManager.exists(userId)) return null;
7598            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7599            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7600                return null;
7601            }
7602            final PackageParser.Service service = info.service;
7603            if (mSafeMode && (service.info.applicationInfo.flags
7604                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7605                return null;
7606            }
7607            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7608            if (ps == null) {
7609                return null;
7610            }
7611            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7612                    ps.readUserState(userId), userId);
7613            if (si == null) {
7614                return null;
7615            }
7616            final ResolveInfo res = new ResolveInfo();
7617            res.serviceInfo = si;
7618            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7619                res.filter = filter;
7620            }
7621            res.priority = info.getPriority();
7622            res.preferredOrder = service.owner.mPreferredOrder;
7623            //System.out.println("Result: " + res.activityInfo.className +
7624            //                   " = " + res.priority);
7625            res.match = match;
7626            res.isDefault = info.hasDefault;
7627            res.labelRes = info.labelRes;
7628            res.nonLocalizedLabel = info.nonLocalizedLabel;
7629            res.icon = info.icon;
7630            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7631            return res;
7632        }
7633
7634        @Override
7635        protected void sortResults(List<ResolveInfo> results) {
7636            Collections.sort(results, mResolvePrioritySorter);
7637        }
7638
7639        @Override
7640        protected void dumpFilter(PrintWriter out, String prefix,
7641                PackageParser.ServiceIntentInfo filter) {
7642            out.print(prefix); out.print(
7643                    Integer.toHexString(System.identityHashCode(filter.service)));
7644                    out.print(' ');
7645                    filter.service.printComponentShortName(out);
7646                    out.print(" filter ");
7647                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7648        }
7649
7650        @Override
7651        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
7652            return filter.service;
7653        }
7654
7655        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7656            PackageParser.Service service = (PackageParser.Service)label;
7657            out.print(prefix); out.print(
7658                    Integer.toHexString(System.identityHashCode(service)));
7659                    out.print(' ');
7660                    service.printComponentShortName(out);
7661            if (count > 1) {
7662                out.print(" ("); out.print(count); out.print(" filters)");
7663            }
7664            out.println();
7665        }
7666
7667//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7668//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7669//            final List<ResolveInfo> retList = Lists.newArrayList();
7670//            while (i.hasNext()) {
7671//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7672//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7673//                    retList.add(resolveInfo);
7674//                }
7675//            }
7676//            return retList;
7677//        }
7678
7679        // Keys are String (activity class name), values are Activity.
7680        private final ArrayMap<ComponentName, PackageParser.Service> mServices
7681                = new ArrayMap<ComponentName, PackageParser.Service>();
7682        private int mFlags;
7683    };
7684
7685    private final class ProviderIntentResolver
7686            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7687        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7688                boolean defaultOnly, int userId) {
7689            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7690            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7691        }
7692
7693        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7694                int userId) {
7695            if (!sUserManager.exists(userId))
7696                return null;
7697            mFlags = flags;
7698            return super.queryIntent(intent, resolvedType,
7699                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7700        }
7701
7702        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7703                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7704            if (!sUserManager.exists(userId))
7705                return null;
7706            if (packageProviders == null) {
7707                return null;
7708            }
7709            mFlags = flags;
7710            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7711            final int N = packageProviders.size();
7712            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7713                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7714
7715            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7716            for (int i = 0; i < N; ++i) {
7717                intentFilters = packageProviders.get(i).intents;
7718                if (intentFilters != null && intentFilters.size() > 0) {
7719                    PackageParser.ProviderIntentInfo[] array =
7720                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7721                    intentFilters.toArray(array);
7722                    listCut.add(array);
7723                }
7724            }
7725            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7726        }
7727
7728        public final void addProvider(PackageParser.Provider p) {
7729            if (mProviders.containsKey(p.getComponentName())) {
7730                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7731                return;
7732            }
7733
7734            mProviders.put(p.getComponentName(), p);
7735            if (DEBUG_SHOW_INFO) {
7736                Log.v(TAG, "  "
7737                        + (p.info.nonLocalizedLabel != null
7738                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7739                Log.v(TAG, "    Class=" + p.info.name);
7740            }
7741            final int NI = p.intents.size();
7742            int j;
7743            for (j = 0; j < NI; j++) {
7744                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7745                if (DEBUG_SHOW_INFO) {
7746                    Log.v(TAG, "    IntentFilter:");
7747                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7748                }
7749                if (!intent.debugCheck()) {
7750                    Log.w(TAG, "==> For Provider " + p.info.name);
7751                }
7752                addFilter(intent);
7753            }
7754        }
7755
7756        public final void removeProvider(PackageParser.Provider p) {
7757            mProviders.remove(p.getComponentName());
7758            if (DEBUG_SHOW_INFO) {
7759                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7760                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7761                Log.v(TAG, "    Class=" + p.info.name);
7762            }
7763            final int NI = p.intents.size();
7764            int j;
7765            for (j = 0; j < NI; j++) {
7766                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7767                if (DEBUG_SHOW_INFO) {
7768                    Log.v(TAG, "    IntentFilter:");
7769                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7770                }
7771                removeFilter(intent);
7772            }
7773        }
7774
7775        @Override
7776        protected boolean allowFilterResult(
7777                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7778            ProviderInfo filterPi = filter.provider.info;
7779            for (int i = dest.size() - 1; i >= 0; i--) {
7780                ProviderInfo destPi = dest.get(i).providerInfo;
7781                if (destPi.name == filterPi.name
7782                        && destPi.packageName == filterPi.packageName) {
7783                    return false;
7784                }
7785            }
7786            return true;
7787        }
7788
7789        @Override
7790        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7791            return new PackageParser.ProviderIntentInfo[size];
7792        }
7793
7794        @Override
7795        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7796            if (!sUserManager.exists(userId))
7797                return true;
7798            PackageParser.Package p = filter.provider.owner;
7799            if (p != null) {
7800                PackageSetting ps = (PackageSetting) p.mExtras;
7801                if (ps != null) {
7802                    // System apps are never considered stopped for purposes of
7803                    // filtering, because there may be no way for the user to
7804                    // actually re-launch them.
7805                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7806                            && ps.getStopped(userId);
7807                }
7808            }
7809            return false;
7810        }
7811
7812        @Override
7813        protected boolean isPackageForFilter(String packageName,
7814                PackageParser.ProviderIntentInfo info) {
7815            return packageName.equals(info.provider.owner.packageName);
7816        }
7817
7818        @Override
7819        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7820                int match, int userId) {
7821            if (!sUserManager.exists(userId))
7822                return null;
7823            final PackageParser.ProviderIntentInfo info = filter;
7824            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7825                return null;
7826            }
7827            final PackageParser.Provider provider = info.provider;
7828            if (mSafeMode && (provider.info.applicationInfo.flags
7829                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7830                return null;
7831            }
7832            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7833            if (ps == null) {
7834                return null;
7835            }
7836            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7837                    ps.readUserState(userId), userId);
7838            if (pi == null) {
7839                return null;
7840            }
7841            final ResolveInfo res = new ResolveInfo();
7842            res.providerInfo = pi;
7843            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7844                res.filter = filter;
7845            }
7846            res.priority = info.getPriority();
7847            res.preferredOrder = provider.owner.mPreferredOrder;
7848            res.match = match;
7849            res.isDefault = info.hasDefault;
7850            res.labelRes = info.labelRes;
7851            res.nonLocalizedLabel = info.nonLocalizedLabel;
7852            res.icon = info.icon;
7853            res.system = isSystemApp(res.providerInfo.applicationInfo);
7854            return res;
7855        }
7856
7857        @Override
7858        protected void sortResults(List<ResolveInfo> results) {
7859            Collections.sort(results, mResolvePrioritySorter);
7860        }
7861
7862        @Override
7863        protected void dumpFilter(PrintWriter out, String prefix,
7864                PackageParser.ProviderIntentInfo filter) {
7865            out.print(prefix);
7866            out.print(
7867                    Integer.toHexString(System.identityHashCode(filter.provider)));
7868            out.print(' ');
7869            filter.provider.printComponentShortName(out);
7870            out.print(" filter ");
7871            out.println(Integer.toHexString(System.identityHashCode(filter)));
7872        }
7873
7874        @Override
7875        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
7876            return filter.provider;
7877        }
7878
7879        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7880            PackageParser.Provider provider = (PackageParser.Provider)label;
7881            out.print(prefix); out.print(
7882                    Integer.toHexString(System.identityHashCode(provider)));
7883                    out.print(' ');
7884                    provider.printComponentShortName(out);
7885            if (count > 1) {
7886                out.print(" ("); out.print(count); out.print(" filters)");
7887            }
7888            out.println();
7889        }
7890
7891        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
7892                = new ArrayMap<ComponentName, PackageParser.Provider>();
7893        private int mFlags;
7894    };
7895
7896    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7897            new Comparator<ResolveInfo>() {
7898        public int compare(ResolveInfo r1, ResolveInfo r2) {
7899            int v1 = r1.priority;
7900            int v2 = r2.priority;
7901            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7902            if (v1 != v2) {
7903                return (v1 > v2) ? -1 : 1;
7904            }
7905            v1 = r1.preferredOrder;
7906            v2 = r2.preferredOrder;
7907            if (v1 != v2) {
7908                return (v1 > v2) ? -1 : 1;
7909            }
7910            if (r1.isDefault != r2.isDefault) {
7911                return r1.isDefault ? -1 : 1;
7912            }
7913            v1 = r1.match;
7914            v2 = r2.match;
7915            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7916            if (v1 != v2) {
7917                return (v1 > v2) ? -1 : 1;
7918            }
7919            if (r1.system != r2.system) {
7920                return r1.system ? -1 : 1;
7921            }
7922            return 0;
7923        }
7924    };
7925
7926    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7927            new Comparator<ProviderInfo>() {
7928        public int compare(ProviderInfo p1, ProviderInfo p2) {
7929            final int v1 = p1.initOrder;
7930            final int v2 = p2.initOrder;
7931            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7932        }
7933    };
7934
7935    static final void sendPackageBroadcast(String action, String pkg,
7936            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7937            int[] userIds) {
7938        IActivityManager am = ActivityManagerNative.getDefault();
7939        if (am != null) {
7940            try {
7941                if (userIds == null) {
7942                    userIds = am.getRunningUserIds();
7943                }
7944                for (int id : userIds) {
7945                    final Intent intent = new Intent(action,
7946                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7947                    if (extras != null) {
7948                        intent.putExtras(extras);
7949                    }
7950                    if (targetPkg != null) {
7951                        intent.setPackage(targetPkg);
7952                    }
7953                    // Modify the UID when posting to other users
7954                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7955                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7956                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7957                        intent.putExtra(Intent.EXTRA_UID, uid);
7958                    }
7959                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7960                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7961                    if (DEBUG_BROADCASTS) {
7962                        RuntimeException here = new RuntimeException("here");
7963                        here.fillInStackTrace();
7964                        Slog.d(TAG, "Sending to user " + id + ": "
7965                                + intent.toShortString(false, true, false, false)
7966                                + " " + intent.getExtras(), here);
7967                    }
7968                    am.broadcastIntent(null, intent, null, finishedReceiver,
7969                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7970                            finishedReceiver != null, false, id);
7971                }
7972            } catch (RemoteException ex) {
7973            }
7974        }
7975    }
7976
7977    /**
7978     * Check if the external storage media is available. This is true if there
7979     * is a mounted external storage medium or if the external storage is
7980     * emulated.
7981     */
7982    private boolean isExternalMediaAvailable() {
7983        return mMediaMounted || Environment.isExternalStorageEmulated();
7984    }
7985
7986    @Override
7987    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7988        // writer
7989        synchronized (mPackages) {
7990            if (!isExternalMediaAvailable()) {
7991                // If the external storage is no longer mounted at this point,
7992                // the caller may not have been able to delete all of this
7993                // packages files and can not delete any more.  Bail.
7994                return null;
7995            }
7996            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7997            if (lastPackage != null) {
7998                pkgs.remove(lastPackage);
7999            }
8000            if (pkgs.size() > 0) {
8001                return pkgs.get(0);
8002            }
8003        }
8004        return null;
8005    }
8006
8007    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8008        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8009                userId, andCode ? 1 : 0, packageName);
8010        if (mSystemReady) {
8011            msg.sendToTarget();
8012        } else {
8013            if (mPostSystemReadyMessages == null) {
8014                mPostSystemReadyMessages = new ArrayList<>();
8015            }
8016            mPostSystemReadyMessages.add(msg);
8017        }
8018    }
8019
8020    void startCleaningPackages() {
8021        // reader
8022        synchronized (mPackages) {
8023            if (!isExternalMediaAvailable()) {
8024                return;
8025            }
8026            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8027                return;
8028            }
8029        }
8030        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8031        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8032        IActivityManager am = ActivityManagerNative.getDefault();
8033        if (am != null) {
8034            try {
8035                am.startService(null, intent, null, UserHandle.USER_OWNER);
8036            } catch (RemoteException e) {
8037            }
8038        }
8039    }
8040
8041    @Override
8042    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8043            int installFlags, String installerPackageName, VerificationParams verificationParams,
8044            String packageAbiOverride) {
8045        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
8046                packageAbiOverride, UserHandle.getCallingUserId());
8047    }
8048
8049    @Override
8050    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8051            int installFlags, String installerPackageName, VerificationParams verificationParams,
8052            String packageAbiOverride, int userId) {
8053        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8054
8055        final int callingUid = Binder.getCallingUid();
8056        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8057
8058        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8059            try {
8060                if (observer != null) {
8061                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8062                }
8063            } catch (RemoteException re) {
8064            }
8065            return;
8066        }
8067
8068        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8069            installFlags |= PackageManager.INSTALL_FROM_ADB;
8070
8071        } else {
8072            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8073            // about installerPackageName.
8074
8075            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8076            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8077        }
8078
8079        UserHandle user;
8080        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8081            user = UserHandle.ALL;
8082        } else {
8083            user = new UserHandle(userId);
8084        }
8085
8086        verificationParams.setInstallerUid(callingUid);
8087
8088        final File originFile = new File(originPath);
8089        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8090
8091        final Message msg = mHandler.obtainMessage(INIT_COPY);
8092        msg.obj = new InstallParams(origin, observer, installFlags,
8093                installerPackageName, verificationParams, user, packageAbiOverride);
8094        mHandler.sendMessage(msg);
8095    }
8096
8097    void installStage(String packageName, File stagedDir, String stagedCid,
8098            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8099            String installerPackageName, int installerUid, UserHandle user) {
8100        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8101                params.referrerUri, installerUid, null);
8102
8103        final OriginInfo origin;
8104        if (stagedDir != null) {
8105            origin = OriginInfo.fromStagedFile(stagedDir);
8106        } else {
8107            origin = OriginInfo.fromStagedContainer(stagedCid);
8108        }
8109
8110        final Message msg = mHandler.obtainMessage(INIT_COPY);
8111        msg.obj = new InstallParams(origin, observer, params.installFlags,
8112                installerPackageName, verifParams, user, params.abiOverride);
8113        mHandler.sendMessage(msg);
8114    }
8115
8116    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8117        Bundle extras = new Bundle(1);
8118        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8119
8120        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8121                packageName, extras, null, null, new int[] {userId});
8122        try {
8123            IActivityManager am = ActivityManagerNative.getDefault();
8124            final boolean isSystem =
8125                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8126            if (isSystem && am.isUserRunning(userId, false)) {
8127                // The just-installed/enabled app is bundled on the system, so presumed
8128                // to be able to run automatically without needing an explicit launch.
8129                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8130                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8131                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8132                        .setPackage(packageName);
8133                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8134                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8135            }
8136        } catch (RemoteException e) {
8137            // shouldn't happen
8138            Slog.w(TAG, "Unable to bootstrap installed package", e);
8139        }
8140    }
8141
8142    @Override
8143    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8144            int userId) {
8145        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8146        PackageSetting pkgSetting;
8147        final int uid = Binder.getCallingUid();
8148        enforceCrossUserPermission(uid, userId, true, true,
8149                "setApplicationHiddenSetting for user " + userId);
8150
8151        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8152            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8153            return false;
8154        }
8155
8156        long callingId = Binder.clearCallingIdentity();
8157        try {
8158            boolean sendAdded = false;
8159            boolean sendRemoved = false;
8160            // writer
8161            synchronized (mPackages) {
8162                pkgSetting = mSettings.mPackages.get(packageName);
8163                if (pkgSetting == null) {
8164                    return false;
8165                }
8166                if (pkgSetting.getHidden(userId) != hidden) {
8167                    pkgSetting.setHidden(hidden, userId);
8168                    mSettings.writePackageRestrictionsLPr(userId);
8169                    if (hidden) {
8170                        sendRemoved = true;
8171                    } else {
8172                        sendAdded = true;
8173                    }
8174                }
8175            }
8176            if (sendAdded) {
8177                sendPackageAddedForUser(packageName, pkgSetting, userId);
8178                return true;
8179            }
8180            if (sendRemoved) {
8181                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8182                        "hiding pkg");
8183                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8184            }
8185        } finally {
8186            Binder.restoreCallingIdentity(callingId);
8187        }
8188        return false;
8189    }
8190
8191    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8192            int userId) {
8193        final PackageRemovedInfo info = new PackageRemovedInfo();
8194        info.removedPackage = packageName;
8195        info.removedUsers = new int[] {userId};
8196        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8197        info.sendBroadcast(false, false, false);
8198    }
8199
8200    /**
8201     * Returns true if application is not found or there was an error. Otherwise it returns
8202     * the hidden state of the package for the given user.
8203     */
8204    @Override
8205    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8206        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8207        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8208                false, "getApplicationHidden for user " + userId);
8209        PackageSetting pkgSetting;
8210        long callingId = Binder.clearCallingIdentity();
8211        try {
8212            // writer
8213            synchronized (mPackages) {
8214                pkgSetting = mSettings.mPackages.get(packageName);
8215                if (pkgSetting == null) {
8216                    return true;
8217                }
8218                return pkgSetting.getHidden(userId);
8219            }
8220        } finally {
8221            Binder.restoreCallingIdentity(callingId);
8222        }
8223    }
8224
8225    /**
8226     * @hide
8227     */
8228    @Override
8229    public int installExistingPackageAsUser(String packageName, int userId) {
8230        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8231                null);
8232        PackageSetting pkgSetting;
8233        final int uid = Binder.getCallingUid();
8234        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8235                + userId);
8236        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8237            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8238        }
8239
8240        long callingId = Binder.clearCallingIdentity();
8241        try {
8242            boolean sendAdded = false;
8243            Bundle extras = new Bundle(1);
8244
8245            // writer
8246            synchronized (mPackages) {
8247                pkgSetting = mSettings.mPackages.get(packageName);
8248                if (pkgSetting == null) {
8249                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8250                }
8251                if (!pkgSetting.getInstalled(userId)) {
8252                    pkgSetting.setInstalled(true, userId);
8253                    pkgSetting.setHidden(false, userId);
8254                    mSettings.writePackageRestrictionsLPr(userId);
8255                    sendAdded = true;
8256                }
8257            }
8258
8259            if (sendAdded) {
8260                sendPackageAddedForUser(packageName, pkgSetting, userId);
8261            }
8262        } finally {
8263            Binder.restoreCallingIdentity(callingId);
8264        }
8265
8266        return PackageManager.INSTALL_SUCCEEDED;
8267    }
8268
8269    boolean isUserRestricted(int userId, String restrictionKey) {
8270        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8271        if (restrictions.getBoolean(restrictionKey, false)) {
8272            Log.w(TAG, "User is restricted: " + restrictionKey);
8273            return true;
8274        }
8275        return false;
8276    }
8277
8278    @Override
8279    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8280        mContext.enforceCallingOrSelfPermission(
8281                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8282                "Only package verification agents can verify applications");
8283
8284        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8285        final PackageVerificationResponse response = new PackageVerificationResponse(
8286                verificationCode, Binder.getCallingUid());
8287        msg.arg1 = id;
8288        msg.obj = response;
8289        mHandler.sendMessage(msg);
8290    }
8291
8292    @Override
8293    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8294            long millisecondsToDelay) {
8295        mContext.enforceCallingOrSelfPermission(
8296                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8297                "Only package verification agents can extend verification timeouts");
8298
8299        final PackageVerificationState state = mPendingVerification.get(id);
8300        final PackageVerificationResponse response = new PackageVerificationResponse(
8301                verificationCodeAtTimeout, Binder.getCallingUid());
8302
8303        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8304            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8305        }
8306        if (millisecondsToDelay < 0) {
8307            millisecondsToDelay = 0;
8308        }
8309        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8310                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8311            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8312        }
8313
8314        if ((state != null) && !state.timeoutExtended()) {
8315            state.extendTimeout();
8316
8317            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8318            msg.arg1 = id;
8319            msg.obj = response;
8320            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8321        }
8322    }
8323
8324    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8325            int verificationCode, UserHandle user) {
8326        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8327        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8328        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8329        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8330        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8331
8332        mContext.sendBroadcastAsUser(intent, user,
8333                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8334    }
8335
8336    private ComponentName matchComponentForVerifier(String packageName,
8337            List<ResolveInfo> receivers) {
8338        ActivityInfo targetReceiver = null;
8339
8340        final int NR = receivers.size();
8341        for (int i = 0; i < NR; i++) {
8342            final ResolveInfo info = receivers.get(i);
8343            if (info.activityInfo == null) {
8344                continue;
8345            }
8346
8347            if (packageName.equals(info.activityInfo.packageName)) {
8348                targetReceiver = info.activityInfo;
8349                break;
8350            }
8351        }
8352
8353        if (targetReceiver == null) {
8354            return null;
8355        }
8356
8357        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8358    }
8359
8360    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8361            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8362        if (pkgInfo.verifiers.length == 0) {
8363            return null;
8364        }
8365
8366        final int N = pkgInfo.verifiers.length;
8367        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8368        for (int i = 0; i < N; i++) {
8369            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8370
8371            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8372                    receivers);
8373            if (comp == null) {
8374                continue;
8375            }
8376
8377            final int verifierUid = getUidForVerifier(verifierInfo);
8378            if (verifierUid == -1) {
8379                continue;
8380            }
8381
8382            if (DEBUG_VERIFY) {
8383                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8384                        + " with the correct signature");
8385            }
8386            sufficientVerifiers.add(comp);
8387            verificationState.addSufficientVerifier(verifierUid);
8388        }
8389
8390        return sufficientVerifiers;
8391    }
8392
8393    private int getUidForVerifier(VerifierInfo verifierInfo) {
8394        synchronized (mPackages) {
8395            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8396            if (pkg == null) {
8397                return -1;
8398            } else if (pkg.mSignatures.length != 1) {
8399                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8400                        + " has more than one signature; ignoring");
8401                return -1;
8402            }
8403
8404            /*
8405             * If the public key of the package's signature does not match
8406             * our expected public key, then this is a different package and
8407             * we should skip.
8408             */
8409
8410            final byte[] expectedPublicKey;
8411            try {
8412                final Signature verifierSig = pkg.mSignatures[0];
8413                final PublicKey publicKey = verifierSig.getPublicKey();
8414                expectedPublicKey = publicKey.getEncoded();
8415            } catch (CertificateException e) {
8416                return -1;
8417            }
8418
8419            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8420
8421            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8422                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8423                        + " does not have the expected public key; ignoring");
8424                return -1;
8425            }
8426
8427            return pkg.applicationInfo.uid;
8428        }
8429    }
8430
8431    @Override
8432    public void finishPackageInstall(int token) {
8433        enforceSystemOrRoot("Only the system is allowed to finish installs");
8434
8435        if (DEBUG_INSTALL) {
8436            Slog.v(TAG, "BM finishing package install for " + token);
8437        }
8438
8439        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8440        mHandler.sendMessage(msg);
8441    }
8442
8443    /**
8444     * Get the verification agent timeout.
8445     *
8446     * @return verification timeout in milliseconds
8447     */
8448    private long getVerificationTimeout() {
8449        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8450                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8451                DEFAULT_VERIFICATION_TIMEOUT);
8452    }
8453
8454    /**
8455     * Get the default verification agent response code.
8456     *
8457     * @return default verification response code
8458     */
8459    private int getDefaultVerificationResponse() {
8460        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8461                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8462                DEFAULT_VERIFICATION_RESPONSE);
8463    }
8464
8465    /**
8466     * Check whether or not package verification has been enabled.
8467     *
8468     * @return true if verification should be performed
8469     */
8470    private boolean isVerificationEnabled(int userId, int installFlags) {
8471        if (!DEFAULT_VERIFY_ENABLE) {
8472            return false;
8473        }
8474
8475        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8476
8477        // Check if installing from ADB
8478        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8479            // Do not run verification in a test harness environment
8480            if (ActivityManager.isRunningInTestHarness()) {
8481                return false;
8482            }
8483            if (ensureVerifyAppsEnabled) {
8484                return true;
8485            }
8486            // Check if the developer does not want package verification for ADB installs
8487            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8488                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8489                return false;
8490            }
8491        }
8492
8493        if (ensureVerifyAppsEnabled) {
8494            return true;
8495        }
8496
8497        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8498                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8499    }
8500
8501    /**
8502     * Get the "allow unknown sources" setting.
8503     *
8504     * @return the current "allow unknown sources" setting
8505     */
8506    private int getUnknownSourcesSettings() {
8507        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8508                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8509                -1);
8510    }
8511
8512    @Override
8513    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8514        final int uid = Binder.getCallingUid();
8515        // writer
8516        synchronized (mPackages) {
8517            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8518            if (targetPackageSetting == null) {
8519                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8520            }
8521
8522            PackageSetting installerPackageSetting;
8523            if (installerPackageName != null) {
8524                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8525                if (installerPackageSetting == null) {
8526                    throw new IllegalArgumentException("Unknown installer package: "
8527                            + installerPackageName);
8528                }
8529            } else {
8530                installerPackageSetting = null;
8531            }
8532
8533            Signature[] callerSignature;
8534            Object obj = mSettings.getUserIdLPr(uid);
8535            if (obj != null) {
8536                if (obj instanceof SharedUserSetting) {
8537                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8538                } else if (obj instanceof PackageSetting) {
8539                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8540                } else {
8541                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8542                }
8543            } else {
8544                throw new SecurityException("Unknown calling uid " + uid);
8545            }
8546
8547            // Verify: can't set installerPackageName to a package that is
8548            // not signed with the same cert as the caller.
8549            if (installerPackageSetting != null) {
8550                if (compareSignatures(callerSignature,
8551                        installerPackageSetting.signatures.mSignatures)
8552                        != PackageManager.SIGNATURE_MATCH) {
8553                    throw new SecurityException(
8554                            "Caller does not have same cert as new installer package "
8555                            + installerPackageName);
8556                }
8557            }
8558
8559            // Verify: if target already has an installer package, it must
8560            // be signed with the same cert as the caller.
8561            if (targetPackageSetting.installerPackageName != null) {
8562                PackageSetting setting = mSettings.mPackages.get(
8563                        targetPackageSetting.installerPackageName);
8564                // If the currently set package isn't valid, then it's always
8565                // okay to change it.
8566                if (setting != null) {
8567                    if (compareSignatures(callerSignature,
8568                            setting.signatures.mSignatures)
8569                            != PackageManager.SIGNATURE_MATCH) {
8570                        throw new SecurityException(
8571                                "Caller does not have same cert as old installer package "
8572                                + targetPackageSetting.installerPackageName);
8573                    }
8574                }
8575            }
8576
8577            // Okay!
8578            targetPackageSetting.installerPackageName = installerPackageName;
8579            scheduleWriteSettingsLocked();
8580        }
8581    }
8582
8583    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8584        // Queue up an async operation since the package installation may take a little while.
8585        mHandler.post(new Runnable() {
8586            public void run() {
8587                mHandler.removeCallbacks(this);
8588                 // Result object to be returned
8589                PackageInstalledInfo res = new PackageInstalledInfo();
8590                res.returnCode = currentStatus;
8591                res.uid = -1;
8592                res.pkg = null;
8593                res.removedInfo = new PackageRemovedInfo();
8594                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8595                    args.doPreInstall(res.returnCode);
8596                    synchronized (mInstallLock) {
8597                        installPackageLI(args, res);
8598                    }
8599                    args.doPostInstall(res.returnCode, res.uid);
8600                }
8601
8602                // A restore should be performed at this point if (a) the install
8603                // succeeded, (b) the operation is not an update, and (c) the new
8604                // package has not opted out of backup participation.
8605                final boolean update = res.removedInfo.removedPackage != null;
8606                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8607                boolean doRestore = !update
8608                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8609
8610                // Set up the post-install work request bookkeeping.  This will be used
8611                // and cleaned up by the post-install event handling regardless of whether
8612                // there's a restore pass performed.  Token values are >= 1.
8613                int token;
8614                if (mNextInstallToken < 0) mNextInstallToken = 1;
8615                token = mNextInstallToken++;
8616
8617                PostInstallData data = new PostInstallData(args, res);
8618                mRunningInstalls.put(token, data);
8619                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8620
8621                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8622                    // Pass responsibility to the Backup Manager.  It will perform a
8623                    // restore if appropriate, then pass responsibility back to the
8624                    // Package Manager to run the post-install observer callbacks
8625                    // and broadcasts.
8626                    IBackupManager bm = IBackupManager.Stub.asInterface(
8627                            ServiceManager.getService(Context.BACKUP_SERVICE));
8628                    if (bm != null) {
8629                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8630                                + " to BM for possible restore");
8631                        try {
8632                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8633                        } catch (RemoteException e) {
8634                            // can't happen; the backup manager is local
8635                        } catch (Exception e) {
8636                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8637                            doRestore = false;
8638                        }
8639                    } else {
8640                        Slog.e(TAG, "Backup Manager not found!");
8641                        doRestore = false;
8642                    }
8643                }
8644
8645                if (!doRestore) {
8646                    // No restore possible, or the Backup Manager was mysteriously not
8647                    // available -- just fire the post-install work request directly.
8648                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8649                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8650                    mHandler.sendMessage(msg);
8651                }
8652            }
8653        });
8654    }
8655
8656    private abstract class HandlerParams {
8657        private static final int MAX_RETRIES = 4;
8658
8659        /**
8660         * Number of times startCopy() has been attempted and had a non-fatal
8661         * error.
8662         */
8663        private int mRetries = 0;
8664
8665        /** User handle for the user requesting the information or installation. */
8666        private final UserHandle mUser;
8667
8668        HandlerParams(UserHandle user) {
8669            mUser = user;
8670        }
8671
8672        UserHandle getUser() {
8673            return mUser;
8674        }
8675
8676        final boolean startCopy() {
8677            boolean res;
8678            try {
8679                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8680
8681                if (++mRetries > MAX_RETRIES) {
8682                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8683                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8684                    handleServiceError();
8685                    return false;
8686                } else {
8687                    handleStartCopy();
8688                    res = true;
8689                }
8690            } catch (RemoteException e) {
8691                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8692                mHandler.sendEmptyMessage(MCS_RECONNECT);
8693                res = false;
8694            }
8695            handleReturnCode();
8696            return res;
8697        }
8698
8699        final void serviceError() {
8700            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8701            handleServiceError();
8702            handleReturnCode();
8703        }
8704
8705        abstract void handleStartCopy() throws RemoteException;
8706        abstract void handleServiceError();
8707        abstract void handleReturnCode();
8708    }
8709
8710    class MeasureParams extends HandlerParams {
8711        private final PackageStats mStats;
8712        private boolean mSuccess;
8713
8714        private final IPackageStatsObserver mObserver;
8715
8716        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8717            super(new UserHandle(stats.userHandle));
8718            mObserver = observer;
8719            mStats = stats;
8720        }
8721
8722        @Override
8723        public String toString() {
8724            return "MeasureParams{"
8725                + Integer.toHexString(System.identityHashCode(this))
8726                + " " + mStats.packageName + "}";
8727        }
8728
8729        @Override
8730        void handleStartCopy() throws RemoteException {
8731            synchronized (mInstallLock) {
8732                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8733            }
8734
8735            if (mSuccess) {
8736                final boolean mounted;
8737                if (Environment.isExternalStorageEmulated()) {
8738                    mounted = true;
8739                } else {
8740                    final String status = Environment.getExternalStorageState();
8741                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8742                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8743                }
8744
8745                if (mounted) {
8746                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8747
8748                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8749                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8750
8751                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8752                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8753
8754                    // Always subtract cache size, since it's a subdirectory
8755                    mStats.externalDataSize -= mStats.externalCacheSize;
8756
8757                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8758                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8759
8760                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8761                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8762                }
8763            }
8764        }
8765
8766        @Override
8767        void handleReturnCode() {
8768            if (mObserver != null) {
8769                try {
8770                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8771                } catch (RemoteException e) {
8772                    Slog.i(TAG, "Observer no longer exists.");
8773                }
8774            }
8775        }
8776
8777        @Override
8778        void handleServiceError() {
8779            Slog.e(TAG, "Could not measure application " + mStats.packageName
8780                            + " external storage");
8781        }
8782    }
8783
8784    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8785            throws RemoteException {
8786        long result = 0;
8787        for (File path : paths) {
8788            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8789        }
8790        return result;
8791    }
8792
8793    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8794        for (File path : paths) {
8795            try {
8796                mcs.clearDirectory(path.getAbsolutePath());
8797            } catch (RemoteException e) {
8798            }
8799        }
8800    }
8801
8802    static class OriginInfo {
8803        /**
8804         * Location where install is coming from, before it has been
8805         * copied/renamed into place. This could be a single monolithic APK
8806         * file, or a cluster directory. This location may be untrusted.
8807         */
8808        final File file;
8809        final String cid;
8810
8811        /**
8812         * Flag indicating that {@link #file} or {@link #cid} has already been
8813         * staged, meaning downstream users don't need to defensively copy the
8814         * contents.
8815         */
8816        final boolean staged;
8817
8818        /**
8819         * Flag indicating that {@link #file} or {@link #cid} is an already
8820         * installed app that is being moved.
8821         */
8822        final boolean existing;
8823
8824        final String resolvedPath;
8825        final File resolvedFile;
8826
8827        static OriginInfo fromNothing() {
8828            return new OriginInfo(null, null, false, false);
8829        }
8830
8831        static OriginInfo fromUntrustedFile(File file) {
8832            return new OriginInfo(file, null, false, false);
8833        }
8834
8835        static OriginInfo fromExistingFile(File file) {
8836            return new OriginInfo(file, null, false, true);
8837        }
8838
8839        static OriginInfo fromStagedFile(File file) {
8840            return new OriginInfo(file, null, true, false);
8841        }
8842
8843        static OriginInfo fromStagedContainer(String cid) {
8844            return new OriginInfo(null, cid, true, false);
8845        }
8846
8847        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8848            this.file = file;
8849            this.cid = cid;
8850            this.staged = staged;
8851            this.existing = existing;
8852
8853            if (cid != null) {
8854                resolvedPath = PackageHelper.getSdDir(cid);
8855                resolvedFile = new File(resolvedPath);
8856            } else if (file != null) {
8857                resolvedPath = file.getAbsolutePath();
8858                resolvedFile = file;
8859            } else {
8860                resolvedPath = null;
8861                resolvedFile = null;
8862            }
8863        }
8864    }
8865
8866    class InstallParams extends HandlerParams {
8867        final OriginInfo origin;
8868        final IPackageInstallObserver2 observer;
8869        int installFlags;
8870        final String installerPackageName;
8871        final VerificationParams verificationParams;
8872        private InstallArgs mArgs;
8873        private int mRet;
8874        final String packageAbiOverride;
8875
8876        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8877                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8878                String packageAbiOverride) {
8879            super(user);
8880            this.origin = origin;
8881            this.observer = observer;
8882            this.installFlags = installFlags;
8883            this.installerPackageName = installerPackageName;
8884            this.verificationParams = verificationParams;
8885            this.packageAbiOverride = packageAbiOverride;
8886        }
8887
8888        @Override
8889        public String toString() {
8890            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8891                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8892        }
8893
8894        public ManifestDigest getManifestDigest() {
8895            if (verificationParams == null) {
8896                return null;
8897            }
8898            return verificationParams.getManifestDigest();
8899        }
8900
8901        private int installLocationPolicy(PackageInfoLite pkgLite) {
8902            String packageName = pkgLite.packageName;
8903            int installLocation = pkgLite.installLocation;
8904            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8905            // reader
8906            synchronized (mPackages) {
8907                PackageParser.Package pkg = mPackages.get(packageName);
8908                if (pkg != null) {
8909                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8910                        // Check for downgrading.
8911                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8912                            try {
8913                                checkDowngrade(pkg, pkgLite);
8914                            } catch (PackageManagerException e) {
8915                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
8916                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8917                            }
8918                        }
8919                        // Check for updated system application.
8920                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8921                            if (onSd) {
8922                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8923                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8924                            }
8925                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8926                        } else {
8927                            if (onSd) {
8928                                // Install flag overrides everything.
8929                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8930                            }
8931                            // If current upgrade specifies particular preference
8932                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8933                                // Application explicitly specified internal.
8934                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8935                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8936                                // App explictly prefers external. Let policy decide
8937                            } else {
8938                                // Prefer previous location
8939                                if (isExternal(pkg)) {
8940                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8941                                }
8942                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8943                            }
8944                        }
8945                    } else {
8946                        // Invalid install. Return error code
8947                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8948                    }
8949                }
8950            }
8951            // All the special cases have been taken care of.
8952            // Return result based on recommended install location.
8953            if (onSd) {
8954                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8955            }
8956            return pkgLite.recommendedInstallLocation;
8957        }
8958
8959        /*
8960         * Invoke remote method to get package information and install
8961         * location values. Override install location based on default
8962         * policy if needed and then create install arguments based
8963         * on the install location.
8964         */
8965        public void handleStartCopy() throws RemoteException {
8966            int ret = PackageManager.INSTALL_SUCCEEDED;
8967
8968            // If we're already staged, we've firmly committed to an install location
8969            if (origin.staged) {
8970                if (origin.file != null) {
8971                    installFlags |= PackageManager.INSTALL_INTERNAL;
8972                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8973                } else if (origin.cid != null) {
8974                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8975                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8976                } else {
8977                    throw new IllegalStateException("Invalid stage location");
8978                }
8979            }
8980
8981            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8982            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8983
8984            PackageInfoLite pkgLite = null;
8985
8986            if (onInt && onSd) {
8987                // Check if both bits are set.
8988                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8989                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8990            } else {
8991                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8992                        packageAbiOverride);
8993
8994                /*
8995                 * If we have too little free space, try to free cache
8996                 * before giving up.
8997                 */
8998                if (!origin.staged && pkgLite.recommendedInstallLocation
8999                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9000                    // TODO: focus freeing disk space on the target device
9001                    final StorageManager storage = StorageManager.from(mContext);
9002                    final long lowThreshold = storage.getStorageLowBytes(
9003                            Environment.getDataDirectory());
9004
9005                    final long sizeBytes = mContainerService.calculateInstalledSize(
9006                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9007
9008                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
9009                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9010                                installFlags, packageAbiOverride);
9011                    }
9012
9013                    /*
9014                     * The cache free must have deleted the file we
9015                     * downloaded to install.
9016                     *
9017                     * TODO: fix the "freeCache" call to not delete
9018                     *       the file we care about.
9019                     */
9020                    if (pkgLite.recommendedInstallLocation
9021                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9022                        pkgLite.recommendedInstallLocation
9023                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9024                    }
9025                }
9026            }
9027
9028            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9029                int loc = pkgLite.recommendedInstallLocation;
9030                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9031                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9032                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9033                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9034                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9035                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9036                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9037                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9038                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9039                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9040                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9041                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9042                } else {
9043                    // Override with defaults if needed.
9044                    loc = installLocationPolicy(pkgLite);
9045                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9046                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9047                    } else if (!onSd && !onInt) {
9048                        // Override install location with flags
9049                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9050                            // Set the flag to install on external media.
9051                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9052                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9053                        } else {
9054                            // Make sure the flag for installing on external
9055                            // media is unset
9056                            installFlags |= PackageManager.INSTALL_INTERNAL;
9057                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9058                        }
9059                    }
9060                }
9061            }
9062
9063            final InstallArgs args = createInstallArgs(this);
9064            mArgs = args;
9065
9066            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9067                 /*
9068                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9069                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9070                 */
9071                int userIdentifier = getUser().getIdentifier();
9072                if (userIdentifier == UserHandle.USER_ALL
9073                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9074                    userIdentifier = UserHandle.USER_OWNER;
9075                }
9076
9077                /*
9078                 * Determine if we have any installed package verifiers. If we
9079                 * do, then we'll defer to them to verify the packages.
9080                 */
9081                final int requiredUid = mRequiredVerifierPackage == null ? -1
9082                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9083                if (!origin.existing && requiredUid != -1
9084                        && isVerificationEnabled(userIdentifier, installFlags)) {
9085                    final Intent verification = new Intent(
9086                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9087                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9088                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9089                            PACKAGE_MIME_TYPE);
9090                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9091
9092                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9093                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9094                            0 /* TODO: Which userId? */);
9095
9096                    if (DEBUG_VERIFY) {
9097                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9098                                + verification.toString() + " with " + pkgLite.verifiers.length
9099                                + " optional verifiers");
9100                    }
9101
9102                    final int verificationId = mPendingVerificationToken++;
9103
9104                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9105
9106                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9107                            installerPackageName);
9108
9109                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9110                            installFlags);
9111
9112                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9113                            pkgLite.packageName);
9114
9115                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9116                            pkgLite.versionCode);
9117
9118                    if (verificationParams != null) {
9119                        if (verificationParams.getVerificationURI() != null) {
9120                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9121                                 verificationParams.getVerificationURI());
9122                        }
9123                        if (verificationParams.getOriginatingURI() != null) {
9124                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9125                                  verificationParams.getOriginatingURI());
9126                        }
9127                        if (verificationParams.getReferrer() != null) {
9128                            verification.putExtra(Intent.EXTRA_REFERRER,
9129                                  verificationParams.getReferrer());
9130                        }
9131                        if (verificationParams.getOriginatingUid() >= 0) {
9132                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9133                                  verificationParams.getOriginatingUid());
9134                        }
9135                        if (verificationParams.getInstallerUid() >= 0) {
9136                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9137                                  verificationParams.getInstallerUid());
9138                        }
9139                    }
9140
9141                    final PackageVerificationState verificationState = new PackageVerificationState(
9142                            requiredUid, args);
9143
9144                    mPendingVerification.append(verificationId, verificationState);
9145
9146                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9147                            receivers, verificationState);
9148
9149                    /*
9150                     * If any sufficient verifiers were listed in the package
9151                     * manifest, attempt to ask them.
9152                     */
9153                    if (sufficientVerifiers != null) {
9154                        final int N = sufficientVerifiers.size();
9155                        if (N == 0) {
9156                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9157                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9158                        } else {
9159                            for (int i = 0; i < N; i++) {
9160                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9161
9162                                final Intent sufficientIntent = new Intent(verification);
9163                                sufficientIntent.setComponent(verifierComponent);
9164
9165                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9166                            }
9167                        }
9168                    }
9169
9170                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9171                            mRequiredVerifierPackage, receivers);
9172                    if (ret == PackageManager.INSTALL_SUCCEEDED
9173                            && mRequiredVerifierPackage != null) {
9174                        /*
9175                         * Send the intent to the required verification agent,
9176                         * but only start the verification timeout after the
9177                         * target BroadcastReceivers have run.
9178                         */
9179                        verification.setComponent(requiredVerifierComponent);
9180                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9181                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9182                                new BroadcastReceiver() {
9183                                    @Override
9184                                    public void onReceive(Context context, Intent intent) {
9185                                        final Message msg = mHandler
9186                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9187                                        msg.arg1 = verificationId;
9188                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9189                                    }
9190                                }, null, 0, null, null);
9191
9192                        /*
9193                         * We don't want the copy to proceed until verification
9194                         * succeeds, so null out this field.
9195                         */
9196                        mArgs = null;
9197                    }
9198                } else {
9199                    /*
9200                     * No package verification is enabled, so immediately start
9201                     * the remote call to initiate copy using temporary file.
9202                     */
9203                    ret = args.copyApk(mContainerService, true);
9204                }
9205            }
9206
9207            mRet = ret;
9208        }
9209
9210        @Override
9211        void handleReturnCode() {
9212            // If mArgs is null, then MCS couldn't be reached. When it
9213            // reconnects, it will try again to install. At that point, this
9214            // will succeed.
9215            if (mArgs != null) {
9216                processPendingInstall(mArgs, mRet);
9217            }
9218        }
9219
9220        @Override
9221        void handleServiceError() {
9222            mArgs = createInstallArgs(this);
9223            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9224        }
9225
9226        public boolean isForwardLocked() {
9227            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9228        }
9229    }
9230
9231    /**
9232     * Used during creation of InstallArgs
9233     *
9234     * @param installFlags package installation flags
9235     * @return true if should be installed on external storage
9236     */
9237    private static boolean installOnSd(int installFlags) {
9238        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9239            return false;
9240        }
9241        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9242            return true;
9243        }
9244        return false;
9245    }
9246
9247    /**
9248     * Used during creation of InstallArgs
9249     *
9250     * @param installFlags package installation flags
9251     * @return true if should be installed as forward locked
9252     */
9253    private static boolean installForwardLocked(int installFlags) {
9254        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9255    }
9256
9257    private InstallArgs createInstallArgs(InstallParams params) {
9258        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
9259            return new AsecInstallArgs(params);
9260        } else {
9261            return new FileInstallArgs(params);
9262        }
9263    }
9264
9265    /**
9266     * Create args that describe an existing installed package. Typically used
9267     * when cleaning up old installs, or used as a move source.
9268     */
9269    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9270            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9271        final boolean isInAsec;
9272        if (installOnSd(installFlags)) {
9273            /* Apps on SD card are always in ASEC containers. */
9274            isInAsec = true;
9275        } else if (installForwardLocked(installFlags)
9276                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9277            /*
9278             * Forward-locked apps are only in ASEC containers if they're the
9279             * new style
9280             */
9281            isInAsec = true;
9282        } else {
9283            isInAsec = false;
9284        }
9285
9286        if (isInAsec) {
9287            return new AsecInstallArgs(codePath, instructionSets,
9288                    installOnSd(installFlags), installForwardLocked(installFlags));
9289        } else {
9290            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9291                    instructionSets);
9292        }
9293    }
9294
9295    static abstract class InstallArgs {
9296        /** @see InstallParams#origin */
9297        final OriginInfo origin;
9298
9299        final IPackageInstallObserver2 observer;
9300        // Always refers to PackageManager flags only
9301        final int installFlags;
9302        final String installerPackageName;
9303        final ManifestDigest manifestDigest;
9304        final UserHandle user;
9305        final String abiOverride;
9306
9307        // The list of instruction sets supported by this app. This is currently
9308        // only used during the rmdex() phase to clean up resources. We can get rid of this
9309        // if we move dex files under the common app path.
9310        /* nullable */ String[] instructionSets;
9311
9312        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9313                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9314                String[] instructionSets, String abiOverride) {
9315            this.origin = origin;
9316            this.installFlags = installFlags;
9317            this.observer = observer;
9318            this.installerPackageName = installerPackageName;
9319            this.manifestDigest = manifestDigest;
9320            this.user = user;
9321            this.instructionSets = instructionSets;
9322            this.abiOverride = abiOverride;
9323        }
9324
9325        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9326        abstract int doPreInstall(int status);
9327
9328        /**
9329         * Rename package into final resting place. All paths on the given
9330         * scanned package should be updated to reflect the rename.
9331         */
9332        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9333        abstract int doPostInstall(int status, int uid);
9334
9335        /** @see PackageSettingBase#codePathString */
9336        abstract String getCodePath();
9337        /** @see PackageSettingBase#resourcePathString */
9338        abstract String getResourcePath();
9339        abstract String getLegacyNativeLibraryPath();
9340
9341        // Need installer lock especially for dex file removal.
9342        abstract void cleanUpResourcesLI();
9343        abstract boolean doPostDeleteLI(boolean delete);
9344        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9345
9346        /**
9347         * Called before the source arguments are copied. This is used mostly
9348         * for MoveParams when it needs to read the source file to put it in the
9349         * destination.
9350         */
9351        int doPreCopy() {
9352            return PackageManager.INSTALL_SUCCEEDED;
9353        }
9354
9355        /**
9356         * Called after the source arguments are copied. This is used mostly for
9357         * MoveParams when it needs to read the source file to put it in the
9358         * destination.
9359         *
9360         * @return
9361         */
9362        int doPostCopy(int uid) {
9363            return PackageManager.INSTALL_SUCCEEDED;
9364        }
9365
9366        protected boolean isFwdLocked() {
9367            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9368        }
9369
9370        protected boolean isExternal() {
9371            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9372        }
9373
9374        UserHandle getUser() {
9375            return user;
9376        }
9377    }
9378
9379    /**
9380     * Logic to handle installation of non-ASEC applications, including copying
9381     * and renaming logic.
9382     */
9383    class FileInstallArgs extends InstallArgs {
9384        private File codeFile;
9385        private File resourceFile;
9386        private File legacyNativeLibraryPath;
9387
9388        // Example topology:
9389        // /data/app/com.example/base.apk
9390        // /data/app/com.example/split_foo.apk
9391        // /data/app/com.example/lib/arm/libfoo.so
9392        // /data/app/com.example/lib/arm64/libfoo.so
9393        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9394
9395        /** New install */
9396        FileInstallArgs(InstallParams params) {
9397            super(params.origin, params.observer, params.installFlags,
9398                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9399                    null /* instruction sets */, params.packageAbiOverride);
9400            if (isFwdLocked()) {
9401                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9402            }
9403        }
9404
9405        /** Existing install */
9406        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9407                String[] instructionSets) {
9408            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9409            this.codeFile = (codePath != null) ? new File(codePath) : null;
9410            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9411            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9412                    new File(legacyNativeLibraryPath) : null;
9413        }
9414
9415        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9416            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9417                    isFwdLocked(), abiOverride);
9418
9419            final StorageManager storage = StorageManager.from(mContext);
9420            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9421        }
9422
9423        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9424            if (origin.staged) {
9425                Slog.d(TAG, origin.file + " already staged; skipping copy");
9426                codeFile = origin.file;
9427                resourceFile = origin.file;
9428                return PackageManager.INSTALL_SUCCEEDED;
9429            }
9430
9431            try {
9432                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9433                codeFile = tempDir;
9434                resourceFile = tempDir;
9435            } catch (IOException e) {
9436                Slog.w(TAG, "Failed to create copy file: " + e);
9437                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9438            }
9439
9440            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9441                @Override
9442                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9443                    if (!FileUtils.isValidExtFilename(name)) {
9444                        throw new IllegalArgumentException("Invalid filename: " + name);
9445                    }
9446                    try {
9447                        final File file = new File(codeFile, name);
9448                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9449                                O_RDWR | O_CREAT, 0644);
9450                        Os.chmod(file.getAbsolutePath(), 0644);
9451                        return new ParcelFileDescriptor(fd);
9452                    } catch (ErrnoException e) {
9453                        throw new RemoteException("Failed to open: " + e.getMessage());
9454                    }
9455                }
9456            };
9457
9458            int ret = PackageManager.INSTALL_SUCCEEDED;
9459            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9460            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9461                Slog.e(TAG, "Failed to copy package");
9462                return ret;
9463            }
9464
9465            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9466            NativeLibraryHelper.Handle handle = null;
9467            try {
9468                handle = NativeLibraryHelper.Handle.create(codeFile);
9469                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9470                        abiOverride);
9471            } catch (IOException e) {
9472                Slog.e(TAG, "Copying native libraries failed", e);
9473                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9474            } finally {
9475                IoUtils.closeQuietly(handle);
9476            }
9477
9478            return ret;
9479        }
9480
9481        int doPreInstall(int status) {
9482            if (status != PackageManager.INSTALL_SUCCEEDED) {
9483                cleanUp();
9484            }
9485            return status;
9486        }
9487
9488        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9489            if (status != PackageManager.INSTALL_SUCCEEDED) {
9490                cleanUp();
9491                return false;
9492            } else {
9493                final File beforeCodeFile = codeFile;
9494                final File afterCodeFile = getNextCodePath(pkg.packageName);
9495
9496                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9497                try {
9498                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9499                } catch (ErrnoException e) {
9500                    Slog.d(TAG, "Failed to rename", e);
9501                    return false;
9502                }
9503
9504                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9505                    Slog.d(TAG, "Failed to restorecon");
9506                    return false;
9507                }
9508
9509                // Reflect the rename internally
9510                codeFile = afterCodeFile;
9511                resourceFile = afterCodeFile;
9512
9513                // Reflect the rename in scanned details
9514                pkg.codePath = afterCodeFile.getAbsolutePath();
9515                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9516                        pkg.baseCodePath);
9517                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9518                        pkg.splitCodePaths);
9519
9520                // Reflect the rename in app info
9521                pkg.applicationInfo.setCodePath(pkg.codePath);
9522                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9523                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9524                pkg.applicationInfo.setResourcePath(pkg.codePath);
9525                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9526                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9527
9528                return true;
9529            }
9530        }
9531
9532        int doPostInstall(int status, int uid) {
9533            if (status != PackageManager.INSTALL_SUCCEEDED) {
9534                cleanUp();
9535            }
9536            return status;
9537        }
9538
9539        @Override
9540        String getCodePath() {
9541            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9542        }
9543
9544        @Override
9545        String getResourcePath() {
9546            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9547        }
9548
9549        @Override
9550        String getLegacyNativeLibraryPath() {
9551            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9552        }
9553
9554        private boolean cleanUp() {
9555            if (codeFile == null || !codeFile.exists()) {
9556                return false;
9557            }
9558
9559            if (codeFile.isDirectory()) {
9560                FileUtils.deleteContents(codeFile);
9561            }
9562            codeFile.delete();
9563
9564            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9565                resourceFile.delete();
9566            }
9567
9568            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9569                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9570                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9571                }
9572                legacyNativeLibraryPath.delete();
9573            }
9574
9575            return true;
9576        }
9577
9578        void cleanUpResourcesLI() {
9579            // Try enumerating all code paths before deleting
9580            List<String> allCodePaths = Collections.EMPTY_LIST;
9581            if (codeFile != null && codeFile.exists()) {
9582                try {
9583                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9584                    allCodePaths = pkg.getAllCodePaths();
9585                } catch (PackageParserException e) {
9586                    // Ignored; we tried our best
9587                }
9588            }
9589
9590            cleanUp();
9591
9592            if (!allCodePaths.isEmpty()) {
9593                if (instructionSets == null) {
9594                    throw new IllegalStateException("instructionSet == null");
9595                }
9596                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9597                for (String codePath : allCodePaths) {
9598                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9599                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9600                        if (retCode < 0) {
9601                            Slog.w(TAG, "Couldn't remove dex file for package: "
9602                                    + " at location " + codePath + ", retcode=" + retCode);
9603                            // we don't consider this to be a failure of the core package deletion
9604                        }
9605                    }
9606                }
9607            }
9608        }
9609
9610        boolean doPostDeleteLI(boolean delete) {
9611            // XXX err, shouldn't we respect the delete flag?
9612            cleanUpResourcesLI();
9613            return true;
9614        }
9615    }
9616
9617    private boolean isAsecExternal(String cid) {
9618        final String asecPath = PackageHelper.getSdFilesystem(cid);
9619        return !asecPath.startsWith(mAsecInternalPath);
9620    }
9621
9622    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9623            PackageManagerException {
9624        if (copyRet < 0) {
9625            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9626                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9627                throw new PackageManagerException(copyRet, message);
9628            }
9629        }
9630    }
9631
9632    /**
9633     * Extract the MountService "container ID" from the full code path of an
9634     * .apk.
9635     */
9636    static String cidFromCodePath(String fullCodePath) {
9637        int eidx = fullCodePath.lastIndexOf("/");
9638        String subStr1 = fullCodePath.substring(0, eidx);
9639        int sidx = subStr1.lastIndexOf("/");
9640        return subStr1.substring(sidx+1, eidx);
9641    }
9642
9643    /**
9644     * Logic to handle installation of ASEC applications, including copying and
9645     * renaming logic.
9646     */
9647    class AsecInstallArgs extends InstallArgs {
9648        static final String RES_FILE_NAME = "pkg.apk";
9649        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9650
9651        String cid;
9652        String packagePath;
9653        String resourcePath;
9654        String legacyNativeLibraryDir;
9655
9656        /** New install */
9657        AsecInstallArgs(InstallParams params) {
9658            super(params.origin, params.observer, params.installFlags,
9659                    params.installerPackageName, params.getManifestDigest(),
9660                    params.getUser(), null /* instruction sets */,
9661                    params.packageAbiOverride);
9662        }
9663
9664        /** Existing install */
9665        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9666                        boolean isExternal, boolean isForwardLocked) {
9667            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9668                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9669                    instructionSets, null);
9670            // Hackily pretend we're still looking at a full code path
9671            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9672                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9673            }
9674
9675            // Extract cid from fullCodePath
9676            int eidx = fullCodePath.lastIndexOf("/");
9677            String subStr1 = fullCodePath.substring(0, eidx);
9678            int sidx = subStr1.lastIndexOf("/");
9679            cid = subStr1.substring(sidx+1, eidx);
9680            setMountPath(subStr1);
9681        }
9682
9683        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9684            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9685                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9686                    instructionSets, null);
9687            this.cid = cid;
9688            setMountPath(PackageHelper.getSdDir(cid));
9689        }
9690
9691        void createCopyFile() {
9692            cid = mInstallerService.allocateExternalStageCidLegacy();
9693        }
9694
9695        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9696            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9697                    abiOverride);
9698
9699            final File target;
9700            if (isExternal()) {
9701                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9702            } else {
9703                target = Environment.getDataDirectory();
9704            }
9705
9706            final StorageManager storage = StorageManager.from(mContext);
9707            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9708        }
9709
9710        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9711            if (origin.staged) {
9712                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9713                cid = origin.cid;
9714                setMountPath(PackageHelper.getSdDir(cid));
9715                return PackageManager.INSTALL_SUCCEEDED;
9716            }
9717
9718            if (temp) {
9719                createCopyFile();
9720            } else {
9721                /*
9722                 * Pre-emptively destroy the container since it's destroyed if
9723                 * copying fails due to it existing anyway.
9724                 */
9725                PackageHelper.destroySdDir(cid);
9726            }
9727
9728            final String newMountPath = imcs.copyPackageToContainer(
9729                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9730                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9731
9732            if (newMountPath != null) {
9733                setMountPath(newMountPath);
9734                return PackageManager.INSTALL_SUCCEEDED;
9735            } else {
9736                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9737            }
9738        }
9739
9740        @Override
9741        String getCodePath() {
9742            return packagePath;
9743        }
9744
9745        @Override
9746        String getResourcePath() {
9747            return resourcePath;
9748        }
9749
9750        @Override
9751        String getLegacyNativeLibraryPath() {
9752            return legacyNativeLibraryDir;
9753        }
9754
9755        int doPreInstall(int status) {
9756            if (status != PackageManager.INSTALL_SUCCEEDED) {
9757                // Destroy container
9758                PackageHelper.destroySdDir(cid);
9759            } else {
9760                boolean mounted = PackageHelper.isContainerMounted(cid);
9761                if (!mounted) {
9762                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9763                            Process.SYSTEM_UID);
9764                    if (newMountPath != null) {
9765                        setMountPath(newMountPath);
9766                    } else {
9767                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9768                    }
9769                }
9770            }
9771            return status;
9772        }
9773
9774        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9775            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9776            String newMountPath = null;
9777            if (PackageHelper.isContainerMounted(cid)) {
9778                // Unmount the container
9779                if (!PackageHelper.unMountSdDir(cid)) {
9780                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9781                    return false;
9782                }
9783            }
9784            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9785                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9786                        " which might be stale. Will try to clean up.");
9787                // Clean up the stale container and proceed to recreate.
9788                if (!PackageHelper.destroySdDir(newCacheId)) {
9789                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9790                    return false;
9791                }
9792                // Successfully cleaned up stale container. Try to rename again.
9793                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9794                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9795                            + " inspite of cleaning it up.");
9796                    return false;
9797                }
9798            }
9799            if (!PackageHelper.isContainerMounted(newCacheId)) {
9800                Slog.w(TAG, "Mounting container " + newCacheId);
9801                newMountPath = PackageHelper.mountSdDir(newCacheId,
9802                        getEncryptKey(), Process.SYSTEM_UID);
9803            } else {
9804                newMountPath = PackageHelper.getSdDir(newCacheId);
9805            }
9806            if (newMountPath == null) {
9807                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9808                return false;
9809            }
9810            Log.i(TAG, "Succesfully renamed " + cid +
9811                    " to " + newCacheId +
9812                    " at new path: " + newMountPath);
9813            cid = newCacheId;
9814
9815            final File beforeCodeFile = new File(packagePath);
9816            setMountPath(newMountPath);
9817            final File afterCodeFile = new File(packagePath);
9818
9819            // Reflect the rename in scanned details
9820            pkg.codePath = afterCodeFile.getAbsolutePath();
9821            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9822                    pkg.baseCodePath);
9823            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9824                    pkg.splitCodePaths);
9825
9826            // Reflect the rename in app info
9827            pkg.applicationInfo.setCodePath(pkg.codePath);
9828            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9829            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9830            pkg.applicationInfo.setResourcePath(pkg.codePath);
9831            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9832            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9833
9834            return true;
9835        }
9836
9837        private void setMountPath(String mountPath) {
9838            final File mountFile = new File(mountPath);
9839
9840            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9841            if (monolithicFile.exists()) {
9842                packagePath = monolithicFile.getAbsolutePath();
9843                if (isFwdLocked()) {
9844                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9845                } else {
9846                    resourcePath = packagePath;
9847                }
9848            } else {
9849                packagePath = mountFile.getAbsolutePath();
9850                resourcePath = packagePath;
9851            }
9852
9853            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9854        }
9855
9856        int doPostInstall(int status, int uid) {
9857            if (status != PackageManager.INSTALL_SUCCEEDED) {
9858                cleanUp();
9859            } else {
9860                final int groupOwner;
9861                final String protectedFile;
9862                if (isFwdLocked()) {
9863                    groupOwner = UserHandle.getSharedAppGid(uid);
9864                    protectedFile = RES_FILE_NAME;
9865                } else {
9866                    groupOwner = -1;
9867                    protectedFile = null;
9868                }
9869
9870                if (uid < Process.FIRST_APPLICATION_UID
9871                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9872                    Slog.e(TAG, "Failed to finalize " + cid);
9873                    PackageHelper.destroySdDir(cid);
9874                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9875                }
9876
9877                boolean mounted = PackageHelper.isContainerMounted(cid);
9878                if (!mounted) {
9879                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9880                }
9881            }
9882            return status;
9883        }
9884
9885        private void cleanUp() {
9886            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9887
9888            // Destroy secure container
9889            PackageHelper.destroySdDir(cid);
9890        }
9891
9892        private List<String> getAllCodePaths() {
9893            final File codeFile = new File(getCodePath());
9894            if (codeFile != null && codeFile.exists()) {
9895                try {
9896                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9897                    return pkg.getAllCodePaths();
9898                } catch (PackageParserException e) {
9899                    // Ignored; we tried our best
9900                }
9901            }
9902            return Collections.EMPTY_LIST;
9903        }
9904
9905        void cleanUpResourcesLI() {
9906            // Enumerate all code paths before deleting
9907            cleanUpResourcesLI(getAllCodePaths());
9908        }
9909
9910        private void cleanUpResourcesLI(List<String> allCodePaths) {
9911            cleanUp();
9912
9913            if (!allCodePaths.isEmpty()) {
9914                if (instructionSets == null) {
9915                    throw new IllegalStateException("instructionSet == null");
9916                }
9917                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9918                for (String codePath : allCodePaths) {
9919                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9920                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9921                        if (retCode < 0) {
9922                            Slog.w(TAG, "Couldn't remove dex file for package: "
9923                                    + " at location " + codePath + ", retcode=" + retCode);
9924                            // we don't consider this to be a failure of the core package deletion
9925                        }
9926                    }
9927                }
9928            }
9929        }
9930
9931        boolean matchContainer(String app) {
9932            if (cid.startsWith(app)) {
9933                return true;
9934            }
9935            return false;
9936        }
9937
9938        String getPackageName() {
9939            return getAsecPackageName(cid);
9940        }
9941
9942        boolean doPostDeleteLI(boolean delete) {
9943            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9944            final List<String> allCodePaths = getAllCodePaths();
9945            boolean mounted = PackageHelper.isContainerMounted(cid);
9946            if (mounted) {
9947                // Unmount first
9948                if (PackageHelper.unMountSdDir(cid)) {
9949                    mounted = false;
9950                }
9951            }
9952            if (!mounted && delete) {
9953                cleanUpResourcesLI(allCodePaths);
9954            }
9955            return !mounted;
9956        }
9957
9958        @Override
9959        int doPreCopy() {
9960            if (isFwdLocked()) {
9961                if (!PackageHelper.fixSdPermissions(cid,
9962                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9963                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9964                }
9965            }
9966
9967            return PackageManager.INSTALL_SUCCEEDED;
9968        }
9969
9970        @Override
9971        int doPostCopy(int uid) {
9972            if (isFwdLocked()) {
9973                if (uid < Process.FIRST_APPLICATION_UID
9974                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9975                                RES_FILE_NAME)) {
9976                    Slog.e(TAG, "Failed to finalize " + cid);
9977                    PackageHelper.destroySdDir(cid);
9978                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9979                }
9980            }
9981
9982            return PackageManager.INSTALL_SUCCEEDED;
9983        }
9984    }
9985
9986    static String getAsecPackageName(String packageCid) {
9987        int idx = packageCid.lastIndexOf("-");
9988        if (idx == -1) {
9989            return packageCid;
9990        }
9991        return packageCid.substring(0, idx);
9992    }
9993
9994    // Utility method used to create code paths based on package name and available index.
9995    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9996        String idxStr = "";
9997        int idx = 1;
9998        // Fall back to default value of idx=1 if prefix is not
9999        // part of oldCodePath
10000        if (oldCodePath != null) {
10001            String subStr = oldCodePath;
10002            // Drop the suffix right away
10003            if (suffix != null && subStr.endsWith(suffix)) {
10004                subStr = subStr.substring(0, subStr.length() - suffix.length());
10005            }
10006            // If oldCodePath already contains prefix find out the
10007            // ending index to either increment or decrement.
10008            int sidx = subStr.lastIndexOf(prefix);
10009            if (sidx != -1) {
10010                subStr = subStr.substring(sidx + prefix.length());
10011                if (subStr != null) {
10012                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10013                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10014                    }
10015                    try {
10016                        idx = Integer.parseInt(subStr);
10017                        if (idx <= 1) {
10018                            idx++;
10019                        } else {
10020                            idx--;
10021                        }
10022                    } catch(NumberFormatException e) {
10023                    }
10024                }
10025            }
10026        }
10027        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10028        return prefix + idxStr;
10029    }
10030
10031    private File getNextCodePath(String packageName) {
10032        int suffix = 1;
10033        File result;
10034        do {
10035            result = new File(mAppInstallDir, packageName + "-" + suffix);
10036            suffix++;
10037        } while (result.exists());
10038        return result;
10039    }
10040
10041    // Utility method used to ignore ADD/REMOVE events
10042    // by directory observer.
10043    private static boolean ignoreCodePath(String fullPathStr) {
10044        String apkName = deriveCodePathName(fullPathStr);
10045        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
10046        if (idx != -1 && ((idx+1) < apkName.length())) {
10047            // Make sure the package ends with a numeral
10048            String version = apkName.substring(idx+1);
10049            try {
10050                Integer.parseInt(version);
10051                return true;
10052            } catch (NumberFormatException e) {}
10053        }
10054        return false;
10055    }
10056
10057    // Utility method that returns the relative package path with respect
10058    // to the installation directory. Like say for /data/data/com.test-1.apk
10059    // string com.test-1 is returned.
10060    static String deriveCodePathName(String codePath) {
10061        if (codePath == null) {
10062            return null;
10063        }
10064        final File codeFile = new File(codePath);
10065        final String name = codeFile.getName();
10066        if (codeFile.isDirectory()) {
10067            return name;
10068        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10069            final int lastDot = name.lastIndexOf('.');
10070            return name.substring(0, lastDot);
10071        } else {
10072            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10073            return null;
10074        }
10075    }
10076
10077    class PackageInstalledInfo {
10078        String name;
10079        int uid;
10080        // The set of users that originally had this package installed.
10081        int[] origUsers;
10082        // The set of users that now have this package installed.
10083        int[] newUsers;
10084        PackageParser.Package pkg;
10085        int returnCode;
10086        String returnMsg;
10087        PackageRemovedInfo removedInfo;
10088
10089        public void setError(int code, String msg) {
10090            returnCode = code;
10091            returnMsg = msg;
10092            Slog.w(TAG, msg);
10093        }
10094
10095        public void setError(String msg, PackageParserException e) {
10096            returnCode = e.error;
10097            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10098            Slog.w(TAG, msg, e);
10099        }
10100
10101        public void setError(String msg, PackageManagerException e) {
10102            returnCode = e.error;
10103            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10104            Slog.w(TAG, msg, e);
10105        }
10106
10107        // In some error cases we want to convey more info back to the observer
10108        String origPackage;
10109        String origPermission;
10110    }
10111
10112    /*
10113     * Install a non-existing package.
10114     */
10115    private void installNewPackageLI(PackageParser.Package pkg,
10116            int parseFlags, int scanFlags, UserHandle user,
10117            String installerPackageName, PackageInstalledInfo res) {
10118        // Remember this for later, in case we need to rollback this install
10119        String pkgName = pkg.packageName;
10120
10121        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10122        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
10123        synchronized(mPackages) {
10124            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10125                // A package with the same name is already installed, though
10126                // it has been renamed to an older name.  The package we
10127                // are trying to install should be installed as an update to
10128                // the existing one, but that has not been requested, so bail.
10129                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10130                        + " without first uninstalling package running as "
10131                        + mSettings.mRenamedPackages.get(pkgName));
10132                return;
10133            }
10134            if (mPackages.containsKey(pkgName)) {
10135                // Don't allow installation over an existing package with the same name.
10136                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10137                        + " without first uninstalling.");
10138                return;
10139            }
10140        }
10141
10142        try {
10143            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10144                    System.currentTimeMillis(), user);
10145
10146            updateSettingsLI(newPackage, installerPackageName, null, null, res);
10147            // delete the partially installed application. the data directory will have to be
10148            // restored if it was already existing
10149            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10150                // remove package from internal structures.  Note that we want deletePackageX to
10151                // delete the package data and cache directories that it created in
10152                // scanPackageLocked, unless those directories existed before we even tried to
10153                // install.
10154                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10155                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10156                                res.removedInfo, true);
10157            }
10158
10159        } catch (PackageManagerException e) {
10160            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10161        }
10162    }
10163
10164    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10165        // Upgrade keysets are being used.  Determine if new package has a superset of the
10166        // required keys.
10167        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10168        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10169        for (int i = 0; i < upgradeKeySets.length; i++) {
10170            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10171            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10172                return true;
10173            }
10174        }
10175        return false;
10176    }
10177
10178    private void replacePackageLI(PackageParser.Package pkg,
10179            int parseFlags, int scanFlags, UserHandle user,
10180            String installerPackageName, PackageInstalledInfo res) {
10181        PackageParser.Package oldPackage;
10182        String pkgName = pkg.packageName;
10183        int[] allUsers;
10184        boolean[] perUserInstalled;
10185
10186        // First find the old package info and check signatures
10187        synchronized(mPackages) {
10188            oldPackage = mPackages.get(pkgName);
10189            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10190            PackageSetting ps = mSettings.mPackages.get(pkgName);
10191            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10192                // default to original signature matching
10193                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10194                    != PackageManager.SIGNATURE_MATCH) {
10195                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10196                            "New package has a different signature: " + pkgName);
10197                    return;
10198                }
10199            } else {
10200                if(!checkUpgradeKeySetLP(ps, pkg)) {
10201                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10202                            "New package not signed by keys specified by upgrade-keysets: "
10203                            + pkgName);
10204                    return;
10205                }
10206            }
10207
10208            // In case of rollback, remember per-user/profile install state
10209            allUsers = sUserManager.getUserIds();
10210            perUserInstalled = new boolean[allUsers.length];
10211            for (int i = 0; i < allUsers.length; i++) {
10212                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10213            }
10214        }
10215
10216        boolean sysPkg = (isSystemApp(oldPackage));
10217        if (sysPkg) {
10218            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10219                    user, allUsers, perUserInstalled, installerPackageName, res);
10220        } else {
10221            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10222                    user, allUsers, perUserInstalled, installerPackageName, res);
10223        }
10224    }
10225
10226    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10227            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10228            int[] allUsers, boolean[] perUserInstalled,
10229            String installerPackageName, PackageInstalledInfo res) {
10230        String pkgName = deletedPackage.packageName;
10231        boolean deletedPkg = true;
10232        boolean updatedSettings = false;
10233
10234        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10235                + deletedPackage);
10236        long origUpdateTime;
10237        if (pkg.mExtras != null) {
10238            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10239        } else {
10240            origUpdateTime = 0;
10241        }
10242
10243        // First delete the existing package while retaining the data directory
10244        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10245                res.removedInfo, true)) {
10246            // If the existing package wasn't successfully deleted
10247            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10248            deletedPkg = false;
10249        } else {
10250            // Successfully deleted the old package; proceed with replace.
10251
10252            // If deleted package lived in a container, give users a chance to
10253            // relinquish resources before killing.
10254            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
10255                if (DEBUG_INSTALL) {
10256                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10257                }
10258                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10259                final ArrayList<String> pkgList = new ArrayList<String>(1);
10260                pkgList.add(deletedPackage.applicationInfo.packageName);
10261                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10262            }
10263
10264            deleteCodeCacheDirsLI(pkgName);
10265            try {
10266                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10267                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10268                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10269                updatedSettings = true;
10270            } catch (PackageManagerException e) {
10271                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10272            }
10273        }
10274
10275        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10276            // remove package from internal structures.  Note that we want deletePackageX to
10277            // delete the package data and cache directories that it created in
10278            // scanPackageLocked, unless those directories existed before we even tried to
10279            // install.
10280            if(updatedSettings) {
10281                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10282                deletePackageLI(
10283                        pkgName, null, true, allUsers, perUserInstalled,
10284                        PackageManager.DELETE_KEEP_DATA,
10285                                res.removedInfo, true);
10286            }
10287            // Since we failed to install the new package we need to restore the old
10288            // package that we deleted.
10289            if (deletedPkg) {
10290                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10291                File restoreFile = new File(deletedPackage.codePath);
10292                // Parse old package
10293                boolean oldOnSd = isExternal(deletedPackage);
10294                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10295                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10296                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10297                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10298                try {
10299                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10300                } catch (PackageManagerException e) {
10301                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10302                            + e.getMessage());
10303                    return;
10304                }
10305                // Restore of old package succeeded. Update permissions.
10306                // writer
10307                synchronized (mPackages) {
10308                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10309                            UPDATE_PERMISSIONS_ALL);
10310                    // can downgrade to reader
10311                    mSettings.writeLPr();
10312                }
10313                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10314            }
10315        }
10316    }
10317
10318    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10319            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10320            int[] allUsers, boolean[] perUserInstalled,
10321            String installerPackageName, PackageInstalledInfo res) {
10322        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10323                + ", old=" + deletedPackage);
10324        boolean disabledSystem = false;
10325        boolean updatedSettings = false;
10326        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10327        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10328            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10329        }
10330        String packageName = deletedPackage.packageName;
10331        if (packageName == null) {
10332            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10333                    "Attempt to delete null packageName.");
10334            return;
10335        }
10336        PackageParser.Package oldPkg;
10337        PackageSetting oldPkgSetting;
10338        // reader
10339        synchronized (mPackages) {
10340            oldPkg = mPackages.get(packageName);
10341            oldPkgSetting = mSettings.mPackages.get(packageName);
10342            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10343                    (oldPkgSetting == null)) {
10344                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10345                        "Couldn't find package:" + packageName + " information");
10346                return;
10347            }
10348        }
10349
10350        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10351
10352        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10353        res.removedInfo.removedPackage = packageName;
10354        // Remove existing system package
10355        removePackageLI(oldPkgSetting, true);
10356        // writer
10357        synchronized (mPackages) {
10358            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10359            if (!disabledSystem && deletedPackage != null) {
10360                // We didn't need to disable the .apk as a current system package,
10361                // which means we are replacing another update that is already
10362                // installed.  We need to make sure to delete the older one's .apk.
10363                res.removedInfo.args = createInstallArgsForExisting(0,
10364                        deletedPackage.applicationInfo.getCodePath(),
10365                        deletedPackage.applicationInfo.getResourcePath(),
10366                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10367                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10368            } else {
10369                res.removedInfo.args = null;
10370            }
10371        }
10372
10373        // Successfully disabled the old package. Now proceed with re-installation
10374        deleteCodeCacheDirsLI(packageName);
10375
10376        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10377        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10378
10379        PackageParser.Package newPackage = null;
10380        try {
10381            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10382            if (newPackage.mExtras != null) {
10383                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10384                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10385                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10386
10387                // is the update attempting to change shared user? that isn't going to work...
10388                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10389                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10390                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10391                            + " to " + newPkgSetting.sharedUser);
10392                    updatedSettings = true;
10393                }
10394            }
10395
10396            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10397                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10398                updatedSettings = true;
10399            }
10400
10401        } catch (PackageManagerException e) {
10402            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10403        }
10404
10405        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10406            // Re installation failed. Restore old information
10407            // Remove new pkg information
10408            if (newPackage != null) {
10409                removeInstalledPackageLI(newPackage, true);
10410            }
10411            // Add back the old system package
10412            try {
10413                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10414            } catch (PackageManagerException e) {
10415                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10416            }
10417            // Restore the old system information in Settings
10418            synchronized (mPackages) {
10419                if (disabledSystem) {
10420                    mSettings.enableSystemPackageLPw(packageName);
10421                }
10422                if (updatedSettings) {
10423                    mSettings.setInstallerPackageName(packageName,
10424                            oldPkgSetting.installerPackageName);
10425                }
10426                mSettings.writeLPr();
10427            }
10428        }
10429    }
10430
10431    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10432            int[] allUsers, boolean[] perUserInstalled,
10433            PackageInstalledInfo res) {
10434        String pkgName = newPackage.packageName;
10435        synchronized (mPackages) {
10436            //write settings. the installStatus will be incomplete at this stage.
10437            //note that the new package setting would have already been
10438            //added to mPackages. It hasn't been persisted yet.
10439            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10440            mSettings.writeLPr();
10441        }
10442
10443        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10444
10445        synchronized (mPackages) {
10446            updatePermissionsLPw(newPackage.packageName, newPackage,
10447                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10448                            ? UPDATE_PERMISSIONS_ALL : 0));
10449            // For system-bundled packages, we assume that installing an upgraded version
10450            // of the package implies that the user actually wants to run that new code,
10451            // so we enable the package.
10452            if (isSystemApp(newPackage)) {
10453                // NB: implicit assumption that system package upgrades apply to all users
10454                if (DEBUG_INSTALL) {
10455                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10456                }
10457                PackageSetting ps = mSettings.mPackages.get(pkgName);
10458                if (ps != null) {
10459                    if (res.origUsers != null) {
10460                        for (int userHandle : res.origUsers) {
10461                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10462                                    userHandle, installerPackageName);
10463                        }
10464                    }
10465                    // Also convey the prior install/uninstall state
10466                    if (allUsers != null && perUserInstalled != null) {
10467                        for (int i = 0; i < allUsers.length; i++) {
10468                            if (DEBUG_INSTALL) {
10469                                Slog.d(TAG, "    user " + allUsers[i]
10470                                        + " => " + perUserInstalled[i]);
10471                            }
10472                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10473                        }
10474                        // these install state changes will be persisted in the
10475                        // upcoming call to mSettings.writeLPr().
10476                    }
10477                }
10478            }
10479            res.name = pkgName;
10480            res.uid = newPackage.applicationInfo.uid;
10481            res.pkg = newPackage;
10482            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10483            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10484            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10485            //to update install status
10486            mSettings.writeLPr();
10487        }
10488    }
10489
10490    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10491        final int installFlags = args.installFlags;
10492        String installerPackageName = args.installerPackageName;
10493        File tmpPackageFile = new File(args.getCodePath());
10494        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10495        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10496        boolean replace = false;
10497        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10498        // Result object to be returned
10499        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10500
10501        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10502        // Retrieve PackageSettings and parse package
10503        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10504                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10505                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10506        PackageParser pp = new PackageParser();
10507        pp.setSeparateProcesses(mSeparateProcesses);
10508        pp.setDisplayMetrics(mMetrics);
10509
10510        final PackageParser.Package pkg;
10511        try {
10512            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10513        } catch (PackageParserException e) {
10514            res.setError("Failed parse during installPackageLI", e);
10515            return;
10516        }
10517
10518        // Mark that we have an install time CPU ABI override.
10519        pkg.cpuAbiOverride = args.abiOverride;
10520
10521        String pkgName = res.name = pkg.packageName;
10522        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10523            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10524                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10525                return;
10526            }
10527        }
10528
10529        try {
10530            pp.collectCertificates(pkg, parseFlags);
10531            pp.collectManifestDigest(pkg);
10532        } catch (PackageParserException e) {
10533            res.setError("Failed collect during installPackageLI", e);
10534            return;
10535        }
10536
10537        /* If the installer passed in a manifest digest, compare it now. */
10538        if (args.manifestDigest != null) {
10539            if (DEBUG_INSTALL) {
10540                final String parsedManifest = pkg.manifestDigest == null ? "null"
10541                        : pkg.manifestDigest.toString();
10542                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10543                        + parsedManifest);
10544            }
10545
10546            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10547                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10548                return;
10549            }
10550        } else if (DEBUG_INSTALL) {
10551            final String parsedManifest = pkg.manifestDigest == null
10552                    ? "null" : pkg.manifestDigest.toString();
10553            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10554        }
10555
10556        // Get rid of all references to package scan path via parser.
10557        pp = null;
10558        String oldCodePath = null;
10559        boolean systemApp = false;
10560        synchronized (mPackages) {
10561            // Check if installing already existing package
10562            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10563                String oldName = mSettings.mRenamedPackages.get(pkgName);
10564                if (pkg.mOriginalPackages != null
10565                        && pkg.mOriginalPackages.contains(oldName)
10566                        && mPackages.containsKey(oldName)) {
10567                    // This package is derived from an original package,
10568                    // and this device has been updating from that original
10569                    // name.  We must continue using the original name, so
10570                    // rename the new package here.
10571                    pkg.setPackageName(oldName);
10572                    pkgName = pkg.packageName;
10573                    replace = true;
10574                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10575                            + oldName + " pkgName=" + pkgName);
10576                } else if (mPackages.containsKey(pkgName)) {
10577                    // This package, under its official name, already exists
10578                    // on the device; we should replace it.
10579                    replace = true;
10580                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10581                }
10582            }
10583
10584            PackageSetting ps = mSettings.mPackages.get(pkgName);
10585            if (ps != null) {
10586                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10587
10588                // Quick sanity check that we're signed correctly if updating;
10589                // we'll check this again later when scanning, but we want to
10590                // bail early here before tripping over redefined permissions.
10591                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10592                    try {
10593                        verifySignaturesLP(ps, pkg);
10594                    } catch (PackageManagerException e) {
10595                        res.setError(e.error, e.getMessage());
10596                        return;
10597                    }
10598                } else {
10599                    if (!checkUpgradeKeySetLP(ps, pkg)) {
10600                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
10601                                + pkg.packageName + " upgrade keys do not match the "
10602                                + "previously installed version");
10603                        return;
10604                    }
10605                }
10606
10607                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10608                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10609                    systemApp = (ps.pkg.applicationInfo.flags &
10610                            ApplicationInfo.FLAG_SYSTEM) != 0;
10611                }
10612                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10613            }
10614
10615            // Check whether the newly-scanned package wants to define an already-defined perm
10616            int N = pkg.permissions.size();
10617            for (int i = N-1; i >= 0; i--) {
10618                PackageParser.Permission perm = pkg.permissions.get(i);
10619                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10620                if (bp != null) {
10621                    // If the defining package is signed with our cert, it's okay.  This
10622                    // also includes the "updating the same package" case, of course.
10623                    // "updating same package" could also involve key-rotation.
10624                    final boolean sigsOk;
10625                    if (!bp.sourcePackage.equals(pkg.packageName)
10626                            || !(bp.packageSetting instanceof PackageSetting)
10627                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10628                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10629                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10630                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10631                    } else {
10632                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10633                    }
10634                    if (!sigsOk) {
10635                        // If the owning package is the system itself, we log but allow
10636                        // install to proceed; we fail the install on all other permission
10637                        // redefinitions.
10638                        if (!bp.sourcePackage.equals("android")) {
10639                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10640                                    + pkg.packageName + " attempting to redeclare permission "
10641                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10642                            res.origPermission = perm.info.name;
10643                            res.origPackage = bp.sourcePackage;
10644                            return;
10645                        } else {
10646                            Slog.w(TAG, "Package " + pkg.packageName
10647                                    + " attempting to redeclare system permission "
10648                                    + perm.info.name + "; ignoring new declaration");
10649                            pkg.permissions.remove(i);
10650                        }
10651                    }
10652                }
10653            }
10654
10655        }
10656
10657        if (systemApp && onSd) {
10658            // Disable updates to system apps on sdcard
10659            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10660                    "Cannot install updates to system apps on sdcard");
10661            return;
10662        }
10663
10664        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10665            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10666            return;
10667        }
10668
10669        if (replace) {
10670            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10671                    installerPackageName, res);
10672        } else {
10673            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10674                    args.user, installerPackageName, res);
10675        }
10676        synchronized (mPackages) {
10677            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10678            if (ps != null) {
10679                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10680            }
10681        }
10682    }
10683
10684    private static boolean isForwardLocked(PackageParser.Package pkg) {
10685        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10686    }
10687
10688    private static boolean isForwardLocked(ApplicationInfo info) {
10689        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10690    }
10691
10692    private boolean isForwardLocked(PackageSetting ps) {
10693        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10694    }
10695
10696    private static boolean isMultiArch(PackageSetting ps) {
10697        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10698    }
10699
10700    private static boolean isMultiArch(ApplicationInfo info) {
10701        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10702    }
10703
10704    private static boolean isExternal(PackageParser.Package pkg) {
10705        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10706    }
10707
10708    private static boolean isExternal(PackageSetting ps) {
10709        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10710    }
10711
10712    private static boolean isExternal(ApplicationInfo info) {
10713        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10714    }
10715
10716    private static boolean isSystemApp(PackageParser.Package pkg) {
10717        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10718    }
10719
10720    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10721        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10722    }
10723
10724    private static boolean isSystemApp(ApplicationInfo info) {
10725        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10726    }
10727
10728    private static boolean isSystemApp(PackageSetting ps) {
10729        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10730    }
10731
10732    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10733        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10734    }
10735
10736    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10737        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10738    }
10739
10740    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10741        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10742    }
10743
10744    private int packageFlagsToInstallFlags(PackageSetting ps) {
10745        int installFlags = 0;
10746        if (isExternal(ps)) {
10747            installFlags |= PackageManager.INSTALL_EXTERNAL;
10748        }
10749        if (isForwardLocked(ps)) {
10750            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10751        }
10752        return installFlags;
10753    }
10754
10755    private void deleteTempPackageFiles() {
10756        final FilenameFilter filter = new FilenameFilter() {
10757            public boolean accept(File dir, String name) {
10758                return name.startsWith("vmdl") && name.endsWith(".tmp");
10759            }
10760        };
10761        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10762            file.delete();
10763        }
10764    }
10765
10766    @Override
10767    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10768            int flags) {
10769        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10770                flags);
10771    }
10772
10773    @Override
10774    public void deletePackage(final String packageName,
10775            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10776        mContext.enforceCallingOrSelfPermission(
10777                android.Manifest.permission.DELETE_PACKAGES, null);
10778        final int uid = Binder.getCallingUid();
10779        if (UserHandle.getUserId(uid) != userId) {
10780            mContext.enforceCallingPermission(
10781                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10782                    "deletePackage for user " + userId);
10783        }
10784        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10785            try {
10786                observer.onPackageDeleted(packageName,
10787                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10788            } catch (RemoteException re) {
10789            }
10790            return;
10791        }
10792
10793        boolean uninstallBlocked = false;
10794        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10795            int[] users = sUserManager.getUserIds();
10796            for (int i = 0; i < users.length; ++i) {
10797                if (getBlockUninstallForUser(packageName, users[i])) {
10798                    uninstallBlocked = true;
10799                    break;
10800                }
10801            }
10802        } else {
10803            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10804        }
10805        if (uninstallBlocked) {
10806            try {
10807                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10808                        null);
10809            } catch (RemoteException re) {
10810            }
10811            return;
10812        }
10813
10814        if (DEBUG_REMOVE) {
10815            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10816        }
10817        // Queue up an async operation since the package deletion may take a little while.
10818        mHandler.post(new Runnable() {
10819            public void run() {
10820                mHandler.removeCallbacks(this);
10821                final int returnCode = deletePackageX(packageName, userId, flags);
10822                if (observer != null) {
10823                    try {
10824                        observer.onPackageDeleted(packageName, returnCode, null);
10825                    } catch (RemoteException e) {
10826                        Log.i(TAG, "Observer no longer exists.");
10827                    } //end catch
10828                } //end if
10829            } //end run
10830        });
10831    }
10832
10833    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10834        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10835                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10836        try {
10837            if (dpm != null) {
10838                if (dpm.isDeviceOwner(packageName)) {
10839                    return true;
10840                }
10841                int[] users;
10842                if (userId == UserHandle.USER_ALL) {
10843                    users = sUserManager.getUserIds();
10844                } else {
10845                    users = new int[]{userId};
10846                }
10847                for (int i = 0; i < users.length; ++i) {
10848                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10849                        return true;
10850                    }
10851                }
10852            }
10853        } catch (RemoteException e) {
10854        }
10855        return false;
10856    }
10857
10858    /**
10859     *  This method is an internal method that could be get invoked either
10860     *  to delete an installed package or to clean up a failed installation.
10861     *  After deleting an installed package, a broadcast is sent to notify any
10862     *  listeners that the package has been installed. For cleaning up a failed
10863     *  installation, the broadcast is not necessary since the package's
10864     *  installation wouldn't have sent the initial broadcast either
10865     *  The key steps in deleting a package are
10866     *  deleting the package information in internal structures like mPackages,
10867     *  deleting the packages base directories through installd
10868     *  updating mSettings to reflect current status
10869     *  persisting settings for later use
10870     *  sending a broadcast if necessary
10871     */
10872    private int deletePackageX(String packageName, int userId, int flags) {
10873        final PackageRemovedInfo info = new PackageRemovedInfo();
10874        final boolean res;
10875
10876        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10877                ? UserHandle.ALL : new UserHandle(userId);
10878
10879        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10880            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10881            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10882        }
10883
10884        boolean removedForAllUsers = false;
10885        boolean systemUpdate = false;
10886
10887        // for the uninstall-updates case and restricted profiles, remember the per-
10888        // userhandle installed state
10889        int[] allUsers;
10890        boolean[] perUserInstalled;
10891        synchronized (mPackages) {
10892            PackageSetting ps = mSettings.mPackages.get(packageName);
10893            allUsers = sUserManager.getUserIds();
10894            perUserInstalled = new boolean[allUsers.length];
10895            for (int i = 0; i < allUsers.length; i++) {
10896                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10897            }
10898        }
10899
10900        synchronized (mInstallLock) {
10901            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10902            res = deletePackageLI(packageName, removeForUser,
10903                    true, allUsers, perUserInstalled,
10904                    flags | REMOVE_CHATTY, info, true);
10905            systemUpdate = info.isRemovedPackageSystemUpdate;
10906            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10907                removedForAllUsers = true;
10908            }
10909            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10910                    + " removedForAllUsers=" + removedForAllUsers);
10911        }
10912
10913        if (res) {
10914            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10915
10916            // If the removed package was a system update, the old system package
10917            // was re-enabled; we need to broadcast this information
10918            if (systemUpdate) {
10919                Bundle extras = new Bundle(1);
10920                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10921                        ? info.removedAppId : info.uid);
10922                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10923
10924                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10925                        extras, null, null, null);
10926                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10927                        extras, null, null, null);
10928                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10929                        null, packageName, null, null);
10930            }
10931        }
10932        // Force a gc here.
10933        Runtime.getRuntime().gc();
10934        // Delete the resources here after sending the broadcast to let
10935        // other processes clean up before deleting resources.
10936        if (info.args != null) {
10937            synchronized (mInstallLock) {
10938                info.args.doPostDeleteLI(true);
10939            }
10940        }
10941
10942        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10943    }
10944
10945    static class PackageRemovedInfo {
10946        String removedPackage;
10947        int uid = -1;
10948        int removedAppId = -1;
10949        int[] removedUsers = null;
10950        boolean isRemovedPackageSystemUpdate = false;
10951        // Clean up resources deleted packages.
10952        InstallArgs args = null;
10953
10954        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10955            Bundle extras = new Bundle(1);
10956            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10957            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10958            if (replacing) {
10959                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10960            }
10961            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10962            if (removedPackage != null) {
10963                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10964                        extras, null, null, removedUsers);
10965                if (fullRemove && !replacing) {
10966                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10967                            extras, null, null, removedUsers);
10968                }
10969            }
10970            if (removedAppId >= 0) {
10971                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10972                        removedUsers);
10973            }
10974        }
10975    }
10976
10977    /*
10978     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10979     * flag is not set, the data directory is removed as well.
10980     * make sure this flag is set for partially installed apps. If not its meaningless to
10981     * delete a partially installed application.
10982     */
10983    private void removePackageDataLI(PackageSetting ps,
10984            int[] allUserHandles, boolean[] perUserInstalled,
10985            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10986        String packageName = ps.name;
10987        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10988        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10989        // Retrieve object to delete permissions for shared user later on
10990        final PackageSetting deletedPs;
10991        // reader
10992        synchronized (mPackages) {
10993            deletedPs = mSettings.mPackages.get(packageName);
10994            if (outInfo != null) {
10995                outInfo.removedPackage = packageName;
10996                outInfo.removedUsers = deletedPs != null
10997                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10998                        : null;
10999            }
11000        }
11001        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11002            removeDataDirsLI(packageName);
11003            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
11004        }
11005        // writer
11006        synchronized (mPackages) {
11007            if (deletedPs != null) {
11008                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11009                    if (outInfo != null) {
11010                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
11011                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
11012                    }
11013                    if (deletedPs != null) {
11014                        updatePermissionsLPw(deletedPs.name, null, 0);
11015                        if (deletedPs.sharedUser != null) {
11016                            // remove permissions associated with package
11017                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
11018                        }
11019                    }
11020                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
11021                }
11022                // make sure to preserve per-user disabled state if this removal was just
11023                // a downgrade of a system app to the factory package
11024                if (allUserHandles != null && perUserInstalled != null) {
11025                    if (DEBUG_REMOVE) {
11026                        Slog.d(TAG, "Propagating install state across downgrade");
11027                    }
11028                    for (int i = 0; i < allUserHandles.length; i++) {
11029                        if (DEBUG_REMOVE) {
11030                            Slog.d(TAG, "    user " + allUserHandles[i]
11031                                    + " => " + perUserInstalled[i]);
11032                        }
11033                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11034                    }
11035                }
11036            }
11037            // can downgrade to reader
11038            if (writeSettings) {
11039                // Save settings now
11040                mSettings.writeLPr();
11041            }
11042        }
11043        if (outInfo != null) {
11044            // A user ID was deleted here. Go through all users and remove it
11045            // from KeyStore.
11046            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
11047        }
11048    }
11049
11050    static boolean locationIsPrivileged(File path) {
11051        try {
11052            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
11053                    .getCanonicalPath();
11054            return path.getCanonicalPath().startsWith(privilegedAppDir);
11055        } catch (IOException e) {
11056            Slog.e(TAG, "Unable to access code path " + path);
11057        }
11058        return false;
11059    }
11060
11061    /*
11062     * Tries to delete system package.
11063     */
11064    private boolean deleteSystemPackageLI(PackageSetting newPs,
11065            int[] allUserHandles, boolean[] perUserInstalled,
11066            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
11067        final boolean applyUserRestrictions
11068                = (allUserHandles != null) && (perUserInstalled != null);
11069        PackageSetting disabledPs = null;
11070        // Confirm if the system package has been updated
11071        // An updated system app can be deleted. This will also have to restore
11072        // the system pkg from system partition
11073        // reader
11074        synchronized (mPackages) {
11075            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
11076        }
11077        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
11078                + " disabledPs=" + disabledPs);
11079        if (disabledPs == null) {
11080            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
11081            return false;
11082        } else if (DEBUG_REMOVE) {
11083            Slog.d(TAG, "Deleting system pkg from data partition");
11084        }
11085        if (DEBUG_REMOVE) {
11086            if (applyUserRestrictions) {
11087                Slog.d(TAG, "Remembering install states:");
11088                for (int i = 0; i < allUserHandles.length; i++) {
11089                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
11090                }
11091            }
11092        }
11093        // Delete the updated package
11094        outInfo.isRemovedPackageSystemUpdate = true;
11095        if (disabledPs.versionCode < newPs.versionCode) {
11096            // Delete data for downgrades
11097            flags &= ~PackageManager.DELETE_KEEP_DATA;
11098        } else {
11099            // Preserve data by setting flag
11100            flags |= PackageManager.DELETE_KEEP_DATA;
11101        }
11102        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
11103                allUserHandles, perUserInstalled, outInfo, writeSettings);
11104        if (!ret) {
11105            return false;
11106        }
11107        // writer
11108        synchronized (mPackages) {
11109            // Reinstate the old system package
11110            mSettings.enableSystemPackageLPw(newPs.name);
11111            // Remove any native libraries from the upgraded package.
11112            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
11113        }
11114        // Install the system package
11115        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
11116        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
11117        if (locationIsPrivileged(disabledPs.codePath)) {
11118            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11119        }
11120
11121        final PackageParser.Package newPkg;
11122        try {
11123            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
11124        } catch (PackageManagerException e) {
11125            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
11126            return false;
11127        }
11128
11129        // writer
11130        synchronized (mPackages) {
11131            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
11132            updatePermissionsLPw(newPkg.packageName, newPkg,
11133                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
11134            if (applyUserRestrictions) {
11135                if (DEBUG_REMOVE) {
11136                    Slog.d(TAG, "Propagating install state across reinstall");
11137                }
11138                for (int i = 0; i < allUserHandles.length; i++) {
11139                    if (DEBUG_REMOVE) {
11140                        Slog.d(TAG, "    user " + allUserHandles[i]
11141                                + " => " + perUserInstalled[i]);
11142                    }
11143                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11144                }
11145                // Regardless of writeSettings we need to ensure that this restriction
11146                // state propagation is persisted
11147                mSettings.writeAllUsersPackageRestrictionsLPr();
11148            }
11149            // can downgrade to reader here
11150            if (writeSettings) {
11151                mSettings.writeLPr();
11152            }
11153        }
11154        return true;
11155    }
11156
11157    private boolean deleteInstalledPackageLI(PackageSetting ps,
11158            boolean deleteCodeAndResources, int flags,
11159            int[] allUserHandles, boolean[] perUserInstalled,
11160            PackageRemovedInfo outInfo, boolean writeSettings) {
11161        if (outInfo != null) {
11162            outInfo.uid = ps.appId;
11163        }
11164
11165        // Delete package data from internal structures and also remove data if flag is set
11166        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
11167
11168        // Delete application code and resources
11169        if (deleteCodeAndResources && (outInfo != null)) {
11170            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
11171                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
11172                    getAppDexInstructionSets(ps));
11173            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
11174        }
11175        return true;
11176    }
11177
11178    @Override
11179    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11180            int userId) {
11181        mContext.enforceCallingOrSelfPermission(
11182                android.Manifest.permission.DELETE_PACKAGES, null);
11183        synchronized (mPackages) {
11184            PackageSetting ps = mSettings.mPackages.get(packageName);
11185            if (ps == null) {
11186                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11187                return false;
11188            }
11189            if (!ps.getInstalled(userId)) {
11190                // Can't block uninstall for an app that is not installed or enabled.
11191                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11192                return false;
11193            }
11194            ps.setBlockUninstall(blockUninstall, userId);
11195            mSettings.writePackageRestrictionsLPr(userId);
11196        }
11197        return true;
11198    }
11199
11200    @Override
11201    public boolean getBlockUninstallForUser(String packageName, int userId) {
11202        synchronized (mPackages) {
11203            PackageSetting ps = mSettings.mPackages.get(packageName);
11204            if (ps == null) {
11205                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11206                return false;
11207            }
11208            return ps.getBlockUninstall(userId);
11209        }
11210    }
11211
11212    /*
11213     * This method handles package deletion in general
11214     */
11215    private boolean deletePackageLI(String packageName, UserHandle user,
11216            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11217            int flags, PackageRemovedInfo outInfo,
11218            boolean writeSettings) {
11219        if (packageName == null) {
11220            Slog.w(TAG, "Attempt to delete null packageName.");
11221            return false;
11222        }
11223        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11224        PackageSetting ps;
11225        boolean dataOnly = false;
11226        int removeUser = -1;
11227        int appId = -1;
11228        synchronized (mPackages) {
11229            ps = mSettings.mPackages.get(packageName);
11230            if (ps == null) {
11231                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11232                return false;
11233            }
11234            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11235                    && user.getIdentifier() != UserHandle.USER_ALL) {
11236                // The caller is asking that the package only be deleted for a single
11237                // user.  To do this, we just mark its uninstalled state and delete
11238                // its data.  If this is a system app, we only allow this to happen if
11239                // they have set the special DELETE_SYSTEM_APP which requests different
11240                // semantics than normal for uninstalling system apps.
11241                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11242                ps.setUserState(user.getIdentifier(),
11243                        COMPONENT_ENABLED_STATE_DEFAULT,
11244                        false, //installed
11245                        true,  //stopped
11246                        true,  //notLaunched
11247                        false, //hidden
11248                        null, null, null,
11249                        false // blockUninstall
11250                        );
11251                if (!isSystemApp(ps)) {
11252                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11253                        // Other user still have this package installed, so all
11254                        // we need to do is clear this user's data and save that
11255                        // it is uninstalled.
11256                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11257                        removeUser = user.getIdentifier();
11258                        appId = ps.appId;
11259                        mSettings.writePackageRestrictionsLPr(removeUser);
11260                    } else {
11261                        // We need to set it back to 'installed' so the uninstall
11262                        // broadcasts will be sent correctly.
11263                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11264                        ps.setInstalled(true, user.getIdentifier());
11265                    }
11266                } else {
11267                    // This is a system app, so we assume that the
11268                    // other users still have this package installed, so all
11269                    // we need to do is clear this user's data and save that
11270                    // it is uninstalled.
11271                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11272                    removeUser = user.getIdentifier();
11273                    appId = ps.appId;
11274                    mSettings.writePackageRestrictionsLPr(removeUser);
11275                }
11276            }
11277        }
11278
11279        if (removeUser >= 0) {
11280            // From above, we determined that we are deleting this only
11281            // for a single user.  Continue the work here.
11282            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11283            if (outInfo != null) {
11284                outInfo.removedPackage = packageName;
11285                outInfo.removedAppId = appId;
11286                outInfo.removedUsers = new int[] {removeUser};
11287            }
11288            mInstaller.clearUserData(packageName, removeUser);
11289            removeKeystoreDataIfNeeded(removeUser, appId);
11290            schedulePackageCleaning(packageName, removeUser, false);
11291            return true;
11292        }
11293
11294        if (dataOnly) {
11295            // Delete application data first
11296            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11297            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11298            return true;
11299        }
11300
11301        boolean ret = false;
11302        if (isSystemApp(ps)) {
11303            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11304            // When an updated system application is deleted we delete the existing resources as well and
11305            // fall back to existing code in system partition
11306            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11307                    flags, outInfo, writeSettings);
11308        } else {
11309            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11310            // Kill application pre-emptively especially for apps on sd.
11311            killApplication(packageName, ps.appId, "uninstall pkg");
11312            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11313                    allUserHandles, perUserInstalled,
11314                    outInfo, writeSettings);
11315        }
11316
11317        return ret;
11318    }
11319
11320    private final class ClearStorageConnection implements ServiceConnection {
11321        IMediaContainerService mContainerService;
11322
11323        @Override
11324        public void onServiceConnected(ComponentName name, IBinder service) {
11325            synchronized (this) {
11326                mContainerService = IMediaContainerService.Stub.asInterface(service);
11327                notifyAll();
11328            }
11329        }
11330
11331        @Override
11332        public void onServiceDisconnected(ComponentName name) {
11333        }
11334    }
11335
11336    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11337        final boolean mounted;
11338        if (Environment.isExternalStorageEmulated()) {
11339            mounted = true;
11340        } else {
11341            final String status = Environment.getExternalStorageState();
11342
11343            mounted = status.equals(Environment.MEDIA_MOUNTED)
11344                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11345        }
11346
11347        if (!mounted) {
11348            return;
11349        }
11350
11351        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11352        int[] users;
11353        if (userId == UserHandle.USER_ALL) {
11354            users = sUserManager.getUserIds();
11355        } else {
11356            users = new int[] { userId };
11357        }
11358        final ClearStorageConnection conn = new ClearStorageConnection();
11359        if (mContext.bindServiceAsUser(
11360                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11361            try {
11362                for (int curUser : users) {
11363                    long timeout = SystemClock.uptimeMillis() + 5000;
11364                    synchronized (conn) {
11365                        long now = SystemClock.uptimeMillis();
11366                        while (conn.mContainerService == null && now < timeout) {
11367                            try {
11368                                conn.wait(timeout - now);
11369                            } catch (InterruptedException e) {
11370                            }
11371                        }
11372                    }
11373                    if (conn.mContainerService == null) {
11374                        return;
11375                    }
11376
11377                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11378                    clearDirectory(conn.mContainerService,
11379                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11380                    if (allData) {
11381                        clearDirectory(conn.mContainerService,
11382                                userEnv.buildExternalStorageAppDataDirs(packageName));
11383                        clearDirectory(conn.mContainerService,
11384                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11385                    }
11386                }
11387            } finally {
11388                mContext.unbindService(conn);
11389            }
11390        }
11391    }
11392
11393    @Override
11394    public void clearApplicationUserData(final String packageName,
11395            final IPackageDataObserver observer, final int userId) {
11396        mContext.enforceCallingOrSelfPermission(
11397                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11398        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11399        // Queue up an async operation since the package deletion may take a little while.
11400        mHandler.post(new Runnable() {
11401            public void run() {
11402                mHandler.removeCallbacks(this);
11403                final boolean succeeded;
11404                synchronized (mInstallLock) {
11405                    succeeded = clearApplicationUserDataLI(packageName, userId);
11406                }
11407                clearExternalStorageDataSync(packageName, userId, true);
11408                if (succeeded) {
11409                    // invoke DeviceStorageMonitor's update method to clear any notifications
11410                    DeviceStorageMonitorInternal
11411                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11412                    if (dsm != null) {
11413                        dsm.checkMemory();
11414                    }
11415                }
11416                if(observer != null) {
11417                    try {
11418                        observer.onRemoveCompleted(packageName, succeeded);
11419                    } catch (RemoteException e) {
11420                        Log.i(TAG, "Observer no longer exists.");
11421                    }
11422                } //end if observer
11423            } //end run
11424        });
11425    }
11426
11427    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11428        if (packageName == null) {
11429            Slog.w(TAG, "Attempt to delete null packageName.");
11430            return false;
11431        }
11432
11433        // Try finding details about the requested package
11434        PackageParser.Package pkg;
11435        synchronized (mPackages) {
11436            pkg = mPackages.get(packageName);
11437            if (pkg == null) {
11438                final PackageSetting ps = mSettings.mPackages.get(packageName);
11439                if (ps != null) {
11440                    pkg = ps.pkg;
11441                }
11442            }
11443        }
11444
11445        if (pkg == null) {
11446            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11447        }
11448
11449        // Always delete data directories for package, even if we found no other
11450        // record of app. This helps users recover from UID mismatches without
11451        // resorting to a full data wipe.
11452        int retCode = mInstaller.clearUserData(packageName, userId);
11453        if (retCode < 0) {
11454            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11455            return false;
11456        }
11457
11458        if (pkg == null) {
11459            return false;
11460        }
11461
11462        if (pkg != null && pkg.applicationInfo != null) {
11463            final int appId = pkg.applicationInfo.uid;
11464            removeKeystoreDataIfNeeded(userId, appId);
11465        }
11466
11467        // Create a native library symlink only if we have native libraries
11468        // and if the native libraries are 32 bit libraries. We do not provide
11469        // this symlink for 64 bit libraries.
11470        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11471                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11472            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11473            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11474                Slog.w(TAG, "Failed linking native library dir");
11475                return false;
11476            }
11477        }
11478
11479        return true;
11480    }
11481
11482    /**
11483     * Remove entries from the keystore daemon. Will only remove it if the
11484     * {@code appId} is valid.
11485     */
11486    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11487        if (appId < 0) {
11488            return;
11489        }
11490
11491        final KeyStore keyStore = KeyStore.getInstance();
11492        if (keyStore != null) {
11493            if (userId == UserHandle.USER_ALL) {
11494                for (final int individual : sUserManager.getUserIds()) {
11495                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11496                }
11497            } else {
11498                keyStore.clearUid(UserHandle.getUid(userId, appId));
11499            }
11500        } else {
11501            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11502        }
11503    }
11504
11505    @Override
11506    public void deleteApplicationCacheFiles(final String packageName,
11507            final IPackageDataObserver observer) {
11508        mContext.enforceCallingOrSelfPermission(
11509                android.Manifest.permission.DELETE_CACHE_FILES, null);
11510        // Queue up an async operation since the package deletion may take a little while.
11511        final int userId = UserHandle.getCallingUserId();
11512        mHandler.post(new Runnable() {
11513            public void run() {
11514                mHandler.removeCallbacks(this);
11515                final boolean succeded;
11516                synchronized (mInstallLock) {
11517                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11518                }
11519                clearExternalStorageDataSync(packageName, userId, false);
11520                if(observer != null) {
11521                    try {
11522                        observer.onRemoveCompleted(packageName, succeded);
11523                    } catch (RemoteException e) {
11524                        Log.i(TAG, "Observer no longer exists.");
11525                    }
11526                } //end if observer
11527            } //end run
11528        });
11529    }
11530
11531    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11532        if (packageName == null) {
11533            Slog.w(TAG, "Attempt to delete null packageName.");
11534            return false;
11535        }
11536        PackageParser.Package p;
11537        synchronized (mPackages) {
11538            p = mPackages.get(packageName);
11539        }
11540        if (p == null) {
11541            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11542            return false;
11543        }
11544        final ApplicationInfo applicationInfo = p.applicationInfo;
11545        if (applicationInfo == null) {
11546            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11547            return false;
11548        }
11549        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11550        if (retCode < 0) {
11551            Slog.w(TAG, "Couldn't remove cache files for package: "
11552                       + packageName + " u" + userId);
11553            return false;
11554        }
11555        return true;
11556    }
11557
11558    @Override
11559    public void getPackageSizeInfo(final String packageName, int userHandle,
11560            final IPackageStatsObserver observer) {
11561        mContext.enforceCallingOrSelfPermission(
11562                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11563        if (packageName == null) {
11564            throw new IllegalArgumentException("Attempt to get size of null packageName");
11565        }
11566
11567        PackageStats stats = new PackageStats(packageName, userHandle);
11568
11569        /*
11570         * Queue up an async operation since the package measurement may take a
11571         * little while.
11572         */
11573        Message msg = mHandler.obtainMessage(INIT_COPY);
11574        msg.obj = new MeasureParams(stats, observer);
11575        mHandler.sendMessage(msg);
11576    }
11577
11578    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11579            PackageStats pStats) {
11580        if (packageName == null) {
11581            Slog.w(TAG, "Attempt to get size of null packageName.");
11582            return false;
11583        }
11584        PackageParser.Package p;
11585        boolean dataOnly = false;
11586        String libDirRoot = null;
11587        String asecPath = null;
11588        PackageSetting ps = null;
11589        synchronized (mPackages) {
11590            p = mPackages.get(packageName);
11591            ps = mSettings.mPackages.get(packageName);
11592            if(p == null) {
11593                dataOnly = true;
11594                if((ps == null) || (ps.pkg == null)) {
11595                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11596                    return false;
11597                }
11598                p = ps.pkg;
11599            }
11600            if (ps != null) {
11601                libDirRoot = ps.legacyNativeLibraryPathString;
11602            }
11603            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11604                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11605                if (secureContainerId != null) {
11606                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11607                }
11608            }
11609        }
11610        String publicSrcDir = null;
11611        if(!dataOnly) {
11612            final ApplicationInfo applicationInfo = p.applicationInfo;
11613            if (applicationInfo == null) {
11614                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11615                return false;
11616            }
11617            if (isForwardLocked(p)) {
11618                publicSrcDir = applicationInfo.getBaseResourcePath();
11619            }
11620        }
11621        // TODO: extend to measure size of split APKs
11622        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11623        // not just the first level.
11624        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11625        // just the primary.
11626        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11627        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11628                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11629        if (res < 0) {
11630            return false;
11631        }
11632
11633        // Fix-up for forward-locked applications in ASEC containers.
11634        if (!isExternal(p)) {
11635            pStats.codeSize += pStats.externalCodeSize;
11636            pStats.externalCodeSize = 0L;
11637        }
11638
11639        return true;
11640    }
11641
11642
11643    @Override
11644    public void addPackageToPreferred(String packageName) {
11645        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11646    }
11647
11648    @Override
11649    public void removePackageFromPreferred(String packageName) {
11650        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11651    }
11652
11653    @Override
11654    public List<PackageInfo> getPreferredPackages(int flags) {
11655        return new ArrayList<PackageInfo>();
11656    }
11657
11658    private int getUidTargetSdkVersionLockedLPr(int uid) {
11659        Object obj = mSettings.getUserIdLPr(uid);
11660        if (obj instanceof SharedUserSetting) {
11661            final SharedUserSetting sus = (SharedUserSetting) obj;
11662            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11663            final Iterator<PackageSetting> it = sus.packages.iterator();
11664            while (it.hasNext()) {
11665                final PackageSetting ps = it.next();
11666                if (ps.pkg != null) {
11667                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11668                    if (v < vers) vers = v;
11669                }
11670            }
11671            return vers;
11672        } else if (obj instanceof PackageSetting) {
11673            final PackageSetting ps = (PackageSetting) obj;
11674            if (ps.pkg != null) {
11675                return ps.pkg.applicationInfo.targetSdkVersion;
11676            }
11677        }
11678        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11679    }
11680
11681    @Override
11682    public void addPreferredActivity(IntentFilter filter, int match,
11683            ComponentName[] set, ComponentName activity, int userId) {
11684        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11685                "Adding preferred");
11686    }
11687
11688    private void addPreferredActivityInternal(IntentFilter filter, int match,
11689            ComponentName[] set, ComponentName activity, boolean always, int userId,
11690            String opname) {
11691        // writer
11692        int callingUid = Binder.getCallingUid();
11693        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11694        if (filter.countActions() == 0) {
11695            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11696            return;
11697        }
11698        synchronized (mPackages) {
11699            if (mContext.checkCallingOrSelfPermission(
11700                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11701                    != PackageManager.PERMISSION_GRANTED) {
11702                if (getUidTargetSdkVersionLockedLPr(callingUid)
11703                        < Build.VERSION_CODES.FROYO) {
11704                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11705                            + callingUid);
11706                    return;
11707                }
11708                mContext.enforceCallingOrSelfPermission(
11709                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11710            }
11711
11712            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11713            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11714                    + userId + ":");
11715            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11716            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11717            scheduleWritePackageRestrictionsLocked(userId);
11718        }
11719    }
11720
11721    @Override
11722    public void replacePreferredActivity(IntentFilter filter, int match,
11723            ComponentName[] set, ComponentName activity, int userId) {
11724        if (filter.countActions() != 1) {
11725            throw new IllegalArgumentException(
11726                    "replacePreferredActivity expects filter to have only 1 action.");
11727        }
11728        if (filter.countDataAuthorities() != 0
11729                || filter.countDataPaths() != 0
11730                || filter.countDataSchemes() > 1
11731                || filter.countDataTypes() != 0) {
11732            throw new IllegalArgumentException(
11733                    "replacePreferredActivity expects filter to have no data authorities, " +
11734                    "paths, or types; and at most one scheme.");
11735        }
11736
11737        final int callingUid = Binder.getCallingUid();
11738        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11739        synchronized (mPackages) {
11740            if (mContext.checkCallingOrSelfPermission(
11741                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11742                    != PackageManager.PERMISSION_GRANTED) {
11743                if (getUidTargetSdkVersionLockedLPr(callingUid)
11744                        < Build.VERSION_CODES.FROYO) {
11745                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11746                            + Binder.getCallingUid());
11747                    return;
11748                }
11749                mContext.enforceCallingOrSelfPermission(
11750                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11751            }
11752
11753            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11754            if (pir != null) {
11755                // Get all of the existing entries that exactly match this filter.
11756                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11757                if (existing != null && existing.size() == 1) {
11758                    PreferredActivity cur = existing.get(0);
11759                    if (DEBUG_PREFERRED) {
11760                        Slog.i(TAG, "Checking replace of preferred:");
11761                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11762                        if (!cur.mPref.mAlways) {
11763                            Slog.i(TAG, "  -- CUR; not mAlways!");
11764                        } else {
11765                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11766                            Slog.i(TAG, "  -- CUR: mSet="
11767                                    + Arrays.toString(cur.mPref.mSetComponents));
11768                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11769                            Slog.i(TAG, "  -- NEW: mMatch="
11770                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11771                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11772                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11773                        }
11774                    }
11775                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11776                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11777                            && cur.mPref.sameSet(set)) {
11778                        // Setting the preferred activity to what it happens to be already
11779                        if (DEBUG_PREFERRED) {
11780                            Slog.i(TAG, "Replacing with same preferred activity "
11781                                    + cur.mPref.mShortComponent + " for user "
11782                                    + userId + ":");
11783                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11784                        }
11785                        return;
11786                    }
11787                }
11788
11789                if (existing != null) {
11790                    if (DEBUG_PREFERRED) {
11791                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11792                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11793                    }
11794                    for (int i = 0; i < existing.size(); i++) {
11795                        PreferredActivity pa = existing.get(i);
11796                        if (DEBUG_PREFERRED) {
11797                            Slog.i(TAG, "Removing existing preferred activity "
11798                                    + pa.mPref.mComponent + ":");
11799                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11800                        }
11801                        pir.removeFilter(pa);
11802                    }
11803                }
11804            }
11805            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11806                    "Replacing preferred");
11807        }
11808    }
11809
11810    @Override
11811    public void clearPackagePreferredActivities(String packageName) {
11812        final int uid = Binder.getCallingUid();
11813        // writer
11814        synchronized (mPackages) {
11815            PackageParser.Package pkg = mPackages.get(packageName);
11816            if (pkg == null || pkg.applicationInfo.uid != uid) {
11817                if (mContext.checkCallingOrSelfPermission(
11818                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11819                        != PackageManager.PERMISSION_GRANTED) {
11820                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11821                            < Build.VERSION_CODES.FROYO) {
11822                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11823                                + Binder.getCallingUid());
11824                        return;
11825                    }
11826                    mContext.enforceCallingOrSelfPermission(
11827                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11828                }
11829            }
11830
11831            int user = UserHandle.getCallingUserId();
11832            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11833                scheduleWritePackageRestrictionsLocked(user);
11834            }
11835        }
11836    }
11837
11838    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11839    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11840        ArrayList<PreferredActivity> removed = null;
11841        boolean changed = false;
11842        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11843            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11844            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11845            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11846                continue;
11847            }
11848            Iterator<PreferredActivity> it = pir.filterIterator();
11849            while (it.hasNext()) {
11850                PreferredActivity pa = it.next();
11851                // Mark entry for removal only if it matches the package name
11852                // and the entry is of type "always".
11853                if (packageName == null ||
11854                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11855                                && pa.mPref.mAlways)) {
11856                    if (removed == null) {
11857                        removed = new ArrayList<PreferredActivity>();
11858                    }
11859                    removed.add(pa);
11860                }
11861            }
11862            if (removed != null) {
11863                for (int j=0; j<removed.size(); j++) {
11864                    PreferredActivity pa = removed.get(j);
11865                    pir.removeFilter(pa);
11866                }
11867                changed = true;
11868            }
11869        }
11870        return changed;
11871    }
11872
11873    @Override
11874    public void resetPreferredActivities(int userId) {
11875        /* TODO: Actually use userId. Why is it being passed in? */
11876        mContext.enforceCallingOrSelfPermission(
11877                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11878        // writer
11879        synchronized (mPackages) {
11880            int user = UserHandle.getCallingUserId();
11881            clearPackagePreferredActivitiesLPw(null, user);
11882            mSettings.readDefaultPreferredAppsLPw(this, user);
11883            scheduleWritePackageRestrictionsLocked(user);
11884        }
11885    }
11886
11887    @Override
11888    public int getPreferredActivities(List<IntentFilter> outFilters,
11889            List<ComponentName> outActivities, String packageName) {
11890
11891        int num = 0;
11892        final int userId = UserHandle.getCallingUserId();
11893        // reader
11894        synchronized (mPackages) {
11895            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11896            if (pir != null) {
11897                final Iterator<PreferredActivity> it = pir.filterIterator();
11898                while (it.hasNext()) {
11899                    final PreferredActivity pa = it.next();
11900                    if (packageName == null
11901                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11902                                    && pa.mPref.mAlways)) {
11903                        if (outFilters != null) {
11904                            outFilters.add(new IntentFilter(pa));
11905                        }
11906                        if (outActivities != null) {
11907                            outActivities.add(pa.mPref.mComponent);
11908                        }
11909                    }
11910                }
11911            }
11912        }
11913
11914        return num;
11915    }
11916
11917    @Override
11918    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11919            int userId) {
11920        int callingUid = Binder.getCallingUid();
11921        if (callingUid != Process.SYSTEM_UID) {
11922            throw new SecurityException(
11923                    "addPersistentPreferredActivity can only be run by the system");
11924        }
11925        if (filter.countActions() == 0) {
11926            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11927            return;
11928        }
11929        synchronized (mPackages) {
11930            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11931                    " :");
11932            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11933            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11934                    new PersistentPreferredActivity(filter, activity));
11935            scheduleWritePackageRestrictionsLocked(userId);
11936        }
11937    }
11938
11939    @Override
11940    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11941        int callingUid = Binder.getCallingUid();
11942        if (callingUid != Process.SYSTEM_UID) {
11943            throw new SecurityException(
11944                    "clearPackagePersistentPreferredActivities can only be run by the system");
11945        }
11946        ArrayList<PersistentPreferredActivity> removed = null;
11947        boolean changed = false;
11948        synchronized (mPackages) {
11949            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11950                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11951                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11952                        .valueAt(i);
11953                if (userId != thisUserId) {
11954                    continue;
11955                }
11956                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11957                while (it.hasNext()) {
11958                    PersistentPreferredActivity ppa = it.next();
11959                    // Mark entry for removal only if it matches the package name.
11960                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11961                        if (removed == null) {
11962                            removed = new ArrayList<PersistentPreferredActivity>();
11963                        }
11964                        removed.add(ppa);
11965                    }
11966                }
11967                if (removed != null) {
11968                    for (int j=0; j<removed.size(); j++) {
11969                        PersistentPreferredActivity ppa = removed.get(j);
11970                        ppir.removeFilter(ppa);
11971                    }
11972                    changed = true;
11973                }
11974            }
11975
11976            if (changed) {
11977                scheduleWritePackageRestrictionsLocked(userId);
11978            }
11979        }
11980    }
11981
11982    @Override
11983    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11984            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11985        mContext.enforceCallingOrSelfPermission(
11986                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11987        int callingUid = Binder.getCallingUid();
11988        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11989        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11990        if (intentFilter.countActions() == 0) {
11991            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11992            return;
11993        }
11994        synchronized (mPackages) {
11995            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
11996                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11997            CrossProfileIntentResolver resolver =
11998                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11999            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
12000            // We have all those whose filter is equal. Now checking if the rest is equal as well.
12001            if (existing != null) {
12002                int size = existing.size();
12003                for (int i = 0; i < size; i++) {
12004                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
12005                        return;
12006                    }
12007                }
12008            }
12009            resolver.addFilter(newFilter);
12010            scheduleWritePackageRestrictionsLocked(sourceUserId);
12011        }
12012    }
12013
12014    @Override
12015    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
12016            int ownerUserId) {
12017        mContext.enforceCallingOrSelfPermission(
12018                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12019        int callingUid = Binder.getCallingUid();
12020        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
12021        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12022        int callingUserId = UserHandle.getUserId(callingUid);
12023        synchronized (mPackages) {
12024            CrossProfileIntentResolver resolver =
12025                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12026            ArraySet<CrossProfileIntentFilter> set =
12027                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
12028            for (CrossProfileIntentFilter filter : set) {
12029                if (filter.getOwnerPackage().equals(ownerPackage)
12030                        && filter.getOwnerUserId() == callingUserId) {
12031                    resolver.removeFilter(filter);
12032                }
12033            }
12034            scheduleWritePackageRestrictionsLocked(sourceUserId);
12035        }
12036    }
12037
12038    // Enforcing that callingUid is owning pkg on userId
12039    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
12040        // The system owns everything.
12041        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
12042            return;
12043        }
12044        int callingUserId = UserHandle.getUserId(callingUid);
12045        if (callingUserId != userId) {
12046            throw new SecurityException("calling uid " + callingUid
12047                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
12048                    + callingUserId);
12049        }
12050        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
12051        if (pi == null) {
12052            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
12053                    + callingUserId);
12054        }
12055        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
12056            throw new SecurityException("Calling uid " + callingUid
12057                    + " does not own package " + pkg);
12058        }
12059    }
12060
12061    @Override
12062    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
12063        Intent intent = new Intent(Intent.ACTION_MAIN);
12064        intent.addCategory(Intent.CATEGORY_HOME);
12065
12066        final int callingUserId = UserHandle.getCallingUserId();
12067        List<ResolveInfo> list = queryIntentActivities(intent, null,
12068                PackageManager.GET_META_DATA, callingUserId);
12069        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
12070                true, false, false, callingUserId);
12071
12072        allHomeCandidates.clear();
12073        if (list != null) {
12074            for (ResolveInfo ri : list) {
12075                allHomeCandidates.add(ri);
12076            }
12077        }
12078        return (preferred == null || preferred.activityInfo == null)
12079                ? null
12080                : new ComponentName(preferred.activityInfo.packageName,
12081                        preferred.activityInfo.name);
12082    }
12083
12084    @Override
12085    public void setApplicationEnabledSetting(String appPackageName,
12086            int newState, int flags, int userId, String callingPackage) {
12087        if (!sUserManager.exists(userId)) return;
12088        if (callingPackage == null) {
12089            callingPackage = Integer.toString(Binder.getCallingUid());
12090        }
12091        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
12092    }
12093
12094    @Override
12095    public void setComponentEnabledSetting(ComponentName componentName,
12096            int newState, int flags, int userId) {
12097        if (!sUserManager.exists(userId)) return;
12098        setEnabledSetting(componentName.getPackageName(),
12099                componentName.getClassName(), newState, flags, userId, null);
12100    }
12101
12102    private void setEnabledSetting(final String packageName, String className, int newState,
12103            final int flags, int userId, String callingPackage) {
12104        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
12105              || newState == COMPONENT_ENABLED_STATE_ENABLED
12106              || newState == COMPONENT_ENABLED_STATE_DISABLED
12107              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
12108              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
12109            throw new IllegalArgumentException("Invalid new component state: "
12110                    + newState);
12111        }
12112        PackageSetting pkgSetting;
12113        final int uid = Binder.getCallingUid();
12114        final int permission = mContext.checkCallingOrSelfPermission(
12115                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12116        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
12117        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12118        boolean sendNow = false;
12119        boolean isApp = (className == null);
12120        String componentName = isApp ? packageName : className;
12121        int packageUid = -1;
12122        ArrayList<String> components;
12123
12124        // writer
12125        synchronized (mPackages) {
12126            pkgSetting = mSettings.mPackages.get(packageName);
12127            if (pkgSetting == null) {
12128                if (className == null) {
12129                    throw new IllegalArgumentException(
12130                            "Unknown package: " + packageName);
12131                }
12132                throw new IllegalArgumentException(
12133                        "Unknown component: " + packageName
12134                        + "/" + className);
12135            }
12136            // Allow root and verify that userId is not being specified by a different user
12137            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
12138                throw new SecurityException(
12139                        "Permission Denial: attempt to change component state from pid="
12140                        + Binder.getCallingPid()
12141                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
12142            }
12143            if (className == null) {
12144                // We're dealing with an application/package level state change
12145                if (pkgSetting.getEnabled(userId) == newState) {
12146                    // Nothing to do
12147                    return;
12148                }
12149                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
12150                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
12151                    // Don't care about who enables an app.
12152                    callingPackage = null;
12153                }
12154                pkgSetting.setEnabled(newState, userId, callingPackage);
12155                // pkgSetting.pkg.mSetEnabled = newState;
12156            } else {
12157                // We're dealing with a component level state change
12158                // First, verify that this is a valid class name.
12159                PackageParser.Package pkg = pkgSetting.pkg;
12160                if (pkg == null || !pkg.hasComponentClassName(className)) {
12161                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
12162                        throw new IllegalArgumentException("Component class " + className
12163                                + " does not exist in " + packageName);
12164                    } else {
12165                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
12166                                + className + " does not exist in " + packageName);
12167                    }
12168                }
12169                switch (newState) {
12170                case COMPONENT_ENABLED_STATE_ENABLED:
12171                    if (!pkgSetting.enableComponentLPw(className, userId)) {
12172                        return;
12173                    }
12174                    break;
12175                case COMPONENT_ENABLED_STATE_DISABLED:
12176                    if (!pkgSetting.disableComponentLPw(className, userId)) {
12177                        return;
12178                    }
12179                    break;
12180                case COMPONENT_ENABLED_STATE_DEFAULT:
12181                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
12182                        return;
12183                    }
12184                    break;
12185                default:
12186                    Slog.e(TAG, "Invalid new component state: " + newState);
12187                    return;
12188                }
12189            }
12190            mSettings.writePackageRestrictionsLPr(userId);
12191            components = mPendingBroadcasts.get(userId, packageName);
12192            final boolean newPackage = components == null;
12193            if (newPackage) {
12194                components = new ArrayList<String>();
12195            }
12196            if (!components.contains(componentName)) {
12197                components.add(componentName);
12198            }
12199            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12200                sendNow = true;
12201                // Purge entry from pending broadcast list if another one exists already
12202                // since we are sending one right away.
12203                mPendingBroadcasts.remove(userId, packageName);
12204            } else {
12205                if (newPackage) {
12206                    mPendingBroadcasts.put(userId, packageName, components);
12207                }
12208                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12209                    // Schedule a message
12210                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12211                }
12212            }
12213        }
12214
12215        long callingId = Binder.clearCallingIdentity();
12216        try {
12217            if (sendNow) {
12218                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12219                sendPackageChangedBroadcast(packageName,
12220                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12221            }
12222        } finally {
12223            Binder.restoreCallingIdentity(callingId);
12224        }
12225    }
12226
12227    private void sendPackageChangedBroadcast(String packageName,
12228            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12229        if (DEBUG_INSTALL)
12230            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12231                    + componentNames);
12232        Bundle extras = new Bundle(4);
12233        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12234        String nameList[] = new String[componentNames.size()];
12235        componentNames.toArray(nameList);
12236        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12237        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12238        extras.putInt(Intent.EXTRA_UID, packageUid);
12239        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12240                new int[] {UserHandle.getUserId(packageUid)});
12241    }
12242
12243    @Override
12244    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12245        if (!sUserManager.exists(userId)) return;
12246        final int uid = Binder.getCallingUid();
12247        final int permission = mContext.checkCallingOrSelfPermission(
12248                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12249        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12250        enforceCrossUserPermission(uid, userId, true, true, "stop package");
12251        // writer
12252        synchronized (mPackages) {
12253            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12254                    uid, userId)) {
12255                scheduleWritePackageRestrictionsLocked(userId);
12256            }
12257        }
12258    }
12259
12260    @Override
12261    public String getInstallerPackageName(String packageName) {
12262        // reader
12263        synchronized (mPackages) {
12264            return mSettings.getInstallerPackageNameLPr(packageName);
12265        }
12266    }
12267
12268    @Override
12269    public int getApplicationEnabledSetting(String packageName, int userId) {
12270        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12271        int uid = Binder.getCallingUid();
12272        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
12273        // reader
12274        synchronized (mPackages) {
12275            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12276        }
12277    }
12278
12279    @Override
12280    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12281        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12282        int uid = Binder.getCallingUid();
12283        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
12284        // reader
12285        synchronized (mPackages) {
12286            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12287        }
12288    }
12289
12290    @Override
12291    public void enterSafeMode() {
12292        enforceSystemOrRoot("Only the system can request entering safe mode");
12293
12294        if (!mSystemReady) {
12295            mSafeMode = true;
12296        }
12297    }
12298
12299    @Override
12300    public void systemReady() {
12301        mSystemReady = true;
12302
12303        // Read the compatibilty setting when the system is ready.
12304        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12305                mContext.getContentResolver(),
12306                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12307        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12308        if (DEBUG_SETTINGS) {
12309            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12310        }
12311
12312        synchronized (mPackages) {
12313            // Verify that all of the preferred activity components actually
12314            // exist.  It is possible for applications to be updated and at
12315            // that point remove a previously declared activity component that
12316            // had been set as a preferred activity.  We try to clean this up
12317            // the next time we encounter that preferred activity, but it is
12318            // possible for the user flow to never be able to return to that
12319            // situation so here we do a sanity check to make sure we haven't
12320            // left any junk around.
12321            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12322            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12323                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12324                removed.clear();
12325                for (PreferredActivity pa : pir.filterSet()) {
12326                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12327                        removed.add(pa);
12328                    }
12329                }
12330                if (removed.size() > 0) {
12331                    for (int r=0; r<removed.size(); r++) {
12332                        PreferredActivity pa = removed.get(r);
12333                        Slog.w(TAG, "Removing dangling preferred activity: "
12334                                + pa.mPref.mComponent);
12335                        pir.removeFilter(pa);
12336                    }
12337                    mSettings.writePackageRestrictionsLPr(
12338                            mSettings.mPreferredActivities.keyAt(i));
12339                }
12340            }
12341        }
12342        sUserManager.systemReady();
12343
12344        // Kick off any messages waiting for system ready
12345        if (mPostSystemReadyMessages != null) {
12346            for (Message msg : mPostSystemReadyMessages) {
12347                msg.sendToTarget();
12348            }
12349            mPostSystemReadyMessages = null;
12350        }
12351    }
12352
12353    @Override
12354    public boolean isSafeMode() {
12355        return mSafeMode;
12356    }
12357
12358    @Override
12359    public boolean hasSystemUidErrors() {
12360        return mHasSystemUidErrors;
12361    }
12362
12363    static String arrayToString(int[] array) {
12364        StringBuffer buf = new StringBuffer(128);
12365        buf.append('[');
12366        if (array != null) {
12367            for (int i=0; i<array.length; i++) {
12368                if (i > 0) buf.append(", ");
12369                buf.append(array[i]);
12370            }
12371        }
12372        buf.append(']');
12373        return buf.toString();
12374    }
12375
12376    static class DumpState {
12377        public static final int DUMP_LIBS = 1 << 0;
12378        public static final int DUMP_FEATURES = 1 << 1;
12379        public static final int DUMP_RESOLVERS = 1 << 2;
12380        public static final int DUMP_PERMISSIONS = 1 << 3;
12381        public static final int DUMP_PACKAGES = 1 << 4;
12382        public static final int DUMP_SHARED_USERS = 1 << 5;
12383        public static final int DUMP_MESSAGES = 1 << 6;
12384        public static final int DUMP_PROVIDERS = 1 << 7;
12385        public static final int DUMP_VERIFIERS = 1 << 8;
12386        public static final int DUMP_PREFERRED = 1 << 9;
12387        public static final int DUMP_PREFERRED_XML = 1 << 10;
12388        public static final int DUMP_KEYSETS = 1 << 11;
12389        public static final int DUMP_VERSION = 1 << 12;
12390        public static final int DUMP_INSTALLS = 1 << 13;
12391
12392        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12393
12394        private int mTypes;
12395
12396        private int mOptions;
12397
12398        private boolean mTitlePrinted;
12399
12400        private SharedUserSetting mSharedUser;
12401
12402        public boolean isDumping(int type) {
12403            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12404                return true;
12405            }
12406
12407            return (mTypes & type) != 0;
12408        }
12409
12410        public void setDump(int type) {
12411            mTypes |= type;
12412        }
12413
12414        public boolean isOptionEnabled(int option) {
12415            return (mOptions & option) != 0;
12416        }
12417
12418        public void setOptionEnabled(int option) {
12419            mOptions |= option;
12420        }
12421
12422        public boolean onTitlePrinted() {
12423            final boolean printed = mTitlePrinted;
12424            mTitlePrinted = true;
12425            return printed;
12426        }
12427
12428        public boolean getTitlePrinted() {
12429            return mTitlePrinted;
12430        }
12431
12432        public void setTitlePrinted(boolean enabled) {
12433            mTitlePrinted = enabled;
12434        }
12435
12436        public SharedUserSetting getSharedUser() {
12437            return mSharedUser;
12438        }
12439
12440        public void setSharedUser(SharedUserSetting user) {
12441            mSharedUser = user;
12442        }
12443    }
12444
12445    @Override
12446    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12447        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12448                != PackageManager.PERMISSION_GRANTED) {
12449            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12450                    + Binder.getCallingPid()
12451                    + ", uid=" + Binder.getCallingUid()
12452                    + " without permission "
12453                    + android.Manifest.permission.DUMP);
12454            return;
12455        }
12456
12457        DumpState dumpState = new DumpState();
12458        boolean fullPreferred = false;
12459        boolean checkin = false;
12460
12461        String packageName = null;
12462
12463        int opti = 0;
12464        while (opti < args.length) {
12465            String opt = args[opti];
12466            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12467                break;
12468            }
12469            opti++;
12470
12471            if ("-a".equals(opt)) {
12472                // Right now we only know how to print all.
12473            } else if ("-h".equals(opt)) {
12474                pw.println("Package manager dump options:");
12475                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12476                pw.println("    --checkin: dump for a checkin");
12477                pw.println("    -f: print details of intent filters");
12478                pw.println("    -h: print this help");
12479                pw.println("  cmd may be one of:");
12480                pw.println("    l[ibraries]: list known shared libraries");
12481                pw.println("    f[ibraries]: list device features");
12482                pw.println("    k[eysets]: print known keysets");
12483                pw.println("    r[esolvers]: dump intent resolvers");
12484                pw.println("    perm[issions]: dump permissions");
12485                pw.println("    pref[erred]: print preferred package settings");
12486                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12487                pw.println("    prov[iders]: dump content providers");
12488                pw.println("    p[ackages]: dump installed packages");
12489                pw.println("    s[hared-users]: dump shared user IDs");
12490                pw.println("    m[essages]: print collected runtime messages");
12491                pw.println("    v[erifiers]: print package verifier info");
12492                pw.println("    version: print database version info");
12493                pw.println("    write: write current settings now");
12494                pw.println("    <package.name>: info about given package");
12495                pw.println("    installs: details about install sessions");
12496                return;
12497            } else if ("--checkin".equals(opt)) {
12498                checkin = true;
12499            } else if ("-f".equals(opt)) {
12500                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12501            } else {
12502                pw.println("Unknown argument: " + opt + "; use -h for help");
12503            }
12504        }
12505
12506        // Is the caller requesting to dump a particular piece of data?
12507        if (opti < args.length) {
12508            String cmd = args[opti];
12509            opti++;
12510            // Is this a package name?
12511            if ("android".equals(cmd) || cmd.contains(".")) {
12512                packageName = cmd;
12513                // When dumping a single package, we always dump all of its
12514                // filter information since the amount of data will be reasonable.
12515                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12516            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12517                dumpState.setDump(DumpState.DUMP_LIBS);
12518            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12519                dumpState.setDump(DumpState.DUMP_FEATURES);
12520            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12521                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12522            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12523                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12524            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12525                dumpState.setDump(DumpState.DUMP_PREFERRED);
12526            } else if ("preferred-xml".equals(cmd)) {
12527                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12528                if (opti < args.length && "--full".equals(args[opti])) {
12529                    fullPreferred = true;
12530                    opti++;
12531                }
12532            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12533                dumpState.setDump(DumpState.DUMP_PACKAGES);
12534            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12535                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12536            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12537                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12538            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12539                dumpState.setDump(DumpState.DUMP_MESSAGES);
12540            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12541                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12542            } else if ("version".equals(cmd)) {
12543                dumpState.setDump(DumpState.DUMP_VERSION);
12544            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12545                dumpState.setDump(DumpState.DUMP_KEYSETS);
12546            } else if ("installs".equals(cmd)) {
12547                dumpState.setDump(DumpState.DUMP_INSTALLS);
12548            } else if ("write".equals(cmd)) {
12549                synchronized (mPackages) {
12550                    mSettings.writeLPr();
12551                    pw.println("Settings written.");
12552                    return;
12553                }
12554            }
12555        }
12556
12557        if (checkin) {
12558            pw.println("vers,1");
12559        }
12560
12561        // reader
12562        synchronized (mPackages) {
12563            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12564                if (!checkin) {
12565                    if (dumpState.onTitlePrinted())
12566                        pw.println();
12567                    pw.println("Database versions:");
12568                    pw.print("  SDK Version:");
12569                    pw.print(" internal=");
12570                    pw.print(mSettings.mInternalSdkPlatform);
12571                    pw.print(" external=");
12572                    pw.println(mSettings.mExternalSdkPlatform);
12573                    pw.print("  DB Version:");
12574                    pw.print(" internal=");
12575                    pw.print(mSettings.mInternalDatabaseVersion);
12576                    pw.print(" external=");
12577                    pw.println(mSettings.mExternalDatabaseVersion);
12578                }
12579            }
12580
12581            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12582                if (!checkin) {
12583                    if (dumpState.onTitlePrinted())
12584                        pw.println();
12585                    pw.println("Verifiers:");
12586                    pw.print("  Required: ");
12587                    pw.print(mRequiredVerifierPackage);
12588                    pw.print(" (uid=");
12589                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12590                    pw.println(")");
12591                } else if (mRequiredVerifierPackage != null) {
12592                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12593                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12594                }
12595            }
12596
12597            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12598                boolean printedHeader = false;
12599                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12600                while (it.hasNext()) {
12601                    String name = it.next();
12602                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12603                    if (!checkin) {
12604                        if (!printedHeader) {
12605                            if (dumpState.onTitlePrinted())
12606                                pw.println();
12607                            pw.println("Libraries:");
12608                            printedHeader = true;
12609                        }
12610                        pw.print("  ");
12611                    } else {
12612                        pw.print("lib,");
12613                    }
12614                    pw.print(name);
12615                    if (!checkin) {
12616                        pw.print(" -> ");
12617                    }
12618                    if (ent.path != null) {
12619                        if (!checkin) {
12620                            pw.print("(jar) ");
12621                            pw.print(ent.path);
12622                        } else {
12623                            pw.print(",jar,");
12624                            pw.print(ent.path);
12625                        }
12626                    } else {
12627                        if (!checkin) {
12628                            pw.print("(apk) ");
12629                            pw.print(ent.apk);
12630                        } else {
12631                            pw.print(",apk,");
12632                            pw.print(ent.apk);
12633                        }
12634                    }
12635                    pw.println();
12636                }
12637            }
12638
12639            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12640                if (dumpState.onTitlePrinted())
12641                    pw.println();
12642                if (!checkin) {
12643                    pw.println("Features:");
12644                }
12645                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12646                while (it.hasNext()) {
12647                    String name = it.next();
12648                    if (!checkin) {
12649                        pw.print("  ");
12650                    } else {
12651                        pw.print("feat,");
12652                    }
12653                    pw.println(name);
12654                }
12655            }
12656
12657            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12658                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12659                        : "Activity Resolver Table:", "  ", packageName,
12660                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12661                    dumpState.setTitlePrinted(true);
12662                }
12663                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12664                        : "Receiver Resolver Table:", "  ", packageName,
12665                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12666                    dumpState.setTitlePrinted(true);
12667                }
12668                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12669                        : "Service Resolver Table:", "  ", packageName,
12670                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12671                    dumpState.setTitlePrinted(true);
12672                }
12673                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12674                        : "Provider Resolver Table:", "  ", packageName,
12675                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12676                    dumpState.setTitlePrinted(true);
12677                }
12678            }
12679
12680            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12681                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12682                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12683                    int user = mSettings.mPreferredActivities.keyAt(i);
12684                    if (pir.dump(pw,
12685                            dumpState.getTitlePrinted()
12686                                ? "\nPreferred Activities User " + user + ":"
12687                                : "Preferred Activities User " + user + ":", "  ",
12688                            packageName, true, false)) {
12689                        dumpState.setTitlePrinted(true);
12690                    }
12691                }
12692            }
12693
12694            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12695                pw.flush();
12696                FileOutputStream fout = new FileOutputStream(fd);
12697                BufferedOutputStream str = new BufferedOutputStream(fout);
12698                XmlSerializer serializer = new FastXmlSerializer();
12699                try {
12700                    serializer.setOutput(str, "utf-8");
12701                    serializer.startDocument(null, true);
12702                    serializer.setFeature(
12703                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12704                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12705                    serializer.endDocument();
12706                    serializer.flush();
12707                } catch (IllegalArgumentException e) {
12708                    pw.println("Failed writing: " + e);
12709                } catch (IllegalStateException e) {
12710                    pw.println("Failed writing: " + e);
12711                } catch (IOException e) {
12712                    pw.println("Failed writing: " + e);
12713                }
12714            }
12715
12716            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12717                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12718                if (packageName == null) {
12719                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12720                        if (iperm == 0) {
12721                            if (dumpState.onTitlePrinted())
12722                                pw.println();
12723                            pw.println("AppOp Permissions:");
12724                        }
12725                        pw.print("  AppOp Permission ");
12726                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12727                        pw.println(":");
12728                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12729                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12730                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12731                        }
12732                    }
12733                }
12734            }
12735
12736            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12737                boolean printedSomething = false;
12738                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12739                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12740                        continue;
12741                    }
12742                    if (!printedSomething) {
12743                        if (dumpState.onTitlePrinted())
12744                            pw.println();
12745                        pw.println("Registered ContentProviders:");
12746                        printedSomething = true;
12747                    }
12748                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12749                    pw.print("    "); pw.println(p.toString());
12750                }
12751                printedSomething = false;
12752                for (Map.Entry<String, PackageParser.Provider> entry :
12753                        mProvidersByAuthority.entrySet()) {
12754                    PackageParser.Provider p = entry.getValue();
12755                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12756                        continue;
12757                    }
12758                    if (!printedSomething) {
12759                        if (dumpState.onTitlePrinted())
12760                            pw.println();
12761                        pw.println("ContentProvider Authorities:");
12762                        printedSomething = true;
12763                    }
12764                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12765                    pw.print("    "); pw.println(p.toString());
12766                    if (p.info != null && p.info.applicationInfo != null) {
12767                        final String appInfo = p.info.applicationInfo.toString();
12768                        pw.print("      applicationInfo="); pw.println(appInfo);
12769                    }
12770                }
12771            }
12772
12773            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12774                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12775            }
12776
12777            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12778                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12779            }
12780
12781            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12782                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
12783            }
12784
12785            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12786                // XXX should handle packageName != null by dumping only install data that
12787                // the given package is involved with.
12788                if (dumpState.onTitlePrinted()) pw.println();
12789                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12790            }
12791
12792            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12793                if (dumpState.onTitlePrinted()) pw.println();
12794                mSettings.dumpReadMessagesLPr(pw, dumpState);
12795
12796                pw.println();
12797                pw.println("Package warning messages:");
12798                BufferedReader in = null;
12799                String line = null;
12800                try {
12801                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12802                    while ((line = in.readLine()) != null) {
12803                        if (line.contains("ignored: updated version")) continue;
12804                        pw.println(line);
12805                    }
12806                } catch (IOException ignored) {
12807                } finally {
12808                    IoUtils.closeQuietly(in);
12809                }
12810            }
12811
12812            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
12813                BufferedReader in = null;
12814                String line = null;
12815                try {
12816                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12817                    while ((line = in.readLine()) != null) {
12818                        if (line.contains("ignored: updated version")) continue;
12819                        pw.print("msg,");
12820                        pw.println(line);
12821                    }
12822                } catch (IOException ignored) {
12823                } finally {
12824                    IoUtils.closeQuietly(in);
12825                }
12826            }
12827        }
12828    }
12829
12830    // ------- apps on sdcard specific code -------
12831    static final boolean DEBUG_SD_INSTALL = false;
12832
12833    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12834
12835    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12836
12837    private boolean mMediaMounted = false;
12838
12839    static String getEncryptKey() {
12840        try {
12841            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12842                    SD_ENCRYPTION_KEYSTORE_NAME);
12843            if (sdEncKey == null) {
12844                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12845                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12846                if (sdEncKey == null) {
12847                    Slog.e(TAG, "Failed to create encryption keys");
12848                    return null;
12849                }
12850            }
12851            return sdEncKey;
12852        } catch (NoSuchAlgorithmException nsae) {
12853            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12854            return null;
12855        } catch (IOException ioe) {
12856            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12857            return null;
12858        }
12859    }
12860
12861    /*
12862     * Update media status on PackageManager.
12863     */
12864    @Override
12865    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12866        int callingUid = Binder.getCallingUid();
12867        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12868            throw new SecurityException("Media status can only be updated by the system");
12869        }
12870        // reader; this apparently protects mMediaMounted, but should probably
12871        // be a different lock in that case.
12872        synchronized (mPackages) {
12873            Log.i(TAG, "Updating external media status from "
12874                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12875                    + (mediaStatus ? "mounted" : "unmounted"));
12876            if (DEBUG_SD_INSTALL)
12877                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12878                        + ", mMediaMounted=" + mMediaMounted);
12879            if (mediaStatus == mMediaMounted) {
12880                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12881                        : 0, -1);
12882                mHandler.sendMessage(msg);
12883                return;
12884            }
12885            mMediaMounted = mediaStatus;
12886        }
12887        // Queue up an async operation since the package installation may take a
12888        // little while.
12889        mHandler.post(new Runnable() {
12890            public void run() {
12891                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12892            }
12893        });
12894    }
12895
12896    /**
12897     * Called by MountService when the initial ASECs to scan are available.
12898     * Should block until all the ASEC containers are finished being scanned.
12899     */
12900    public void scanAvailableAsecs() {
12901        updateExternalMediaStatusInner(true, false, false);
12902        if (mShouldRestoreconData) {
12903            SELinuxMMAC.setRestoreconDone();
12904            mShouldRestoreconData = false;
12905        }
12906    }
12907
12908    /*
12909     * Collect information of applications on external media, map them against
12910     * existing containers and update information based on current mount status.
12911     * Please note that we always have to report status if reportStatus has been
12912     * set to true especially when unloading packages.
12913     */
12914    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12915            boolean externalStorage) {
12916        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12917        int[] uidArr = EmptyArray.INT;
12918
12919        final String[] list = PackageHelper.getSecureContainerList();
12920        if (ArrayUtils.isEmpty(list)) {
12921            Log.i(TAG, "No secure containers found");
12922        } else {
12923            // Process list of secure containers and categorize them
12924            // as active or stale based on their package internal state.
12925
12926            // reader
12927            synchronized (mPackages) {
12928                for (String cid : list) {
12929                    // Leave stages untouched for now; installer service owns them
12930                    if (PackageInstallerService.isStageName(cid)) continue;
12931
12932                    if (DEBUG_SD_INSTALL)
12933                        Log.i(TAG, "Processing container " + cid);
12934                    String pkgName = getAsecPackageName(cid);
12935                    if (pkgName == null) {
12936                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12937                        continue;
12938                    }
12939                    if (DEBUG_SD_INSTALL)
12940                        Log.i(TAG, "Looking for pkg : " + pkgName);
12941
12942                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12943                    if (ps == null) {
12944                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12945                        continue;
12946                    }
12947
12948                    /*
12949                     * Skip packages that are not external if we're unmounting
12950                     * external storage.
12951                     */
12952                    if (externalStorage && !isMounted && !isExternal(ps)) {
12953                        continue;
12954                    }
12955
12956                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12957                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12958                    // The package status is changed only if the code path
12959                    // matches between settings and the container id.
12960                    if (ps.codePathString != null
12961                            && ps.codePathString.startsWith(args.getCodePath())) {
12962                        if (DEBUG_SD_INSTALL) {
12963                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12964                                    + " at code path: " + ps.codePathString);
12965                        }
12966
12967                        // We do have a valid package installed on sdcard
12968                        processCids.put(args, ps.codePathString);
12969                        final int uid = ps.appId;
12970                        if (uid != -1) {
12971                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12972                        }
12973                    } else {
12974                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12975                                + ps.codePathString);
12976                    }
12977                }
12978            }
12979
12980            Arrays.sort(uidArr);
12981        }
12982
12983        // Process packages with valid entries.
12984        if (isMounted) {
12985            if (DEBUG_SD_INSTALL)
12986                Log.i(TAG, "Loading packages");
12987            loadMediaPackages(processCids, uidArr);
12988            startCleaningPackages();
12989            mInstallerService.onSecureContainersAvailable();
12990        } else {
12991            if (DEBUG_SD_INSTALL)
12992                Log.i(TAG, "Unloading packages");
12993            unloadMediaPackages(processCids, uidArr, reportStatus);
12994        }
12995    }
12996
12997    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12998            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12999        int size = pkgList.size();
13000        if (size > 0) {
13001            // Send broadcasts here
13002            Bundle extras = new Bundle();
13003            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
13004                    .toArray(new String[size]));
13005            if (uidArr != null) {
13006                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
13007            }
13008            if (replacing) {
13009                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
13010            }
13011            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
13012                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
13013            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
13014        }
13015    }
13016
13017   /*
13018     * Look at potentially valid container ids from processCids If package
13019     * information doesn't match the one on record or package scanning fails,
13020     * the cid is added to list of removeCids. We currently don't delete stale
13021     * containers.
13022     */
13023    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
13024        ArrayList<String> pkgList = new ArrayList<String>();
13025        Set<AsecInstallArgs> keys = processCids.keySet();
13026
13027        for (AsecInstallArgs args : keys) {
13028            String codePath = processCids.get(args);
13029            if (DEBUG_SD_INSTALL)
13030                Log.i(TAG, "Loading container : " + args.cid);
13031            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13032            try {
13033                // Make sure there are no container errors first.
13034                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
13035                    Slog.e(TAG, "Failed to mount cid : " + args.cid
13036                            + " when installing from sdcard");
13037                    continue;
13038                }
13039                // Check code path here.
13040                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
13041                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
13042                            + " does not match one in settings " + codePath);
13043                    continue;
13044                }
13045                // Parse package
13046                int parseFlags = mDefParseFlags;
13047                if (args.isExternal()) {
13048                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
13049                }
13050                if (args.isFwdLocked()) {
13051                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
13052                }
13053
13054                synchronized (mInstallLock) {
13055                    PackageParser.Package pkg = null;
13056                    try {
13057                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
13058                    } catch (PackageManagerException e) {
13059                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
13060                    }
13061                    // Scan the package
13062                    if (pkg != null) {
13063                        /*
13064                         * TODO why is the lock being held? doPostInstall is
13065                         * called in other places without the lock. This needs
13066                         * to be straightened out.
13067                         */
13068                        // writer
13069                        synchronized (mPackages) {
13070                            retCode = PackageManager.INSTALL_SUCCEEDED;
13071                            pkgList.add(pkg.packageName);
13072                            // Post process args
13073                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
13074                                    pkg.applicationInfo.uid);
13075                        }
13076                    } else {
13077                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
13078                    }
13079                }
13080
13081            } finally {
13082                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
13083                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
13084                }
13085            }
13086        }
13087        // writer
13088        synchronized (mPackages) {
13089            // If the platform SDK has changed since the last time we booted,
13090            // we need to re-grant app permission to catch any new ones that
13091            // appear. This is really a hack, and means that apps can in some
13092            // cases get permissions that the user didn't initially explicitly
13093            // allow... it would be nice to have some better way to handle
13094            // this situation.
13095            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
13096            if (regrantPermissions)
13097                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
13098                        + mSdkVersion + "; regranting permissions for external storage");
13099            mSettings.mExternalSdkPlatform = mSdkVersion;
13100
13101            // Make sure group IDs have been assigned, and any permission
13102            // changes in other apps are accounted for
13103            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
13104                    | (regrantPermissions
13105                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
13106                            : 0));
13107
13108            mSettings.updateExternalDatabaseVersion();
13109
13110            // can downgrade to reader
13111            // Persist settings
13112            mSettings.writeLPr();
13113        }
13114        // Send a broadcast to let everyone know we are done processing
13115        if (pkgList.size() > 0) {
13116            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13117        }
13118    }
13119
13120   /*
13121     * Utility method to unload a list of specified containers
13122     */
13123    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
13124        // Just unmount all valid containers.
13125        for (AsecInstallArgs arg : cidArgs) {
13126            synchronized (mInstallLock) {
13127                arg.doPostDeleteLI(false);
13128           }
13129       }
13130   }
13131
13132    /*
13133     * Unload packages mounted on external media. This involves deleting package
13134     * data from internal structures, sending broadcasts about diabled packages,
13135     * gc'ing to free up references, unmounting all secure containers
13136     * corresponding to packages on external media, and posting a
13137     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
13138     * that we always have to post this message if status has been requested no
13139     * matter what.
13140     */
13141    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
13142            final boolean reportStatus) {
13143        if (DEBUG_SD_INSTALL)
13144            Log.i(TAG, "unloading media packages");
13145        ArrayList<String> pkgList = new ArrayList<String>();
13146        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
13147        final Set<AsecInstallArgs> keys = processCids.keySet();
13148        for (AsecInstallArgs args : keys) {
13149            String pkgName = args.getPackageName();
13150            if (DEBUG_SD_INSTALL)
13151                Log.i(TAG, "Trying to unload pkg : " + pkgName);
13152            // Delete package internally
13153            PackageRemovedInfo outInfo = new PackageRemovedInfo();
13154            synchronized (mInstallLock) {
13155                boolean res = deletePackageLI(pkgName, null, false, null, null,
13156                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
13157                if (res) {
13158                    pkgList.add(pkgName);
13159                } else {
13160                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
13161                    failedList.add(args);
13162                }
13163            }
13164        }
13165
13166        // reader
13167        synchronized (mPackages) {
13168            // We didn't update the settings after removing each package;
13169            // write them now for all packages.
13170            mSettings.writeLPr();
13171        }
13172
13173        // We have to absolutely send UPDATED_MEDIA_STATUS only
13174        // after confirming that all the receivers processed the ordered
13175        // broadcast when packages get disabled, force a gc to clean things up.
13176        // and unload all the containers.
13177        if (pkgList.size() > 0) {
13178            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
13179                    new IIntentReceiver.Stub() {
13180                public void performReceive(Intent intent, int resultCode, String data,
13181                        Bundle extras, boolean ordered, boolean sticky,
13182                        int sendingUser) throws RemoteException {
13183                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
13184                            reportStatus ? 1 : 0, 1, keys);
13185                    mHandler.sendMessage(msg);
13186                }
13187            });
13188        } else {
13189            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
13190                    keys);
13191            mHandler.sendMessage(msg);
13192        }
13193    }
13194
13195    /** Binder call */
13196    @Override
13197    public void movePackage(final String packageName, final IPackageMoveObserver observer,
13198            final int flags) {
13199        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
13200        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
13201        int returnCode = PackageManager.MOVE_SUCCEEDED;
13202        int currInstallFlags = 0;
13203        int newInstallFlags = 0;
13204
13205        File codeFile = null;
13206        String installerPackageName = null;
13207        String packageAbiOverride = null;
13208
13209        // reader
13210        synchronized (mPackages) {
13211            final PackageParser.Package pkg = mPackages.get(packageName);
13212            final PackageSetting ps = mSettings.mPackages.get(packageName);
13213            if (pkg == null || ps == null) {
13214                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13215            } else {
13216                // Disable moving fwd locked apps and system packages
13217                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
13218                    Slog.w(TAG, "Cannot move system application");
13219                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
13220                } else if (pkg.mOperationPending) {
13221                    Slog.w(TAG, "Attempt to move package which has pending operations");
13222                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
13223                } else {
13224                    // Find install location first
13225                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13226                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13227                        Slog.w(TAG, "Ambigous flags specified for move location.");
13228                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13229                    } else {
13230                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13231                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13232                        currInstallFlags = isExternal(pkg)
13233                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13234
13235                        if (newInstallFlags == currInstallFlags) {
13236                            Slog.w(TAG, "No move required. Trying to move to same location");
13237                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13238                        } else {
13239                            if (isForwardLocked(pkg)) {
13240                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13241                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13242                            }
13243                        }
13244                    }
13245                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13246                        pkg.mOperationPending = true;
13247                    }
13248                }
13249
13250                codeFile = new File(pkg.codePath);
13251                installerPackageName = ps.installerPackageName;
13252                packageAbiOverride = ps.cpuAbiOverrideString;
13253            }
13254        }
13255
13256        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13257            try {
13258                observer.packageMoved(packageName, returnCode);
13259            } catch (RemoteException ignored) {
13260            }
13261            return;
13262        }
13263
13264        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
13265            @Override
13266            public void onUserActionRequired(Intent intent) throws RemoteException {
13267                throw new IllegalStateException();
13268            }
13269
13270            @Override
13271            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
13272                    Bundle extras) throws RemoteException {
13273                Slog.d(TAG, "Install result for move: "
13274                        + PackageManager.installStatusToString(returnCode, msg));
13275
13276                // We usually have a new package now after the install, but if
13277                // we failed we need to clear the pending flag on the original
13278                // package object.
13279                synchronized (mPackages) {
13280                    final PackageParser.Package pkg = mPackages.get(packageName);
13281                    if (pkg != null) {
13282                        pkg.mOperationPending = false;
13283                    }
13284                }
13285
13286                final int status = PackageManager.installStatusToPublicStatus(returnCode);
13287                switch (status) {
13288                    case PackageInstaller.STATUS_SUCCESS:
13289                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
13290                        break;
13291                    case PackageInstaller.STATUS_FAILURE_STORAGE:
13292                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
13293                        break;
13294                    default:
13295                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
13296                        break;
13297                }
13298            }
13299        };
13300
13301        // Treat a move like reinstalling an existing app, which ensures that we
13302        // process everythign uniformly, like unpacking native libraries.
13303        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
13304
13305        final Message msg = mHandler.obtainMessage(INIT_COPY);
13306        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
13307        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
13308                installerPackageName, null, user, packageAbiOverride);
13309        mHandler.sendMessage(msg);
13310    }
13311
13312    @Override
13313    public boolean setInstallLocation(int loc) {
13314        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13315                null);
13316        if (getInstallLocation() == loc) {
13317            return true;
13318        }
13319        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13320                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13321            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13322                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13323            return true;
13324        }
13325        return false;
13326   }
13327
13328    @Override
13329    public int getInstallLocation() {
13330        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13331                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13332                PackageHelper.APP_INSTALL_AUTO);
13333    }
13334
13335    /** Called by UserManagerService */
13336    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13337        mDirtyUsers.remove(userHandle);
13338        mSettings.removeUserLPw(userHandle);
13339        mPendingBroadcasts.remove(userHandle);
13340        if (mInstaller != null) {
13341            // Technically, we shouldn't be doing this with the package lock
13342            // held.  However, this is very rare, and there is already so much
13343            // other disk I/O going on, that we'll let it slide for now.
13344            mInstaller.removeUserDataDirs(userHandle);
13345        }
13346        mUserNeedsBadging.delete(userHandle);
13347        removeUnusedPackagesLILPw(userManager, userHandle);
13348    }
13349
13350    /**
13351     * We're removing userHandle and would like to remove any downloaded packages
13352     * that are no longer in use by any other user.
13353     * @param userHandle the user being removed
13354     */
13355    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13356        final boolean DEBUG_CLEAN_APKS = false;
13357        int [] users = userManager.getUserIdsLPr();
13358        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13359        while (psit.hasNext()) {
13360            PackageSetting ps = psit.next();
13361            if (ps.pkg == null) {
13362                continue;
13363            }
13364            final String packageName = ps.pkg.packageName;
13365            // Skip over if system app
13366            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13367                continue;
13368            }
13369            if (DEBUG_CLEAN_APKS) {
13370                Slog.i(TAG, "Checking package " + packageName);
13371            }
13372            boolean keep = false;
13373            for (int i = 0; i < users.length; i++) {
13374                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13375                    keep = true;
13376                    if (DEBUG_CLEAN_APKS) {
13377                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13378                                + users[i]);
13379                    }
13380                    break;
13381                }
13382            }
13383            if (!keep) {
13384                if (DEBUG_CLEAN_APKS) {
13385                    Slog.i(TAG, "  Removing package " + packageName);
13386                }
13387                mHandler.post(new Runnable() {
13388                    public void run() {
13389                        deletePackageX(packageName, userHandle, 0);
13390                    } //end run
13391                });
13392            }
13393        }
13394    }
13395
13396    /** Called by UserManagerService */
13397    void createNewUserLILPw(int userHandle, File path) {
13398        if (mInstaller != null) {
13399            mInstaller.createUserConfig(userHandle);
13400            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13401        }
13402    }
13403
13404    @Override
13405    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13406        mContext.enforceCallingOrSelfPermission(
13407                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13408                "Only package verification agents can read the verifier device identity");
13409
13410        synchronized (mPackages) {
13411            return mSettings.getVerifierDeviceIdentityLPw();
13412        }
13413    }
13414
13415    @Override
13416    public void setPermissionEnforced(String permission, boolean enforced) {
13417        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13418        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13419            synchronized (mPackages) {
13420                if (mSettings.mReadExternalStorageEnforced == null
13421                        || mSettings.mReadExternalStorageEnforced != enforced) {
13422                    mSettings.mReadExternalStorageEnforced = enforced;
13423                    mSettings.writeLPr();
13424                }
13425            }
13426            // kill any non-foreground processes so we restart them and
13427            // grant/revoke the GID.
13428            final IActivityManager am = ActivityManagerNative.getDefault();
13429            if (am != null) {
13430                final long token = Binder.clearCallingIdentity();
13431                try {
13432                    am.killProcessesBelowForeground("setPermissionEnforcement");
13433                } catch (RemoteException e) {
13434                } finally {
13435                    Binder.restoreCallingIdentity(token);
13436                }
13437            }
13438        } else {
13439            throw new IllegalArgumentException("No selective enforcement for " + permission);
13440        }
13441    }
13442
13443    @Override
13444    @Deprecated
13445    public boolean isPermissionEnforced(String permission) {
13446        return true;
13447    }
13448
13449    @Override
13450    public boolean isStorageLow() {
13451        final long token = Binder.clearCallingIdentity();
13452        try {
13453            final DeviceStorageMonitorInternal
13454                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13455            if (dsm != null) {
13456                return dsm.isMemoryLow();
13457            } else {
13458                return false;
13459            }
13460        } finally {
13461            Binder.restoreCallingIdentity(token);
13462        }
13463    }
13464
13465    @Override
13466    public IPackageInstaller getPackageInstaller() {
13467        return mInstallerService;
13468    }
13469
13470    private boolean userNeedsBadging(int userId) {
13471        int index = mUserNeedsBadging.indexOfKey(userId);
13472        if (index < 0) {
13473            final UserInfo userInfo;
13474            final long token = Binder.clearCallingIdentity();
13475            try {
13476                userInfo = sUserManager.getUserInfo(userId);
13477            } finally {
13478                Binder.restoreCallingIdentity(token);
13479            }
13480            final boolean b;
13481            if (userInfo != null && userInfo.isManagedProfile()) {
13482                b = true;
13483            } else {
13484                b = false;
13485            }
13486            mUserNeedsBadging.put(userId, b);
13487            return b;
13488        }
13489        return mUserNeedsBadging.valueAt(index);
13490    }
13491
13492    @Override
13493    public KeySet getKeySetByAlias(String packageName, String alias) {
13494        if (packageName == null || alias == null) {
13495            return null;
13496        }
13497        synchronized(mPackages) {
13498            final PackageParser.Package pkg = mPackages.get(packageName);
13499            if (pkg == null) {
13500                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13501                throw new IllegalArgumentException("Unknown package: " + packageName);
13502            }
13503            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13504            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13505        }
13506    }
13507
13508    @Override
13509    public KeySet getSigningKeySet(String packageName) {
13510        if (packageName == null) {
13511            return null;
13512        }
13513        synchronized(mPackages) {
13514            final PackageParser.Package pkg = mPackages.get(packageName);
13515            if (pkg == null) {
13516                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13517                throw new IllegalArgumentException("Unknown package: " + packageName);
13518            }
13519            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13520                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13521                throw new SecurityException("May not access signing KeySet of other apps.");
13522            }
13523            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13524            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13525        }
13526    }
13527
13528    @Override
13529    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13530        if (packageName == null || ks == null) {
13531            return false;
13532        }
13533        synchronized(mPackages) {
13534            final PackageParser.Package pkg = mPackages.get(packageName);
13535            if (pkg == null) {
13536                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13537                throw new IllegalArgumentException("Unknown package: " + packageName);
13538            }
13539            IBinder ksh = ks.getToken();
13540            if (ksh instanceof KeySetHandle) {
13541                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13542                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13543            }
13544            return false;
13545        }
13546    }
13547
13548    @Override
13549    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13550        if (packageName == null || ks == null) {
13551            return false;
13552        }
13553        synchronized(mPackages) {
13554            final PackageParser.Package pkg = mPackages.get(packageName);
13555            if (pkg == null) {
13556                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13557                throw new IllegalArgumentException("Unknown package: " + packageName);
13558            }
13559            IBinder ksh = ks.getToken();
13560            if (ksh instanceof KeySetHandle) {
13561                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13562                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13563            }
13564            return false;
13565        }
13566    }
13567
13568    public void getUsageStatsIfNoPackageUsageInfo() {
13569        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
13570            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
13571            if (usm == null) {
13572                throw new IllegalStateException("UsageStatsManager must be initialized");
13573            }
13574            long now = System.currentTimeMillis();
13575            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
13576            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
13577                String packageName = entry.getKey();
13578                PackageParser.Package pkg = mPackages.get(packageName);
13579                if (pkg == null) {
13580                    continue;
13581                }
13582                UsageStats usage = entry.getValue();
13583                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
13584                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
13585            }
13586        }
13587    }
13588
13589    /**
13590     * Check and throw if the given before/after packages would be considered a
13591     * downgrade.
13592     */
13593    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
13594            throws PackageManagerException {
13595        if (after.versionCode < before.mVersionCode) {
13596            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13597                    "Update version code " + after.versionCode + " is older than current "
13598                    + before.mVersionCode);
13599        } else if (after.versionCode == before.mVersionCode) {
13600            if (after.baseRevisionCode < before.baseRevisionCode) {
13601                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13602                        "Update base revision code " + after.baseRevisionCode
13603                        + " is older than current " + before.baseRevisionCode);
13604            }
13605
13606            if (!ArrayUtils.isEmpty(after.splitNames)) {
13607                for (int i = 0; i < after.splitNames.length; i++) {
13608                    final String splitName = after.splitNames[i];
13609                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
13610                    if (j != -1) {
13611                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
13612                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13613                                    "Update split " + splitName + " revision code "
13614                                    + after.splitRevisionCodes[i] + " is older than current "
13615                                    + before.splitRevisionCodes[j]);
13616                        }
13617                    }
13618                }
13619            }
13620        }
13621    }
13622}
13623