PackageManagerService.java revision 174a44888ec56f688426c80d50b9e0021f47c16f
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.PRIVATE_FLAG_PRIVILEGED);
1303        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1304                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1305        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1306                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1307        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1308                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1309        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1310                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1311        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1312                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_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.privateFlags = ps.pkgPrivateFlags;
2128                pkg.applicationInfo.dataDir =
2129                        getDataPathForPackage(packageName, 0).getPath();
2130                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2131                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2132            }
2133            return generatePackageInfo(pkg, flags, userId);
2134        }
2135        return null;
2136    }
2137
2138    @Override
2139    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2140        if (!sUserManager.exists(userId)) return null;
2141        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2142        // writer
2143        synchronized (mPackages) {
2144            PackageParser.Package p = mPackages.get(packageName);
2145            if (DEBUG_PACKAGE_INFO) Log.v(
2146                    TAG, "getApplicationInfo " + packageName
2147                    + ": " + p);
2148            if (p != null) {
2149                PackageSetting ps = mSettings.mPackages.get(packageName);
2150                if (ps == null) return null;
2151                // Note: isEnabledLP() does not apply here - always return info
2152                return PackageParser.generateApplicationInfo(
2153                        p, flags, ps.readUserState(userId), userId);
2154            }
2155            if ("android".equals(packageName)||"system".equals(packageName)) {
2156                return mAndroidApplication;
2157            }
2158            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2159                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2160            }
2161        }
2162        return null;
2163    }
2164
2165
2166    @Override
2167    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2168        mContext.enforceCallingOrSelfPermission(
2169                android.Manifest.permission.CLEAR_APP_CACHE, null);
2170        // Queue up an async operation since clearing cache may take a little while.
2171        mHandler.post(new Runnable() {
2172            public void run() {
2173                mHandler.removeCallbacks(this);
2174                int retCode = -1;
2175                synchronized (mInstallLock) {
2176                    retCode = mInstaller.freeCache(freeStorageSize);
2177                    if (retCode < 0) {
2178                        Slog.w(TAG, "Couldn't clear application caches");
2179                    }
2180                }
2181                if (observer != null) {
2182                    try {
2183                        observer.onRemoveCompleted(null, (retCode >= 0));
2184                    } catch (RemoteException e) {
2185                        Slog.w(TAG, "RemoveException when invoking call back");
2186                    }
2187                }
2188            }
2189        });
2190    }
2191
2192    @Override
2193    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2194        mContext.enforceCallingOrSelfPermission(
2195                android.Manifest.permission.CLEAR_APP_CACHE, null);
2196        // Queue up an async operation since clearing cache may take a little while.
2197        mHandler.post(new Runnable() {
2198            public void run() {
2199                mHandler.removeCallbacks(this);
2200                int retCode = -1;
2201                synchronized (mInstallLock) {
2202                    retCode = mInstaller.freeCache(freeStorageSize);
2203                    if (retCode < 0) {
2204                        Slog.w(TAG, "Couldn't clear application caches");
2205                    }
2206                }
2207                if(pi != null) {
2208                    try {
2209                        // Callback via pending intent
2210                        int code = (retCode >= 0) ? 1 : 0;
2211                        pi.sendIntent(null, code, null,
2212                                null, null);
2213                    } catch (SendIntentException e1) {
2214                        Slog.i(TAG, "Failed to send pending intent");
2215                    }
2216                }
2217            }
2218        });
2219    }
2220
2221    void freeStorage(long freeStorageSize) throws IOException {
2222        synchronized (mInstallLock) {
2223            if (mInstaller.freeCache(freeStorageSize) < 0) {
2224                throw new IOException("Failed to free enough space");
2225            }
2226        }
2227    }
2228
2229    @Override
2230    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2231        if (!sUserManager.exists(userId)) return null;
2232        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2233        synchronized (mPackages) {
2234            PackageParser.Activity a = mActivities.mActivities.get(component);
2235
2236            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2237            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2238                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2239                if (ps == null) return null;
2240                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2241                        userId);
2242            }
2243            if (mResolveComponentName.equals(component)) {
2244                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2245                        new PackageUserState(), userId);
2246            }
2247        }
2248        return null;
2249    }
2250
2251    @Override
2252    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2253            String resolvedType) {
2254        synchronized (mPackages) {
2255            PackageParser.Activity a = mActivities.mActivities.get(component);
2256            if (a == null) {
2257                return false;
2258            }
2259            for (int i=0; i<a.intents.size(); i++) {
2260                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2261                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2262                    return true;
2263                }
2264            }
2265            return false;
2266        }
2267    }
2268
2269    @Override
2270    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2271        if (!sUserManager.exists(userId)) return null;
2272        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2273        synchronized (mPackages) {
2274            PackageParser.Activity a = mReceivers.mActivities.get(component);
2275            if (DEBUG_PACKAGE_INFO) Log.v(
2276                TAG, "getReceiverInfo " + component + ": " + a);
2277            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2278                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2279                if (ps == null) return null;
2280                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2281                        userId);
2282            }
2283        }
2284        return null;
2285    }
2286
2287    @Override
2288    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2289        if (!sUserManager.exists(userId)) return null;
2290        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2291        synchronized (mPackages) {
2292            PackageParser.Service s = mServices.mServices.get(component);
2293            if (DEBUG_PACKAGE_INFO) Log.v(
2294                TAG, "getServiceInfo " + component + ": " + s);
2295            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2296                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2297                if (ps == null) return null;
2298                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2299                        userId);
2300            }
2301        }
2302        return null;
2303    }
2304
2305    @Override
2306    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2307        if (!sUserManager.exists(userId)) return null;
2308        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2309        synchronized (mPackages) {
2310            PackageParser.Provider p = mProviders.mProviders.get(component);
2311            if (DEBUG_PACKAGE_INFO) Log.v(
2312                TAG, "getProviderInfo " + component + ": " + p);
2313            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2314                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2315                if (ps == null) return null;
2316                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2317                        userId);
2318            }
2319        }
2320        return null;
2321    }
2322
2323    @Override
2324    public String[] getSystemSharedLibraryNames() {
2325        Set<String> libSet;
2326        synchronized (mPackages) {
2327            libSet = mSharedLibraries.keySet();
2328            int size = libSet.size();
2329            if (size > 0) {
2330                String[] libs = new String[size];
2331                libSet.toArray(libs);
2332                return libs;
2333            }
2334        }
2335        return null;
2336    }
2337
2338    @Override
2339    public FeatureInfo[] getSystemAvailableFeatures() {
2340        Collection<FeatureInfo> featSet;
2341        synchronized (mPackages) {
2342            featSet = mAvailableFeatures.values();
2343            int size = featSet.size();
2344            if (size > 0) {
2345                FeatureInfo[] features = new FeatureInfo[size+1];
2346                featSet.toArray(features);
2347                FeatureInfo fi = new FeatureInfo();
2348                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2349                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2350                features[size] = fi;
2351                return features;
2352            }
2353        }
2354        return null;
2355    }
2356
2357    @Override
2358    public boolean hasSystemFeature(String name) {
2359        synchronized (mPackages) {
2360            return mAvailableFeatures.containsKey(name);
2361        }
2362    }
2363
2364    private void checkValidCaller(int uid, int userId) {
2365        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2366            return;
2367
2368        throw new SecurityException("Caller uid=" + uid
2369                + " is not privileged to communicate with user=" + userId);
2370    }
2371
2372    @Override
2373    public int checkPermission(String permName, String pkgName) {
2374        synchronized (mPackages) {
2375            PackageParser.Package p = mPackages.get(pkgName);
2376            if (p != null && p.mExtras != null) {
2377                PackageSetting ps = (PackageSetting)p.mExtras;
2378                if (ps.sharedUser != null) {
2379                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2380                        return PackageManager.PERMISSION_GRANTED;
2381                    }
2382                } else if (ps.grantedPermissions.contains(permName)) {
2383                    return PackageManager.PERMISSION_GRANTED;
2384                }
2385            }
2386        }
2387        return PackageManager.PERMISSION_DENIED;
2388    }
2389
2390    @Override
2391    public int checkUidPermission(String permName, int uid) {
2392        synchronized (mPackages) {
2393            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2394            if (obj != null) {
2395                GrantedPermissions gp = (GrantedPermissions)obj;
2396                if (gp.grantedPermissions.contains(permName)) {
2397                    return PackageManager.PERMISSION_GRANTED;
2398                }
2399            } else {
2400                ArraySet<String> perms = mSystemPermissions.get(uid);
2401                if (perms != null && perms.contains(permName)) {
2402                    return PackageManager.PERMISSION_GRANTED;
2403                }
2404            }
2405        }
2406        return PackageManager.PERMISSION_DENIED;
2407    }
2408
2409    /**
2410     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2411     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2412     * @param checkShell TODO(yamasani):
2413     * @param message the message to log on security exception
2414     */
2415    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2416            boolean checkShell, String message) {
2417        if (userId < 0) {
2418            throw new IllegalArgumentException("Invalid userId " + userId);
2419        }
2420        if (checkShell) {
2421            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2422        }
2423        if (userId == UserHandle.getUserId(callingUid)) return;
2424        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2425            if (requireFullPermission) {
2426                mContext.enforceCallingOrSelfPermission(
2427                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2428            } else {
2429                try {
2430                    mContext.enforceCallingOrSelfPermission(
2431                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2432                } catch (SecurityException se) {
2433                    mContext.enforceCallingOrSelfPermission(
2434                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2435                }
2436            }
2437        }
2438    }
2439
2440    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2441        if (callingUid == Process.SHELL_UID) {
2442            if (userHandle >= 0
2443                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2444                throw new SecurityException("Shell does not have permission to access user "
2445                        + userHandle);
2446            } else if (userHandle < 0) {
2447                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2448                        + Debug.getCallers(3));
2449            }
2450        }
2451    }
2452
2453    private BasePermission findPermissionTreeLP(String permName) {
2454        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2455            if (permName.startsWith(bp.name) &&
2456                    permName.length() > bp.name.length() &&
2457                    permName.charAt(bp.name.length()) == '.') {
2458                return bp;
2459            }
2460        }
2461        return null;
2462    }
2463
2464    private BasePermission checkPermissionTreeLP(String permName) {
2465        if (permName != null) {
2466            BasePermission bp = findPermissionTreeLP(permName);
2467            if (bp != null) {
2468                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2469                    return bp;
2470                }
2471                throw new SecurityException("Calling uid "
2472                        + Binder.getCallingUid()
2473                        + " is not allowed to add to permission tree "
2474                        + bp.name + " owned by uid " + bp.uid);
2475            }
2476        }
2477        throw new SecurityException("No permission tree found for " + permName);
2478    }
2479
2480    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2481        if (s1 == null) {
2482            return s2 == null;
2483        }
2484        if (s2 == null) {
2485            return false;
2486        }
2487        if (s1.getClass() != s2.getClass()) {
2488            return false;
2489        }
2490        return s1.equals(s2);
2491    }
2492
2493    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2494        if (pi1.icon != pi2.icon) return false;
2495        if (pi1.logo != pi2.logo) return false;
2496        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2497        if (!compareStrings(pi1.name, pi2.name)) return false;
2498        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2499        // We'll take care of setting this one.
2500        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2501        // These are not currently stored in settings.
2502        //if (!compareStrings(pi1.group, pi2.group)) return false;
2503        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2504        //if (pi1.labelRes != pi2.labelRes) return false;
2505        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2506        return true;
2507    }
2508
2509    int permissionInfoFootprint(PermissionInfo info) {
2510        int size = info.name.length();
2511        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2512        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2513        return size;
2514    }
2515
2516    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2517        int size = 0;
2518        for (BasePermission perm : mSettings.mPermissions.values()) {
2519            if (perm.uid == tree.uid) {
2520                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2521            }
2522        }
2523        return size;
2524    }
2525
2526    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2527        // We calculate the max size of permissions defined by this uid and throw
2528        // if that plus the size of 'info' would exceed our stated maximum.
2529        if (tree.uid != Process.SYSTEM_UID) {
2530            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2531            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2532                throw new SecurityException("Permission tree size cap exceeded");
2533            }
2534        }
2535    }
2536
2537    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2538        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2539            throw new SecurityException("Label must be specified in permission");
2540        }
2541        BasePermission tree = checkPermissionTreeLP(info.name);
2542        BasePermission bp = mSettings.mPermissions.get(info.name);
2543        boolean added = bp == null;
2544        boolean changed = true;
2545        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2546        if (added) {
2547            enforcePermissionCapLocked(info, tree);
2548            bp = new BasePermission(info.name, tree.sourcePackage,
2549                    BasePermission.TYPE_DYNAMIC);
2550        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2551            throw new SecurityException(
2552                    "Not allowed to modify non-dynamic permission "
2553                    + info.name);
2554        } else {
2555            if (bp.protectionLevel == fixedLevel
2556                    && bp.perm.owner.equals(tree.perm.owner)
2557                    && bp.uid == tree.uid
2558                    && comparePermissionInfos(bp.perm.info, info)) {
2559                changed = false;
2560            }
2561        }
2562        bp.protectionLevel = fixedLevel;
2563        info = new PermissionInfo(info);
2564        info.protectionLevel = fixedLevel;
2565        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2566        bp.perm.info.packageName = tree.perm.info.packageName;
2567        bp.uid = tree.uid;
2568        if (added) {
2569            mSettings.mPermissions.put(info.name, bp);
2570        }
2571        if (changed) {
2572            if (!async) {
2573                mSettings.writeLPr();
2574            } else {
2575                scheduleWriteSettingsLocked();
2576            }
2577        }
2578        return added;
2579    }
2580
2581    @Override
2582    public boolean addPermission(PermissionInfo info) {
2583        synchronized (mPackages) {
2584            return addPermissionLocked(info, false);
2585        }
2586    }
2587
2588    @Override
2589    public boolean addPermissionAsync(PermissionInfo info) {
2590        synchronized (mPackages) {
2591            return addPermissionLocked(info, true);
2592        }
2593    }
2594
2595    @Override
2596    public void removePermission(String name) {
2597        synchronized (mPackages) {
2598            checkPermissionTreeLP(name);
2599            BasePermission bp = mSettings.mPermissions.get(name);
2600            if (bp != null) {
2601                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2602                    throw new SecurityException(
2603                            "Not allowed to modify non-dynamic permission "
2604                            + name);
2605                }
2606                mSettings.mPermissions.remove(name);
2607                mSettings.writeLPr();
2608            }
2609        }
2610    }
2611
2612    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2613        int index = pkg.requestedPermissions.indexOf(bp.name);
2614        if (index == -1) {
2615            throw new SecurityException("Package " + pkg.packageName
2616                    + " has not requested permission " + bp.name);
2617        }
2618        boolean isNormal =
2619                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2620                        == PermissionInfo.PROTECTION_NORMAL);
2621        boolean isDangerous =
2622                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2623                        == PermissionInfo.PROTECTION_DANGEROUS);
2624        boolean isDevelopment =
2625                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2626
2627        if (!isNormal && !isDangerous && !isDevelopment) {
2628            throw new SecurityException("Permission " + bp.name
2629                    + " is not a changeable permission type");
2630        }
2631
2632        if (isNormal || isDangerous) {
2633            if (pkg.requestedPermissionsRequired.get(index)) {
2634                throw new SecurityException("Can't change " + bp.name
2635                        + ". It is required by the application");
2636            }
2637        }
2638    }
2639
2640    @Override
2641    public void grantPermission(String packageName, String permissionName) {
2642        mContext.enforceCallingOrSelfPermission(
2643                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2644        synchronized (mPackages) {
2645            final PackageParser.Package pkg = mPackages.get(packageName);
2646            if (pkg == null) {
2647                throw new IllegalArgumentException("Unknown package: " + packageName);
2648            }
2649            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2650            if (bp == null) {
2651                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2652            }
2653
2654            checkGrantRevokePermissions(pkg, bp);
2655
2656            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2657            if (ps == null) {
2658                return;
2659            }
2660            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2661            if (gp.grantedPermissions.add(permissionName)) {
2662                if (ps.haveGids) {
2663                    gp.gids = appendInts(gp.gids, bp.gids);
2664                }
2665                mSettings.writeLPr();
2666            }
2667        }
2668    }
2669
2670    @Override
2671    public void revokePermission(String packageName, String permissionName) {
2672        int changedAppId = -1;
2673
2674        synchronized (mPackages) {
2675            final PackageParser.Package pkg = mPackages.get(packageName);
2676            if (pkg == null) {
2677                throw new IllegalArgumentException("Unknown package: " + packageName);
2678            }
2679            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2680                mContext.enforceCallingOrSelfPermission(
2681                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2682            }
2683            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2684            if (bp == null) {
2685                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2686            }
2687
2688            checkGrantRevokePermissions(pkg, bp);
2689
2690            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2691            if (ps == null) {
2692                return;
2693            }
2694            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2695            if (gp.grantedPermissions.remove(permissionName)) {
2696                gp.grantedPermissions.remove(permissionName);
2697                if (ps.haveGids) {
2698                    gp.gids = removeInts(gp.gids, bp.gids);
2699                }
2700                mSettings.writeLPr();
2701                changedAppId = ps.appId;
2702            }
2703        }
2704
2705        if (changedAppId >= 0) {
2706            // We changed the perm on someone, kill its processes.
2707            IActivityManager am = ActivityManagerNative.getDefault();
2708            if (am != null) {
2709                final int callingUserId = UserHandle.getCallingUserId();
2710                final long ident = Binder.clearCallingIdentity();
2711                try {
2712                    //XXX we should only revoke for the calling user's app permissions,
2713                    // but for now we impact all users.
2714                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2715                    //        "revoke " + permissionName);
2716                    int[] users = sUserManager.getUserIds();
2717                    for (int user : users) {
2718                        am.killUid(UserHandle.getUid(user, changedAppId),
2719                                "revoke " + permissionName);
2720                    }
2721                } catch (RemoteException e) {
2722                } finally {
2723                    Binder.restoreCallingIdentity(ident);
2724                }
2725            }
2726        }
2727    }
2728
2729    @Override
2730    public boolean isProtectedBroadcast(String actionName) {
2731        synchronized (mPackages) {
2732            return mProtectedBroadcasts.contains(actionName);
2733        }
2734    }
2735
2736    @Override
2737    public int checkSignatures(String pkg1, String pkg2) {
2738        synchronized (mPackages) {
2739            final PackageParser.Package p1 = mPackages.get(pkg1);
2740            final PackageParser.Package p2 = mPackages.get(pkg2);
2741            if (p1 == null || p1.mExtras == null
2742                    || p2 == null || p2.mExtras == null) {
2743                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2744            }
2745            return compareSignatures(p1.mSignatures, p2.mSignatures);
2746        }
2747    }
2748
2749    @Override
2750    public int checkUidSignatures(int uid1, int uid2) {
2751        // Map to base uids.
2752        uid1 = UserHandle.getAppId(uid1);
2753        uid2 = UserHandle.getAppId(uid2);
2754        // reader
2755        synchronized (mPackages) {
2756            Signature[] s1;
2757            Signature[] s2;
2758            Object obj = mSettings.getUserIdLPr(uid1);
2759            if (obj != null) {
2760                if (obj instanceof SharedUserSetting) {
2761                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2762                } else if (obj instanceof PackageSetting) {
2763                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2764                } else {
2765                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2766                }
2767            } else {
2768                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2769            }
2770            obj = mSettings.getUserIdLPr(uid2);
2771            if (obj != null) {
2772                if (obj instanceof SharedUserSetting) {
2773                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2774                } else if (obj instanceof PackageSetting) {
2775                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2776                } else {
2777                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2778                }
2779            } else {
2780                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2781            }
2782            return compareSignatures(s1, s2);
2783        }
2784    }
2785
2786    /**
2787     * Compares two sets of signatures. Returns:
2788     * <br />
2789     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2790     * <br />
2791     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2792     * <br />
2793     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2794     * <br />
2795     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2796     * <br />
2797     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2798     */
2799    static int compareSignatures(Signature[] s1, Signature[] s2) {
2800        if (s1 == null) {
2801            return s2 == null
2802                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2803                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2804        }
2805
2806        if (s2 == null) {
2807            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2808        }
2809
2810        if (s1.length != s2.length) {
2811            return PackageManager.SIGNATURE_NO_MATCH;
2812        }
2813
2814        // Since both signature sets are of size 1, we can compare without HashSets.
2815        if (s1.length == 1) {
2816            return s1[0].equals(s2[0]) ?
2817                    PackageManager.SIGNATURE_MATCH :
2818                    PackageManager.SIGNATURE_NO_MATCH;
2819        }
2820
2821        ArraySet<Signature> set1 = new ArraySet<Signature>();
2822        for (Signature sig : s1) {
2823            set1.add(sig);
2824        }
2825        ArraySet<Signature> set2 = new ArraySet<Signature>();
2826        for (Signature sig : s2) {
2827            set2.add(sig);
2828        }
2829        // Make sure s2 contains all signatures in s1.
2830        if (set1.equals(set2)) {
2831            return PackageManager.SIGNATURE_MATCH;
2832        }
2833        return PackageManager.SIGNATURE_NO_MATCH;
2834    }
2835
2836    /**
2837     * If the database version for this type of package (internal storage or
2838     * external storage) is less than the version where package signatures
2839     * were updated, return true.
2840     */
2841    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2842        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2843                DatabaseVersion.SIGNATURE_END_ENTITY))
2844                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2845                        DatabaseVersion.SIGNATURE_END_ENTITY));
2846    }
2847
2848    /**
2849     * Used for backward compatibility to make sure any packages with
2850     * certificate chains get upgraded to the new style. {@code existingSigs}
2851     * will be in the old format (since they were stored on disk from before the
2852     * system upgrade) and {@code scannedSigs} will be in the newer format.
2853     */
2854    private int compareSignaturesCompat(PackageSignatures existingSigs,
2855            PackageParser.Package scannedPkg) {
2856        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2857            return PackageManager.SIGNATURE_NO_MATCH;
2858        }
2859
2860        ArraySet<Signature> existingSet = new ArraySet<Signature>();
2861        for (Signature sig : existingSigs.mSignatures) {
2862            existingSet.add(sig);
2863        }
2864        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
2865        for (Signature sig : scannedPkg.mSignatures) {
2866            try {
2867                Signature[] chainSignatures = sig.getChainSignatures();
2868                for (Signature chainSig : chainSignatures) {
2869                    scannedCompatSet.add(chainSig);
2870                }
2871            } catch (CertificateEncodingException e) {
2872                scannedCompatSet.add(sig);
2873            }
2874        }
2875        /*
2876         * Make sure the expanded scanned set contains all signatures in the
2877         * existing one.
2878         */
2879        if (scannedCompatSet.equals(existingSet)) {
2880            // Migrate the old signatures to the new scheme.
2881            existingSigs.assignSignatures(scannedPkg.mSignatures);
2882            // The new KeySets will be re-added later in the scanning process.
2883            synchronized (mPackages) {
2884                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2885            }
2886            return PackageManager.SIGNATURE_MATCH;
2887        }
2888        return PackageManager.SIGNATURE_NO_MATCH;
2889    }
2890
2891    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2892        if (isExternal(scannedPkg)) {
2893            return mSettings.isExternalDatabaseVersionOlderThan(
2894                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
2895        } else {
2896            return mSettings.isInternalDatabaseVersionOlderThan(
2897                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
2898        }
2899    }
2900
2901    private int compareSignaturesRecover(PackageSignatures existingSigs,
2902            PackageParser.Package scannedPkg) {
2903        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
2904            return PackageManager.SIGNATURE_NO_MATCH;
2905        }
2906
2907        String msg = null;
2908        try {
2909            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
2910                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
2911                        + scannedPkg.packageName);
2912                return PackageManager.SIGNATURE_MATCH;
2913            }
2914        } catch (CertificateException e) {
2915            msg = e.getMessage();
2916        }
2917
2918        logCriticalInfo(Log.INFO,
2919                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
2920        return PackageManager.SIGNATURE_NO_MATCH;
2921    }
2922
2923    @Override
2924    public String[] getPackagesForUid(int uid) {
2925        uid = UserHandle.getAppId(uid);
2926        // reader
2927        synchronized (mPackages) {
2928            Object obj = mSettings.getUserIdLPr(uid);
2929            if (obj instanceof SharedUserSetting) {
2930                final SharedUserSetting sus = (SharedUserSetting) obj;
2931                final int N = sus.packages.size();
2932                final String[] res = new String[N];
2933                final Iterator<PackageSetting> it = sus.packages.iterator();
2934                int i = 0;
2935                while (it.hasNext()) {
2936                    res[i++] = it.next().name;
2937                }
2938                return res;
2939            } else if (obj instanceof PackageSetting) {
2940                final PackageSetting ps = (PackageSetting) obj;
2941                return new String[] { ps.name };
2942            }
2943        }
2944        return null;
2945    }
2946
2947    @Override
2948    public String getNameForUid(int uid) {
2949        // reader
2950        synchronized (mPackages) {
2951            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2952            if (obj instanceof SharedUserSetting) {
2953                final SharedUserSetting sus = (SharedUserSetting) obj;
2954                return sus.name + ":" + sus.userId;
2955            } else if (obj instanceof PackageSetting) {
2956                final PackageSetting ps = (PackageSetting) obj;
2957                return ps.name;
2958            }
2959        }
2960        return null;
2961    }
2962
2963    @Override
2964    public int getUidForSharedUser(String sharedUserName) {
2965        if(sharedUserName == null) {
2966            return -1;
2967        }
2968        // reader
2969        synchronized (mPackages) {
2970            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
2971            if (suid == null) {
2972                return -1;
2973            }
2974            return suid.userId;
2975        }
2976    }
2977
2978    @Override
2979    public int getFlagsForUid(int uid) {
2980        synchronized (mPackages) {
2981            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2982            if (obj instanceof SharedUserSetting) {
2983                final SharedUserSetting sus = (SharedUserSetting) obj;
2984                return sus.pkgFlags;
2985            } else if (obj instanceof PackageSetting) {
2986                final PackageSetting ps = (PackageSetting) obj;
2987                return ps.pkgFlags;
2988            }
2989        }
2990        return 0;
2991    }
2992
2993    @Override
2994    public int getPrivateFlagsForUid(int uid) {
2995        synchronized (mPackages) {
2996            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2997            if (obj instanceof SharedUserSetting) {
2998                final SharedUserSetting sus = (SharedUserSetting) obj;
2999                return sus.pkgPrivateFlags;
3000            } else if (obj instanceof PackageSetting) {
3001                final PackageSetting ps = (PackageSetting) obj;
3002                return ps.pkgPrivateFlags;
3003            }
3004        }
3005        return 0;
3006    }
3007
3008    @Override
3009    public boolean isUidPrivileged(int uid) {
3010        uid = UserHandle.getAppId(uid);
3011        // reader
3012        synchronized (mPackages) {
3013            Object obj = mSettings.getUserIdLPr(uid);
3014            if (obj instanceof SharedUserSetting) {
3015                final SharedUserSetting sus = (SharedUserSetting) obj;
3016                final Iterator<PackageSetting> it = sus.packages.iterator();
3017                while (it.hasNext()) {
3018                    if (it.next().isPrivileged()) {
3019                        return true;
3020                    }
3021                }
3022            } else if (obj instanceof PackageSetting) {
3023                final PackageSetting ps = (PackageSetting) obj;
3024                return ps.isPrivileged();
3025            }
3026        }
3027        return false;
3028    }
3029
3030    @Override
3031    public String[] getAppOpPermissionPackages(String permissionName) {
3032        synchronized (mPackages) {
3033            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3034            if (pkgs == null) {
3035                return null;
3036            }
3037            return pkgs.toArray(new String[pkgs.size()]);
3038        }
3039    }
3040
3041    @Override
3042    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3043            int flags, int userId) {
3044        if (!sUserManager.exists(userId)) return null;
3045        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3046        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3047        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3048    }
3049
3050    @Override
3051    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3052            IntentFilter filter, int match, ComponentName activity) {
3053        final int userId = UserHandle.getCallingUserId();
3054        if (DEBUG_PREFERRED) {
3055            Log.v(TAG, "setLastChosenActivity intent=" + intent
3056                + " resolvedType=" + resolvedType
3057                + " flags=" + flags
3058                + " filter=" + filter
3059                + " match=" + match
3060                + " activity=" + activity);
3061            filter.dump(new PrintStreamPrinter(System.out), "    ");
3062        }
3063        intent.setComponent(null);
3064        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3065        // Find any earlier preferred or last chosen entries and nuke them
3066        findPreferredActivity(intent, resolvedType,
3067                flags, query, 0, false, true, false, userId);
3068        // Add the new activity as the last chosen for this filter
3069        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3070                "Setting last chosen");
3071    }
3072
3073    @Override
3074    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3075        final int userId = UserHandle.getCallingUserId();
3076        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3077        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3078        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3079                false, false, false, userId);
3080    }
3081
3082    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3083            int flags, List<ResolveInfo> query, int userId) {
3084        if (query != null) {
3085            final int N = query.size();
3086            if (N == 1) {
3087                return query.get(0);
3088            } else if (N > 1) {
3089                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3090                // If there is more than one activity with the same priority,
3091                // then let the user decide between them.
3092                ResolveInfo r0 = query.get(0);
3093                ResolveInfo r1 = query.get(1);
3094                if (DEBUG_INTENT_MATCHING || debug) {
3095                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3096                            + r1.activityInfo.name + "=" + r1.priority);
3097                }
3098                // If the first activity has a higher priority, or a different
3099                // default, then it is always desireable to pick it.
3100                if (r0.priority != r1.priority
3101                        || r0.preferredOrder != r1.preferredOrder
3102                        || r0.isDefault != r1.isDefault) {
3103                    return query.get(0);
3104                }
3105                // If we have saved a preference for a preferred activity for
3106                // this Intent, use that.
3107                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3108                        flags, query, r0.priority, true, false, debug, userId);
3109                if (ri != null) {
3110                    return ri;
3111                }
3112                if (userId != 0) {
3113                    ri = new ResolveInfo(mResolveInfo);
3114                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3115                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3116                            ri.activityInfo.applicationInfo);
3117                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3118                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3119                    return ri;
3120                }
3121                return mResolveInfo;
3122            }
3123        }
3124        return null;
3125    }
3126
3127    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3128            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3129        final int N = query.size();
3130        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3131                .get(userId);
3132        // Get the list of persistent preferred activities that handle the intent
3133        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3134        List<PersistentPreferredActivity> pprefs = ppir != null
3135                ? ppir.queryIntent(intent, resolvedType,
3136                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3137                : null;
3138        if (pprefs != null && pprefs.size() > 0) {
3139            final int M = pprefs.size();
3140            for (int i=0; i<M; i++) {
3141                final PersistentPreferredActivity ppa = pprefs.get(i);
3142                if (DEBUG_PREFERRED || debug) {
3143                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3144                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3145                            + "\n  component=" + ppa.mComponent);
3146                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3147                }
3148                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3149                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3150                if (DEBUG_PREFERRED || debug) {
3151                    Slog.v(TAG, "Found persistent preferred activity:");
3152                    if (ai != null) {
3153                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3154                    } else {
3155                        Slog.v(TAG, "  null");
3156                    }
3157                }
3158                if (ai == null) {
3159                    // This previously registered persistent preferred activity
3160                    // component is no longer known. Ignore it and do NOT remove it.
3161                    continue;
3162                }
3163                for (int j=0; j<N; j++) {
3164                    final ResolveInfo ri = query.get(j);
3165                    if (!ri.activityInfo.applicationInfo.packageName
3166                            .equals(ai.applicationInfo.packageName)) {
3167                        continue;
3168                    }
3169                    if (!ri.activityInfo.name.equals(ai.name)) {
3170                        continue;
3171                    }
3172                    //  Found a persistent preference that can handle the intent.
3173                    if (DEBUG_PREFERRED || debug) {
3174                        Slog.v(TAG, "Returning persistent preferred activity: " +
3175                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3176                    }
3177                    return ri;
3178                }
3179            }
3180        }
3181        return null;
3182    }
3183
3184    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3185            List<ResolveInfo> query, int priority, boolean always,
3186            boolean removeMatches, boolean debug, int userId) {
3187        if (!sUserManager.exists(userId)) return null;
3188        // writer
3189        synchronized (mPackages) {
3190            if (intent.getSelector() != null) {
3191                intent = intent.getSelector();
3192            }
3193            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3194
3195            // Try to find a matching persistent preferred activity.
3196            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3197                    debug, userId);
3198
3199            // If a persistent preferred activity matched, use it.
3200            if (pri != null) {
3201                return pri;
3202            }
3203
3204            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3205            // Get the list of preferred activities that handle the intent
3206            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3207            List<PreferredActivity> prefs = pir != null
3208                    ? pir.queryIntent(intent, resolvedType,
3209                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3210                    : null;
3211            if (prefs != null && prefs.size() > 0) {
3212                boolean changed = false;
3213                try {
3214                    // First figure out how good the original match set is.
3215                    // We will only allow preferred activities that came
3216                    // from the same match quality.
3217                    int match = 0;
3218
3219                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3220
3221                    final int N = query.size();
3222                    for (int j=0; j<N; j++) {
3223                        final ResolveInfo ri = query.get(j);
3224                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3225                                + ": 0x" + Integer.toHexString(match));
3226                        if (ri.match > match) {
3227                            match = ri.match;
3228                        }
3229                    }
3230
3231                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3232                            + Integer.toHexString(match));
3233
3234                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3235                    final int M = prefs.size();
3236                    for (int i=0; i<M; i++) {
3237                        final PreferredActivity pa = prefs.get(i);
3238                        if (DEBUG_PREFERRED || debug) {
3239                            Slog.v(TAG, "Checking PreferredActivity ds="
3240                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3241                                    + "\n  component=" + pa.mPref.mComponent);
3242                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3243                        }
3244                        if (pa.mPref.mMatch != match) {
3245                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3246                                    + Integer.toHexString(pa.mPref.mMatch));
3247                            continue;
3248                        }
3249                        // If it's not an "always" type preferred activity and that's what we're
3250                        // looking for, skip it.
3251                        if (always && !pa.mPref.mAlways) {
3252                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3253                            continue;
3254                        }
3255                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3256                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3257                        if (DEBUG_PREFERRED || debug) {
3258                            Slog.v(TAG, "Found preferred activity:");
3259                            if (ai != null) {
3260                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3261                            } else {
3262                                Slog.v(TAG, "  null");
3263                            }
3264                        }
3265                        if (ai == null) {
3266                            // This previously registered preferred activity
3267                            // component is no longer known.  Most likely an update
3268                            // to the app was installed and in the new version this
3269                            // component no longer exists.  Clean it up by removing
3270                            // it from the preferred activities list, and skip it.
3271                            Slog.w(TAG, "Removing dangling preferred activity: "
3272                                    + pa.mPref.mComponent);
3273                            pir.removeFilter(pa);
3274                            changed = true;
3275                            continue;
3276                        }
3277                        for (int j=0; j<N; j++) {
3278                            final ResolveInfo ri = query.get(j);
3279                            if (!ri.activityInfo.applicationInfo.packageName
3280                                    .equals(ai.applicationInfo.packageName)) {
3281                                continue;
3282                            }
3283                            if (!ri.activityInfo.name.equals(ai.name)) {
3284                                continue;
3285                            }
3286
3287                            if (removeMatches) {
3288                                pir.removeFilter(pa);
3289                                changed = true;
3290                                if (DEBUG_PREFERRED) {
3291                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3292                                }
3293                                break;
3294                            }
3295
3296                            // Okay we found a previously set preferred or last chosen app.
3297                            // If the result set is different from when this
3298                            // was created, we need to clear it and re-ask the
3299                            // user their preference, if we're looking for an "always" type entry.
3300                            if (always && !pa.mPref.sameSet(query)) {
3301                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3302                                        + intent + " type " + resolvedType);
3303                                if (DEBUG_PREFERRED) {
3304                                    Slog.v(TAG, "Removing preferred activity since set changed "
3305                                            + pa.mPref.mComponent);
3306                                }
3307                                pir.removeFilter(pa);
3308                                // Re-add the filter as a "last chosen" entry (!always)
3309                                PreferredActivity lastChosen = new PreferredActivity(
3310                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3311                                pir.addFilter(lastChosen);
3312                                changed = true;
3313                                return null;
3314                            }
3315
3316                            // Yay! Either the set matched or we're looking for the last chosen
3317                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3318                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3319                            return ri;
3320                        }
3321                    }
3322                } finally {
3323                    if (changed) {
3324                        if (DEBUG_PREFERRED) {
3325                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3326                        }
3327                        scheduleWritePackageRestrictionsLocked(userId);
3328                    }
3329                }
3330            }
3331        }
3332        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3333        return null;
3334    }
3335
3336    /*
3337     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3338     */
3339    @Override
3340    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3341            int targetUserId) {
3342        mContext.enforceCallingOrSelfPermission(
3343                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3344        List<CrossProfileIntentFilter> matches =
3345                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3346        if (matches != null) {
3347            int size = matches.size();
3348            for (int i = 0; i < size; i++) {
3349                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3350            }
3351        }
3352        return false;
3353    }
3354
3355    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3356            String resolvedType, int userId) {
3357        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3358        if (resolver != null) {
3359            return resolver.queryIntent(intent, resolvedType, false, userId);
3360        }
3361        return null;
3362    }
3363
3364    @Override
3365    public List<ResolveInfo> queryIntentActivities(Intent intent,
3366            String resolvedType, int flags, int userId) {
3367        if (!sUserManager.exists(userId)) return Collections.emptyList();
3368        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3369        ComponentName comp = intent.getComponent();
3370        if (comp == null) {
3371            if (intent.getSelector() != null) {
3372                intent = intent.getSelector();
3373                comp = intent.getComponent();
3374            }
3375        }
3376
3377        if (comp != null) {
3378            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3379            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3380            if (ai != null) {
3381                final ResolveInfo ri = new ResolveInfo();
3382                ri.activityInfo = ai;
3383                list.add(ri);
3384            }
3385            return list;
3386        }
3387
3388        // reader
3389        synchronized (mPackages) {
3390            final String pkgName = intent.getPackage();
3391            if (pkgName == null) {
3392                List<CrossProfileIntentFilter> matchingFilters =
3393                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3394                // Check for results that need to skip the current profile.
3395                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3396                        resolvedType, flags, userId);
3397                if (resolveInfo != null) {
3398                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3399                    result.add(resolveInfo);
3400                    return result;
3401                }
3402                // Check for cross profile results.
3403                resolveInfo = queryCrossProfileIntents(
3404                        matchingFilters, intent, resolvedType, flags, userId);
3405
3406                // Check for results in the current profile.
3407                List<ResolveInfo> result = mActivities.queryIntent(
3408                        intent, resolvedType, flags, userId);
3409                if (resolveInfo != null) {
3410                    result.add(resolveInfo);
3411                    Collections.sort(result, mResolvePrioritySorter);
3412                }
3413                return result;
3414            }
3415            final PackageParser.Package pkg = mPackages.get(pkgName);
3416            if (pkg != null) {
3417                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3418                        pkg.activities, userId);
3419            }
3420            return new ArrayList<ResolveInfo>();
3421        }
3422    }
3423
3424    private ResolveInfo querySkipCurrentProfileIntents(
3425            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3426            int flags, int sourceUserId) {
3427        if (matchingFilters != null) {
3428            int size = matchingFilters.size();
3429            for (int i = 0; i < size; i ++) {
3430                CrossProfileIntentFilter filter = matchingFilters.get(i);
3431                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3432                    // Checking if there are activities in the target user that can handle the
3433                    // intent.
3434                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3435                            flags, sourceUserId);
3436                    if (resolveInfo != null) {
3437                        return resolveInfo;
3438                    }
3439                }
3440            }
3441        }
3442        return null;
3443    }
3444
3445    // Return matching ResolveInfo if any for skip current profile intent filters.
3446    private ResolveInfo queryCrossProfileIntents(
3447            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3448            int flags, int sourceUserId) {
3449        if (matchingFilters != null) {
3450            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3451            // match the same intent. For performance reasons, it is better not to
3452            // run queryIntent twice for the same userId
3453            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3454            int size = matchingFilters.size();
3455            for (int i = 0; i < size; i++) {
3456                CrossProfileIntentFilter filter = matchingFilters.get(i);
3457                int targetUserId = filter.getTargetUserId();
3458                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3459                        && !alreadyTriedUserIds.get(targetUserId)) {
3460                    // Checking if there are activities in the target user that can handle the
3461                    // intent.
3462                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3463                            flags, sourceUserId);
3464                    if (resolveInfo != null) return resolveInfo;
3465                    alreadyTriedUserIds.put(targetUserId, true);
3466                }
3467            }
3468        }
3469        return null;
3470    }
3471
3472    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3473            String resolvedType, int flags, int sourceUserId) {
3474        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3475                resolvedType, flags, filter.getTargetUserId());
3476        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3477            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3478        }
3479        return null;
3480    }
3481
3482    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3483            int sourceUserId, int targetUserId) {
3484        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3485        String className;
3486        if (targetUserId == UserHandle.USER_OWNER) {
3487            className = FORWARD_INTENT_TO_USER_OWNER;
3488        } else {
3489            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3490        }
3491        ComponentName forwardingActivityComponentName = new ComponentName(
3492                mAndroidApplication.packageName, className);
3493        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3494                sourceUserId);
3495        if (targetUserId == UserHandle.USER_OWNER) {
3496            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3497            forwardingResolveInfo.noResourceId = true;
3498        }
3499        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3500        forwardingResolveInfo.priority = 0;
3501        forwardingResolveInfo.preferredOrder = 0;
3502        forwardingResolveInfo.match = 0;
3503        forwardingResolveInfo.isDefault = true;
3504        forwardingResolveInfo.filter = filter;
3505        forwardingResolveInfo.targetUserId = targetUserId;
3506        return forwardingResolveInfo;
3507    }
3508
3509    @Override
3510    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3511            Intent[] specifics, String[] specificTypes, Intent intent,
3512            String resolvedType, int flags, int userId) {
3513        if (!sUserManager.exists(userId)) return Collections.emptyList();
3514        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3515                false, "query intent activity options");
3516        final String resultsAction = intent.getAction();
3517
3518        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3519                | PackageManager.GET_RESOLVED_FILTER, userId);
3520
3521        if (DEBUG_INTENT_MATCHING) {
3522            Log.v(TAG, "Query " + intent + ": " + results);
3523        }
3524
3525        int specificsPos = 0;
3526        int N;
3527
3528        // todo: note that the algorithm used here is O(N^2).  This
3529        // isn't a problem in our current environment, but if we start running
3530        // into situations where we have more than 5 or 10 matches then this
3531        // should probably be changed to something smarter...
3532
3533        // First we go through and resolve each of the specific items
3534        // that were supplied, taking care of removing any corresponding
3535        // duplicate items in the generic resolve list.
3536        if (specifics != null) {
3537            for (int i=0; i<specifics.length; i++) {
3538                final Intent sintent = specifics[i];
3539                if (sintent == null) {
3540                    continue;
3541                }
3542
3543                if (DEBUG_INTENT_MATCHING) {
3544                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3545                }
3546
3547                String action = sintent.getAction();
3548                if (resultsAction != null && resultsAction.equals(action)) {
3549                    // If this action was explicitly requested, then don't
3550                    // remove things that have it.
3551                    action = null;
3552                }
3553
3554                ResolveInfo ri = null;
3555                ActivityInfo ai = null;
3556
3557                ComponentName comp = sintent.getComponent();
3558                if (comp == null) {
3559                    ri = resolveIntent(
3560                        sintent,
3561                        specificTypes != null ? specificTypes[i] : null,
3562                            flags, userId);
3563                    if (ri == null) {
3564                        continue;
3565                    }
3566                    if (ri == mResolveInfo) {
3567                        // ACK!  Must do something better with this.
3568                    }
3569                    ai = ri.activityInfo;
3570                    comp = new ComponentName(ai.applicationInfo.packageName,
3571                            ai.name);
3572                } else {
3573                    ai = getActivityInfo(comp, flags, userId);
3574                    if (ai == null) {
3575                        continue;
3576                    }
3577                }
3578
3579                // Look for any generic query activities that are duplicates
3580                // of this specific one, and remove them from the results.
3581                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3582                N = results.size();
3583                int j;
3584                for (j=specificsPos; j<N; j++) {
3585                    ResolveInfo sri = results.get(j);
3586                    if ((sri.activityInfo.name.equals(comp.getClassName())
3587                            && sri.activityInfo.applicationInfo.packageName.equals(
3588                                    comp.getPackageName()))
3589                        || (action != null && sri.filter.matchAction(action))) {
3590                        results.remove(j);
3591                        if (DEBUG_INTENT_MATCHING) Log.v(
3592                            TAG, "Removing duplicate item from " + j
3593                            + " due to specific " + specificsPos);
3594                        if (ri == null) {
3595                            ri = sri;
3596                        }
3597                        j--;
3598                        N--;
3599                    }
3600                }
3601
3602                // Add this specific item to its proper place.
3603                if (ri == null) {
3604                    ri = new ResolveInfo();
3605                    ri.activityInfo = ai;
3606                }
3607                results.add(specificsPos, ri);
3608                ri.specificIndex = i;
3609                specificsPos++;
3610            }
3611        }
3612
3613        // Now we go through the remaining generic results and remove any
3614        // duplicate actions that are found here.
3615        N = results.size();
3616        for (int i=specificsPos; i<N-1; i++) {
3617            final ResolveInfo rii = results.get(i);
3618            if (rii.filter == null) {
3619                continue;
3620            }
3621
3622            // Iterate over all of the actions of this result's intent
3623            // filter...  typically this should be just one.
3624            final Iterator<String> it = rii.filter.actionsIterator();
3625            if (it == null) {
3626                continue;
3627            }
3628            while (it.hasNext()) {
3629                final String action = it.next();
3630                if (resultsAction != null && resultsAction.equals(action)) {
3631                    // If this action was explicitly requested, then don't
3632                    // remove things that have it.
3633                    continue;
3634                }
3635                for (int j=i+1; j<N; j++) {
3636                    final ResolveInfo rij = results.get(j);
3637                    if (rij.filter != null && rij.filter.hasAction(action)) {
3638                        results.remove(j);
3639                        if (DEBUG_INTENT_MATCHING) Log.v(
3640                            TAG, "Removing duplicate item from " + j
3641                            + " due to action " + action + " at " + i);
3642                        j--;
3643                        N--;
3644                    }
3645                }
3646            }
3647
3648            // If the caller didn't request filter information, drop it now
3649            // so we don't have to marshall/unmarshall it.
3650            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3651                rii.filter = null;
3652            }
3653        }
3654
3655        // Filter out the caller activity if so requested.
3656        if (caller != null) {
3657            N = results.size();
3658            for (int i=0; i<N; i++) {
3659                ActivityInfo ainfo = results.get(i).activityInfo;
3660                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3661                        && caller.getClassName().equals(ainfo.name)) {
3662                    results.remove(i);
3663                    break;
3664                }
3665            }
3666        }
3667
3668        // If the caller didn't request filter information,
3669        // drop them now so we don't have to
3670        // marshall/unmarshall it.
3671        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3672            N = results.size();
3673            for (int i=0; i<N; i++) {
3674                results.get(i).filter = null;
3675            }
3676        }
3677
3678        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3679        return results;
3680    }
3681
3682    @Override
3683    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3684            int userId) {
3685        if (!sUserManager.exists(userId)) return Collections.emptyList();
3686        ComponentName comp = intent.getComponent();
3687        if (comp == null) {
3688            if (intent.getSelector() != null) {
3689                intent = intent.getSelector();
3690                comp = intent.getComponent();
3691            }
3692        }
3693        if (comp != null) {
3694            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3695            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3696            if (ai != null) {
3697                ResolveInfo ri = new ResolveInfo();
3698                ri.activityInfo = ai;
3699                list.add(ri);
3700            }
3701            return list;
3702        }
3703
3704        // reader
3705        synchronized (mPackages) {
3706            String pkgName = intent.getPackage();
3707            if (pkgName == null) {
3708                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3709            }
3710            final PackageParser.Package pkg = mPackages.get(pkgName);
3711            if (pkg != null) {
3712                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3713                        userId);
3714            }
3715            return null;
3716        }
3717    }
3718
3719    @Override
3720    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3721        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3722        if (!sUserManager.exists(userId)) return null;
3723        if (query != null) {
3724            if (query.size() >= 1) {
3725                // If there is more than one service with the same priority,
3726                // just arbitrarily pick the first one.
3727                return query.get(0);
3728            }
3729        }
3730        return null;
3731    }
3732
3733    @Override
3734    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3735            int userId) {
3736        if (!sUserManager.exists(userId)) return Collections.emptyList();
3737        ComponentName comp = intent.getComponent();
3738        if (comp == null) {
3739            if (intent.getSelector() != null) {
3740                intent = intent.getSelector();
3741                comp = intent.getComponent();
3742            }
3743        }
3744        if (comp != null) {
3745            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3746            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3747            if (si != null) {
3748                final ResolveInfo ri = new ResolveInfo();
3749                ri.serviceInfo = si;
3750                list.add(ri);
3751            }
3752            return list;
3753        }
3754
3755        // reader
3756        synchronized (mPackages) {
3757            String pkgName = intent.getPackage();
3758            if (pkgName == null) {
3759                return mServices.queryIntent(intent, resolvedType, flags, userId);
3760            }
3761            final PackageParser.Package pkg = mPackages.get(pkgName);
3762            if (pkg != null) {
3763                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3764                        userId);
3765            }
3766            return null;
3767        }
3768    }
3769
3770    @Override
3771    public List<ResolveInfo> queryIntentContentProviders(
3772            Intent intent, String resolvedType, int flags, int userId) {
3773        if (!sUserManager.exists(userId)) return Collections.emptyList();
3774        ComponentName comp = intent.getComponent();
3775        if (comp == null) {
3776            if (intent.getSelector() != null) {
3777                intent = intent.getSelector();
3778                comp = intent.getComponent();
3779            }
3780        }
3781        if (comp != null) {
3782            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3783            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3784            if (pi != null) {
3785                final ResolveInfo ri = new ResolveInfo();
3786                ri.providerInfo = pi;
3787                list.add(ri);
3788            }
3789            return list;
3790        }
3791
3792        // reader
3793        synchronized (mPackages) {
3794            String pkgName = intent.getPackage();
3795            if (pkgName == null) {
3796                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3797            }
3798            final PackageParser.Package pkg = mPackages.get(pkgName);
3799            if (pkg != null) {
3800                return mProviders.queryIntentForPackage(
3801                        intent, resolvedType, flags, pkg.providers, userId);
3802            }
3803            return null;
3804        }
3805    }
3806
3807    @Override
3808    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3809        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3810
3811        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3812
3813        // writer
3814        synchronized (mPackages) {
3815            ArrayList<PackageInfo> list;
3816            if (listUninstalled) {
3817                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3818                for (PackageSetting ps : mSettings.mPackages.values()) {
3819                    PackageInfo pi;
3820                    if (ps.pkg != null) {
3821                        pi = generatePackageInfo(ps.pkg, flags, userId);
3822                    } else {
3823                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3824                    }
3825                    if (pi != null) {
3826                        list.add(pi);
3827                    }
3828                }
3829            } else {
3830                list = new ArrayList<PackageInfo>(mPackages.size());
3831                for (PackageParser.Package p : mPackages.values()) {
3832                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3833                    if (pi != null) {
3834                        list.add(pi);
3835                    }
3836                }
3837            }
3838
3839            return new ParceledListSlice<PackageInfo>(list);
3840        }
3841    }
3842
3843    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3844            String[] permissions, boolean[] tmp, int flags, int userId) {
3845        int numMatch = 0;
3846        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3847        for (int i=0; i<permissions.length; i++) {
3848            if (gp.grantedPermissions.contains(permissions[i])) {
3849                tmp[i] = true;
3850                numMatch++;
3851            } else {
3852                tmp[i] = false;
3853            }
3854        }
3855        if (numMatch == 0) {
3856            return;
3857        }
3858        PackageInfo pi;
3859        if (ps.pkg != null) {
3860            pi = generatePackageInfo(ps.pkg, flags, userId);
3861        } else {
3862            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3863        }
3864        // The above might return null in cases of uninstalled apps or install-state
3865        // skew across users/profiles.
3866        if (pi != null) {
3867            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3868                if (numMatch == permissions.length) {
3869                    pi.requestedPermissions = permissions;
3870                } else {
3871                    pi.requestedPermissions = new String[numMatch];
3872                    numMatch = 0;
3873                    for (int i=0; i<permissions.length; i++) {
3874                        if (tmp[i]) {
3875                            pi.requestedPermissions[numMatch] = permissions[i];
3876                            numMatch++;
3877                        }
3878                    }
3879                }
3880            }
3881            list.add(pi);
3882        }
3883    }
3884
3885    @Override
3886    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3887            String[] permissions, int flags, int userId) {
3888        if (!sUserManager.exists(userId)) return null;
3889        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3890
3891        // writer
3892        synchronized (mPackages) {
3893            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3894            boolean[] tmpBools = new boolean[permissions.length];
3895            if (listUninstalled) {
3896                for (PackageSetting ps : mSettings.mPackages.values()) {
3897                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3898                }
3899            } else {
3900                for (PackageParser.Package pkg : mPackages.values()) {
3901                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3902                    if (ps != null) {
3903                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3904                                userId);
3905                    }
3906                }
3907            }
3908
3909            return new ParceledListSlice<PackageInfo>(list);
3910        }
3911    }
3912
3913    @Override
3914    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3915        if (!sUserManager.exists(userId)) return null;
3916        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3917
3918        // writer
3919        synchronized (mPackages) {
3920            ArrayList<ApplicationInfo> list;
3921            if (listUninstalled) {
3922                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3923                for (PackageSetting ps : mSettings.mPackages.values()) {
3924                    ApplicationInfo ai;
3925                    if (ps.pkg != null) {
3926                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3927                                ps.readUserState(userId), userId);
3928                    } else {
3929                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3930                    }
3931                    if (ai != null) {
3932                        list.add(ai);
3933                    }
3934                }
3935            } else {
3936                list = new ArrayList<ApplicationInfo>(mPackages.size());
3937                for (PackageParser.Package p : mPackages.values()) {
3938                    if (p.mExtras != null) {
3939                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3940                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3941                        if (ai != null) {
3942                            list.add(ai);
3943                        }
3944                    }
3945                }
3946            }
3947
3948            return new ParceledListSlice<ApplicationInfo>(list);
3949        }
3950    }
3951
3952    public List<ApplicationInfo> getPersistentApplications(int flags) {
3953        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3954
3955        // reader
3956        synchronized (mPackages) {
3957            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3958            final int userId = UserHandle.getCallingUserId();
3959            while (i.hasNext()) {
3960                final PackageParser.Package p = i.next();
3961                if (p.applicationInfo != null
3962                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3963                        && (!mSafeMode || isSystemApp(p))) {
3964                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3965                    if (ps != null) {
3966                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3967                                ps.readUserState(userId), userId);
3968                        if (ai != null) {
3969                            finalList.add(ai);
3970                        }
3971                    }
3972                }
3973            }
3974        }
3975
3976        return finalList;
3977    }
3978
3979    @Override
3980    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3981        if (!sUserManager.exists(userId)) return null;
3982        // reader
3983        synchronized (mPackages) {
3984            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3985            PackageSetting ps = provider != null
3986                    ? mSettings.mPackages.get(provider.owner.packageName)
3987                    : null;
3988            return ps != null
3989                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3990                    && (!mSafeMode || (provider.info.applicationInfo.flags
3991                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3992                    ? PackageParser.generateProviderInfo(provider, flags,
3993                            ps.readUserState(userId), userId)
3994                    : null;
3995        }
3996    }
3997
3998    /**
3999     * @deprecated
4000     */
4001    @Deprecated
4002    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4003        // reader
4004        synchronized (mPackages) {
4005            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4006                    .entrySet().iterator();
4007            final int userId = UserHandle.getCallingUserId();
4008            while (i.hasNext()) {
4009                Map.Entry<String, PackageParser.Provider> entry = i.next();
4010                PackageParser.Provider p = entry.getValue();
4011                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4012
4013                if (ps != null && p.syncable
4014                        && (!mSafeMode || (p.info.applicationInfo.flags
4015                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4016                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4017                            ps.readUserState(userId), userId);
4018                    if (info != null) {
4019                        outNames.add(entry.getKey());
4020                        outInfo.add(info);
4021                    }
4022                }
4023            }
4024        }
4025    }
4026
4027    @Override
4028    public List<ProviderInfo> queryContentProviders(String processName,
4029            int uid, int flags) {
4030        ArrayList<ProviderInfo> finalList = null;
4031        // reader
4032        synchronized (mPackages) {
4033            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4034            final int userId = processName != null ?
4035                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4036            while (i.hasNext()) {
4037                final PackageParser.Provider p = i.next();
4038                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4039                if (ps != null && p.info.authority != null
4040                        && (processName == null
4041                                || (p.info.processName.equals(processName)
4042                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4043                        && mSettings.isEnabledLPr(p.info, flags, userId)
4044                        && (!mSafeMode
4045                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4046                    if (finalList == null) {
4047                        finalList = new ArrayList<ProviderInfo>(3);
4048                    }
4049                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4050                            ps.readUserState(userId), userId);
4051                    if (info != null) {
4052                        finalList.add(info);
4053                    }
4054                }
4055            }
4056        }
4057
4058        if (finalList != null) {
4059            Collections.sort(finalList, mProviderInitOrderSorter);
4060        }
4061
4062        return finalList;
4063    }
4064
4065    @Override
4066    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4067            int flags) {
4068        // reader
4069        synchronized (mPackages) {
4070            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4071            return PackageParser.generateInstrumentationInfo(i, flags);
4072        }
4073    }
4074
4075    @Override
4076    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4077            int flags) {
4078        ArrayList<InstrumentationInfo> finalList =
4079            new ArrayList<InstrumentationInfo>();
4080
4081        // reader
4082        synchronized (mPackages) {
4083            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4084            while (i.hasNext()) {
4085                final PackageParser.Instrumentation p = i.next();
4086                if (targetPackage == null
4087                        || targetPackage.equals(p.info.targetPackage)) {
4088                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4089                            flags);
4090                    if (ii != null) {
4091                        finalList.add(ii);
4092                    }
4093                }
4094            }
4095        }
4096
4097        return finalList;
4098    }
4099
4100    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4101        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4102        if (overlays == null) {
4103            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4104            return;
4105        }
4106        for (PackageParser.Package opkg : overlays.values()) {
4107            // Not much to do if idmap fails: we already logged the error
4108            // and we certainly don't want to abort installation of pkg simply
4109            // because an overlay didn't fit properly. For these reasons,
4110            // ignore the return value of createIdmapForPackagePairLI.
4111            createIdmapForPackagePairLI(pkg, opkg);
4112        }
4113    }
4114
4115    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4116            PackageParser.Package opkg) {
4117        if (!opkg.mTrustedOverlay) {
4118            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4119                    opkg.baseCodePath + ": overlay not trusted");
4120            return false;
4121        }
4122        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4123        if (overlaySet == null) {
4124            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4125                    opkg.baseCodePath + " but target package has no known overlays");
4126            return false;
4127        }
4128        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4129        // TODO: generate idmap for split APKs
4130        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4131            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4132                    + opkg.baseCodePath);
4133            return false;
4134        }
4135        PackageParser.Package[] overlayArray =
4136            overlaySet.values().toArray(new PackageParser.Package[0]);
4137        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4138            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4139                return p1.mOverlayPriority - p2.mOverlayPriority;
4140            }
4141        };
4142        Arrays.sort(overlayArray, cmp);
4143
4144        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4145        int i = 0;
4146        for (PackageParser.Package p : overlayArray) {
4147            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4148        }
4149        return true;
4150    }
4151
4152    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4153        final File[] files = dir.listFiles();
4154        if (ArrayUtils.isEmpty(files)) {
4155            Log.d(TAG, "No files in app dir " + dir);
4156            return;
4157        }
4158
4159        if (DEBUG_PACKAGE_SCANNING) {
4160            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4161                    + " flags=0x" + Integer.toHexString(parseFlags));
4162        }
4163
4164        for (File file : files) {
4165            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4166                    && !PackageInstallerService.isStageName(file.getName());
4167            if (!isPackage) {
4168                // Ignore entries which are not packages
4169                continue;
4170            }
4171            try {
4172                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4173                        scanFlags, currentTime, null);
4174            } catch (PackageManagerException e) {
4175                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4176
4177                // Delete invalid userdata apps
4178                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4179                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4180                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4181                    if (file.isDirectory()) {
4182                        FileUtils.deleteContents(file);
4183                    }
4184                    file.delete();
4185                }
4186            }
4187        }
4188    }
4189
4190    private static File getSettingsProblemFile() {
4191        File dataDir = Environment.getDataDirectory();
4192        File systemDir = new File(dataDir, "system");
4193        File fname = new File(systemDir, "uiderrors.txt");
4194        return fname;
4195    }
4196
4197    static void reportSettingsProblem(int priority, String msg) {
4198        logCriticalInfo(priority, msg);
4199    }
4200
4201    static void logCriticalInfo(int priority, String msg) {
4202        Slog.println(priority, TAG, msg);
4203        EventLogTags.writePmCriticalInfo(msg);
4204        try {
4205            File fname = getSettingsProblemFile();
4206            FileOutputStream out = new FileOutputStream(fname, true);
4207            PrintWriter pw = new FastPrintWriter(out);
4208            SimpleDateFormat formatter = new SimpleDateFormat();
4209            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4210            pw.println(dateString + ": " + msg);
4211            pw.close();
4212            FileUtils.setPermissions(
4213                    fname.toString(),
4214                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4215                    -1, -1);
4216        } catch (java.io.IOException e) {
4217        }
4218    }
4219
4220    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4221            PackageParser.Package pkg, File srcFile, int parseFlags)
4222            throws PackageManagerException {
4223        if (ps != null
4224                && ps.codePath.equals(srcFile)
4225                && ps.timeStamp == srcFile.lastModified()
4226                && !isCompatSignatureUpdateNeeded(pkg)
4227                && !isRecoverSignatureUpdateNeeded(pkg)) {
4228            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4229            if (ps.signatures.mSignatures != null
4230                    && ps.signatures.mSignatures.length != 0
4231                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4232                // Optimization: reuse the existing cached certificates
4233                // if the package appears to be unchanged.
4234                pkg.mSignatures = ps.signatures.mSignatures;
4235                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4236                synchronized (mPackages) {
4237                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4238                }
4239                return;
4240            }
4241
4242            Slog.w(TAG, "PackageSetting for " + ps.name
4243                    + " is missing signatures.  Collecting certs again to recover them.");
4244        } else {
4245            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4246        }
4247
4248        try {
4249            pp.collectCertificates(pkg, parseFlags);
4250            pp.collectManifestDigest(pkg);
4251        } catch (PackageParserException e) {
4252            throw PackageManagerException.from(e);
4253        }
4254    }
4255
4256    /*
4257     *  Scan a package and return the newly parsed package.
4258     *  Returns null in case of errors and the error code is stored in mLastScanError
4259     */
4260    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4261            long currentTime, UserHandle user) throws PackageManagerException {
4262        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4263        parseFlags |= mDefParseFlags;
4264        PackageParser pp = new PackageParser();
4265        pp.setSeparateProcesses(mSeparateProcesses);
4266        pp.setOnlyCoreApps(mOnlyCore);
4267        pp.setDisplayMetrics(mMetrics);
4268
4269        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4270            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4271        }
4272
4273        final PackageParser.Package pkg;
4274        try {
4275            pkg = pp.parsePackage(scanFile, parseFlags);
4276        } catch (PackageParserException e) {
4277            throw PackageManagerException.from(e);
4278        }
4279
4280        PackageSetting ps = null;
4281        PackageSetting updatedPkg;
4282        // reader
4283        synchronized (mPackages) {
4284            // Look to see if we already know about this package.
4285            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4286            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4287                // This package has been renamed to its original name.  Let's
4288                // use that.
4289                ps = mSettings.peekPackageLPr(oldName);
4290            }
4291            // If there was no original package, see one for the real package name.
4292            if (ps == null) {
4293                ps = mSettings.peekPackageLPr(pkg.packageName);
4294            }
4295            // Check to see if this package could be hiding/updating a system
4296            // package.  Must look for it either under the original or real
4297            // package name depending on our state.
4298            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4299            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4300        }
4301        boolean updatedPkgBetter = false;
4302        // First check if this is a system package that may involve an update
4303        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4304            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
4305            // it needs to drop FLAG_PRIVILEGED.
4306            if (locationIsPrivileged(scanFile)) {
4307                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4308            } else {
4309                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4310            }
4311
4312            if (ps != null && !ps.codePath.equals(scanFile)) {
4313                // The path has changed from what was last scanned...  check the
4314                // version of the new path against what we have stored to determine
4315                // what to do.
4316                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4317                if (pkg.mVersionCode <= ps.versionCode) {
4318                    // The system package has been updated and the code path does not match
4319                    // Ignore entry. Skip it.
4320                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
4321                            + " ignored: updated version " + ps.versionCode
4322                            + " better than this " + pkg.mVersionCode);
4323                    if (!updatedPkg.codePath.equals(scanFile)) {
4324                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4325                                + ps.name + " changing from " + updatedPkg.codePathString
4326                                + " to " + scanFile);
4327                        updatedPkg.codePath = scanFile;
4328                        updatedPkg.codePathString = scanFile.toString();
4329                        updatedPkg.resourcePath = scanFile;
4330                        updatedPkg.resourcePathString = scanFile.toString();
4331                    }
4332                    updatedPkg.pkg = pkg;
4333                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4334                } else {
4335                    // The current app on the system partition is better than
4336                    // what we have updated to on the data partition; switch
4337                    // back to the system partition version.
4338                    // At this point, its safely assumed that package installation for
4339                    // apps in system partition will go through. If not there won't be a working
4340                    // version of the app
4341                    // writer
4342                    synchronized (mPackages) {
4343                        // Just remove the loaded entries from package lists.
4344                        mPackages.remove(ps.name);
4345                    }
4346
4347                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4348                            + " reverting from " + ps.codePathString
4349                            + ": new version " + pkg.mVersionCode
4350                            + " better than installed " + ps.versionCode);
4351
4352                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4353                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4354                            getAppDexInstructionSets(ps));
4355                    synchronized (mInstallLock) {
4356                        args.cleanUpResourcesLI();
4357                    }
4358                    synchronized (mPackages) {
4359                        mSettings.enableSystemPackageLPw(ps.name);
4360                    }
4361                    updatedPkgBetter = true;
4362                }
4363            }
4364        }
4365
4366        if (updatedPkg != null) {
4367            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4368            // initially
4369            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4370
4371            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4372            // flag set initially
4373            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
4374                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4375            }
4376        }
4377
4378        // Verify certificates against what was last scanned
4379        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4380
4381        /*
4382         * A new system app appeared, but we already had a non-system one of the
4383         * same name installed earlier.
4384         */
4385        boolean shouldHideSystemApp = false;
4386        if (updatedPkg == null && ps != null
4387                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4388            /*
4389             * Check to make sure the signatures match first. If they don't,
4390             * wipe the installed application and its data.
4391             */
4392            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4393                    != PackageManager.SIGNATURE_MATCH) {
4394                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
4395                        + " signatures don't match existing userdata copy; removing");
4396                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4397                ps = null;
4398            } else {
4399                /*
4400                 * If the newly-added system app is an older version than the
4401                 * already installed version, hide it. It will be scanned later
4402                 * and re-added like an update.
4403                 */
4404                if (pkg.mVersionCode <= ps.versionCode) {
4405                    shouldHideSystemApp = true;
4406                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
4407                            + " but new version " + pkg.mVersionCode + " better than installed "
4408                            + ps.versionCode + "; hiding system");
4409                } else {
4410                    /*
4411                     * The newly found system app is a newer version that the
4412                     * one previously installed. Simply remove the
4413                     * already-installed application and replace it with our own
4414                     * while keeping the application data.
4415                     */
4416                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4417                            + " reverting from " + ps.codePathString + ": new version "
4418                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
4419                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4420                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4421                            getAppDexInstructionSets(ps));
4422                    synchronized (mInstallLock) {
4423                        args.cleanUpResourcesLI();
4424                    }
4425                }
4426            }
4427        }
4428
4429        // The apk is forward locked (not public) if its code and resources
4430        // are kept in different files. (except for app in either system or
4431        // vendor path).
4432        // TODO grab this value from PackageSettings
4433        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4434            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4435                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4436            }
4437        }
4438
4439        // TODO: extend to support forward-locked splits
4440        String resourcePath = null;
4441        String baseResourcePath = null;
4442        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4443            if (ps != null && ps.resourcePathString != null) {
4444                resourcePath = ps.resourcePathString;
4445                baseResourcePath = ps.resourcePathString;
4446            } else {
4447                // Should not happen at all. Just log an error.
4448                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4449            }
4450        } else {
4451            resourcePath = pkg.codePath;
4452            baseResourcePath = pkg.baseCodePath;
4453        }
4454
4455        // Set application objects path explicitly.
4456        pkg.applicationInfo.setCodePath(pkg.codePath);
4457        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4458        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4459        pkg.applicationInfo.setResourcePath(resourcePath);
4460        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4461        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4462
4463        // Note that we invoke the following method only if we are about to unpack an application
4464        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4465                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4466
4467        /*
4468         * If the system app should be overridden by a previously installed
4469         * data, hide the system app now and let the /data/app scan pick it up
4470         * again.
4471         */
4472        if (shouldHideSystemApp) {
4473            synchronized (mPackages) {
4474                /*
4475                 * We have to grant systems permissions before we hide, because
4476                 * grantPermissions will assume the package update is trying to
4477                 * expand its permissions.
4478                 */
4479                grantPermissionsLPw(pkg, true, pkg.packageName);
4480                mSettings.disableSystemPackageLPw(pkg.packageName);
4481            }
4482        }
4483
4484        return scannedPkg;
4485    }
4486
4487    private static String fixProcessName(String defProcessName,
4488            String processName, int uid) {
4489        if (processName == null) {
4490            return defProcessName;
4491        }
4492        return processName;
4493    }
4494
4495    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4496            throws PackageManagerException {
4497        if (pkgSetting.signatures.mSignatures != null) {
4498            // Already existing package. Make sure signatures match
4499            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4500                    == PackageManager.SIGNATURE_MATCH;
4501            if (!match) {
4502                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4503                        == PackageManager.SIGNATURE_MATCH;
4504            }
4505            if (!match) {
4506                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
4507                        == PackageManager.SIGNATURE_MATCH;
4508            }
4509            if (!match) {
4510                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4511                        + pkg.packageName + " signatures do not match the "
4512                        + "previously installed version; ignoring!");
4513            }
4514        }
4515
4516        // Check for shared user signatures
4517        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4518            // Already existing package. Make sure signatures match
4519            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4520                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4521            if (!match) {
4522                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4523                        == PackageManager.SIGNATURE_MATCH;
4524            }
4525            if (!match) {
4526                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
4527                        == PackageManager.SIGNATURE_MATCH;
4528            }
4529            if (!match) {
4530                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4531                        "Package " + pkg.packageName
4532                        + " has no signatures that match those in shared user "
4533                        + pkgSetting.sharedUser.name + "; ignoring!");
4534            }
4535        }
4536    }
4537
4538    /**
4539     * Enforces that only the system UID or root's UID can call a method exposed
4540     * via Binder.
4541     *
4542     * @param message used as message if SecurityException is thrown
4543     * @throws SecurityException if the caller is not system or root
4544     */
4545    private static final void enforceSystemOrRoot(String message) {
4546        final int uid = Binder.getCallingUid();
4547        if (uid != Process.SYSTEM_UID && uid != 0) {
4548            throw new SecurityException(message);
4549        }
4550    }
4551
4552    @Override
4553    public void performBootDexOpt() {
4554        enforceSystemOrRoot("Only the system can request dexopt be performed");
4555
4556        // Before everything else, see whether we need to fstrim.
4557        try {
4558            IMountService ms = PackageHelper.getMountService();
4559            if (ms != null) {
4560                final boolean isUpgrade = isUpgrade();
4561                boolean doTrim = isUpgrade;
4562                if (doTrim) {
4563                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
4564                } else {
4565                    final long interval = android.provider.Settings.Global.getLong(
4566                            mContext.getContentResolver(),
4567                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
4568                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
4569                    if (interval > 0) {
4570                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
4571                        if (timeSinceLast > interval) {
4572                            doTrim = true;
4573                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
4574                                    + "; running immediately");
4575                        }
4576                    }
4577                }
4578                if (doTrim) {
4579                    if (!isFirstBoot()) {
4580                        try {
4581                            ActivityManagerNative.getDefault().showBootMessage(
4582                                    mContext.getResources().getString(
4583                                            R.string.android_upgrading_fstrim), true);
4584                        } catch (RemoteException e) {
4585                        }
4586                    }
4587                    ms.runMaintenance();
4588                }
4589            } else {
4590                Slog.e(TAG, "Mount service unavailable!");
4591            }
4592        } catch (RemoteException e) {
4593            // Can't happen; MountService is local
4594        }
4595
4596        final ArraySet<PackageParser.Package> pkgs;
4597        synchronized (mPackages) {
4598            pkgs = mDeferredDexOpt;
4599            mDeferredDexOpt = null;
4600        }
4601
4602        if (pkgs != null) {
4603            // Sort apps by importance for dexopt ordering. Important apps are given more priority
4604            // in case the device runs out of space.
4605            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
4606            // Give priority to core apps.
4607            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4608                PackageParser.Package pkg = it.next();
4609                if (pkg.coreApp) {
4610                    if (DEBUG_DEXOPT) {
4611                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
4612                    }
4613                    sortedPkgs.add(pkg);
4614                    it.remove();
4615                }
4616            }
4617            // Give priority to system apps that listen for pre boot complete.
4618            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
4619            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
4620            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4621                PackageParser.Package pkg = it.next();
4622                if (pkgNames.contains(pkg.packageName)) {
4623                    if (DEBUG_DEXOPT) {
4624                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
4625                    }
4626                    sortedPkgs.add(pkg);
4627                    it.remove();
4628                }
4629            }
4630            // Give priority to system apps.
4631            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4632                PackageParser.Package pkg = it.next();
4633                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4634                    if (DEBUG_DEXOPT) {
4635                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
4636                    }
4637                    sortedPkgs.add(pkg);
4638                    it.remove();
4639                }
4640            }
4641            // Give priority to updated system apps.
4642            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4643                PackageParser.Package pkg = it.next();
4644                if (isUpdatedSystemApp(pkg)) {
4645                    if (DEBUG_DEXOPT) {
4646                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
4647                    }
4648                    sortedPkgs.add(pkg);
4649                    it.remove();
4650                }
4651            }
4652            // Give priority to apps that listen for boot complete.
4653            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
4654            pkgNames = getPackageNamesForIntent(intent);
4655            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4656                PackageParser.Package pkg = it.next();
4657                if (pkgNames.contains(pkg.packageName)) {
4658                    if (DEBUG_DEXOPT) {
4659                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
4660                    }
4661                    sortedPkgs.add(pkg);
4662                    it.remove();
4663                }
4664            }
4665            // Filter out packages that aren't recently used.
4666            filterRecentlyUsedApps(pkgs);
4667            // Add all remaining apps.
4668            for (PackageParser.Package pkg : pkgs) {
4669                if (DEBUG_DEXOPT) {
4670                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
4671                }
4672                sortedPkgs.add(pkg);
4673            }
4674
4675            // If we want to be lazy, filter everything that wasn't recently used.
4676            if (mLazyDexOpt) {
4677                filterRecentlyUsedApps(sortedPkgs);
4678            }
4679
4680            int i = 0;
4681            int total = sortedPkgs.size();
4682            File dataDir = Environment.getDataDirectory();
4683            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
4684            if (lowThreshold == 0) {
4685                throw new IllegalStateException("Invalid low memory threshold");
4686            }
4687            for (PackageParser.Package pkg : sortedPkgs) {
4688                long usableSpace = dataDir.getUsableSpace();
4689                if (usableSpace < lowThreshold) {
4690                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
4691                    break;
4692                }
4693                performBootDexOpt(pkg, ++i, total);
4694            }
4695        }
4696    }
4697
4698    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
4699        // Filter out packages that aren't recently used.
4700        //
4701        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4702        // should do a full dexopt.
4703        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4704            int total = pkgs.size();
4705            int skipped = 0;
4706            long now = System.currentTimeMillis();
4707            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4708                PackageParser.Package pkg = i.next();
4709                long then = pkg.mLastPackageUsageTimeInMills;
4710                if (then + mDexOptLRUThresholdInMills < now) {
4711                    if (DEBUG_DEXOPT) {
4712                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4713                              ((then == 0) ? "never" : new Date(then)));
4714                    }
4715                    i.remove();
4716                    skipped++;
4717                }
4718            }
4719            if (DEBUG_DEXOPT) {
4720                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4721            }
4722        }
4723    }
4724
4725    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
4726        List<ResolveInfo> ris = null;
4727        try {
4728            ris = AppGlobals.getPackageManager().queryIntentReceivers(
4729                    intent, null, 0, UserHandle.USER_OWNER);
4730        } catch (RemoteException e) {
4731        }
4732        ArraySet<String> pkgNames = new ArraySet<String>();
4733        if (ris != null) {
4734            for (ResolveInfo ri : ris) {
4735                pkgNames.add(ri.activityInfo.packageName);
4736            }
4737        }
4738        return pkgNames;
4739    }
4740
4741    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
4742        if (DEBUG_DEXOPT) {
4743            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
4744        }
4745        if (!isFirstBoot()) {
4746            try {
4747                ActivityManagerNative.getDefault().showBootMessage(
4748                        mContext.getResources().getString(R.string.android_upgrading_apk,
4749                                curr, total), true);
4750            } catch (RemoteException e) {
4751            }
4752        }
4753        PackageParser.Package p = pkg;
4754        synchronized (mInstallLock) {
4755            performDexOptLI(p, null /* instruction sets */, false /* force dex */,
4756                            false /* defer */, true /* include dependencies */);
4757        }
4758    }
4759
4760    @Override
4761    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4762        return performDexOpt(packageName, instructionSet, false);
4763    }
4764
4765    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4766        if (info.primaryCpuAbi == null) {
4767            return getPreferredInstructionSet();
4768        }
4769
4770        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4771    }
4772
4773    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4774        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4775        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4776        if (!dexopt && !updateUsage) {
4777            // We aren't going to dexopt or update usage, so bail early.
4778            return false;
4779        }
4780        PackageParser.Package p;
4781        final String targetInstructionSet;
4782        synchronized (mPackages) {
4783            p = mPackages.get(packageName);
4784            if (p == null) {
4785                return false;
4786            }
4787            if (updateUsage) {
4788                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4789            }
4790            mPackageUsage.write(false);
4791            if (!dexopt) {
4792                // We aren't going to dexopt, so bail early.
4793                return false;
4794            }
4795
4796            targetInstructionSet = instructionSet != null ? instructionSet :
4797                    getPrimaryInstructionSet(p.applicationInfo);
4798            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4799                return false;
4800            }
4801        }
4802
4803        synchronized (mInstallLock) {
4804            final String[] instructionSets = new String[] { targetInstructionSet };
4805            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4806                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4807        }
4808    }
4809
4810    public ArraySet<String> getPackagesThatNeedDexOpt() {
4811        ArraySet<String> pkgs = null;
4812        synchronized (mPackages) {
4813            for (PackageParser.Package p : mPackages.values()) {
4814                if (DEBUG_DEXOPT) {
4815                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4816                }
4817                if (!p.mDexOptPerformed.isEmpty()) {
4818                    continue;
4819                }
4820                if (pkgs == null) {
4821                    pkgs = new ArraySet<String>();
4822                }
4823                pkgs.add(p.packageName);
4824            }
4825        }
4826        return pkgs;
4827    }
4828
4829    public void shutdown() {
4830        mPackageUsage.write(true);
4831    }
4832
4833    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4834             boolean forceDex, boolean defer, ArraySet<String> done) {
4835        for (int i=0; i<libs.size(); i++) {
4836            PackageParser.Package libPkg;
4837            String libName;
4838            synchronized (mPackages) {
4839                libName = libs.get(i);
4840                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4841                if (lib != null && lib.apk != null) {
4842                    libPkg = mPackages.get(lib.apk);
4843                } else {
4844                    libPkg = null;
4845                }
4846            }
4847            if (libPkg != null && !done.contains(libName)) {
4848                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4849            }
4850        }
4851    }
4852
4853    static final int DEX_OPT_SKIPPED = 0;
4854    static final int DEX_OPT_PERFORMED = 1;
4855    static final int DEX_OPT_DEFERRED = 2;
4856    static final int DEX_OPT_FAILED = -1;
4857
4858    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4859            boolean forceDex, boolean defer, ArraySet<String> done) {
4860        final String[] instructionSets = targetInstructionSets != null ?
4861                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4862
4863        if (done != null) {
4864            done.add(pkg.packageName);
4865            if (pkg.usesLibraries != null) {
4866                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4867            }
4868            if (pkg.usesOptionalLibraries != null) {
4869                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4870            }
4871        }
4872
4873        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4874            return DEX_OPT_SKIPPED;
4875        }
4876
4877        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4878        final boolean debuggable = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
4879
4880        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4881        boolean performedDexOpt = false;
4882        // There are three basic cases here:
4883        // 1.) we need to dexopt, either because we are forced or it is needed
4884        // 2.) we are defering a needed dexopt
4885        // 3.) we are skipping an unneeded dexopt
4886        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4887        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4888            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4889                continue;
4890            }
4891
4892            for (String path : paths) {
4893                try {
4894                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4895                    // patckage or the one we find does not match the image checksum (i.e. it was
4896                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4897                    // odex file and it matches the checksum of the image but not its base address,
4898                    // meaning we need to move it.
4899                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4900                            pkg.packageName, dexCodeInstructionSet, defer);
4901                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4902                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4903                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4904                                + " vmSafeMode=" + vmSafeMode + " debuggable=" + debuggable);
4905                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4906                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4907                                pkg.packageName, dexCodeInstructionSet, vmSafeMode, debuggable);
4908
4909                        if (ret < 0) {
4910                            // Don't bother running dexopt again if we failed, it will probably
4911                            // just result in an error again. Also, don't bother dexopting for other
4912                            // paths & ISAs.
4913                            return DEX_OPT_FAILED;
4914                        }
4915
4916                        performedDexOpt = true;
4917                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4918                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4919                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4920                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4921                                pkg.packageName, dexCodeInstructionSet);
4922
4923                        if (ret < 0) {
4924                            // Don't bother running patchoat again if we failed, it will probably
4925                            // just result in an error again. Also, don't bother dexopting for other
4926                            // paths & ISAs.
4927                            return DEX_OPT_FAILED;
4928                        }
4929
4930                        performedDexOpt = true;
4931                    }
4932
4933                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4934                    // paths and instruction sets. We'll deal with them all together when we process
4935                    // our list of deferred dexopts.
4936                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4937                        if (mDeferredDexOpt == null) {
4938                            mDeferredDexOpt = new ArraySet<PackageParser.Package>();
4939                        }
4940                        mDeferredDexOpt.add(pkg);
4941                        return DEX_OPT_DEFERRED;
4942                    }
4943                } catch (FileNotFoundException e) {
4944                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4945                    return DEX_OPT_FAILED;
4946                } catch (IOException e) {
4947                    Slog.w(TAG, "IOException reading apk: " + path, e);
4948                    return DEX_OPT_FAILED;
4949                } catch (StaleDexCacheError e) {
4950                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4951                    return DEX_OPT_FAILED;
4952                } catch (Exception e) {
4953                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4954                    return DEX_OPT_FAILED;
4955                }
4956            }
4957
4958            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4959            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4960            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4961            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4962            // it.
4963            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4964        }
4965
4966        // If we've gotten here, we're sure that no error occurred and that we haven't
4967        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4968        // we've skipped all of them because they are up to date. In both cases this
4969        // package doesn't need dexopt any longer.
4970        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4971    }
4972
4973    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4974        if (info.primaryCpuAbi != null) {
4975            if (info.secondaryCpuAbi != null) {
4976                return new String[] {
4977                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4978                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4979            } else {
4980                return new String[] {
4981                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4982            }
4983        }
4984
4985        return new String[] { getPreferredInstructionSet() };
4986    }
4987
4988    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4989        if (ps.primaryCpuAbiString != null) {
4990            if (ps.secondaryCpuAbiString != null) {
4991                return new String[] {
4992                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4993                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4994            } else {
4995                return new String[] {
4996                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4997            }
4998        }
4999
5000        return new String[] { getPreferredInstructionSet() };
5001    }
5002
5003    private static String getPreferredInstructionSet() {
5004        if (sPreferredInstructionSet == null) {
5005            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
5006        }
5007
5008        return sPreferredInstructionSet;
5009    }
5010
5011    private static List<String> getAllInstructionSets() {
5012        final String[] allAbis = Build.SUPPORTED_ABIS;
5013        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
5014
5015        for (String abi : allAbis) {
5016            final String instructionSet = VMRuntime.getInstructionSet(abi);
5017            if (!allInstructionSets.contains(instructionSet)) {
5018                allInstructionSets.add(instructionSet);
5019            }
5020        }
5021
5022        return allInstructionSets;
5023    }
5024
5025    /**
5026     * Returns the instruction set that should be used to compile dex code. In the presence of
5027     * a native bridge this might be different than the one shared libraries use.
5028     */
5029    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
5030        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
5031        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
5032    }
5033
5034    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
5035        ArraySet<String> dexCodeInstructionSets = new ArraySet<String>(instructionSets.length);
5036        for (String instructionSet : instructionSets) {
5037            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
5038        }
5039        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
5040    }
5041
5042    /**
5043     * Returns deduplicated list of supported instructions for dex code.
5044     */
5045    public static String[] getAllDexCodeInstructionSets() {
5046        String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length];
5047        for (int i = 0; i < supportedInstructionSets.length; i++) {
5048            String abi = Build.SUPPORTED_ABIS[i];
5049            supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi);
5050        }
5051        return getDexCodeInstructionSets(supportedInstructionSets);
5052    }
5053
5054    @Override
5055    public void forceDexOpt(String packageName) {
5056        enforceSystemOrRoot("forceDexOpt");
5057
5058        PackageParser.Package pkg;
5059        synchronized (mPackages) {
5060            pkg = mPackages.get(packageName);
5061            if (pkg == null) {
5062                throw new IllegalArgumentException("Missing package: " + packageName);
5063            }
5064        }
5065
5066        synchronized (mInstallLock) {
5067            final String[] instructionSets = new String[] {
5068                    getPrimaryInstructionSet(pkg.applicationInfo) };
5069            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
5070            if (res != DEX_OPT_PERFORMED) {
5071                throw new IllegalStateException("Failed to dexopt: " + res);
5072            }
5073        }
5074    }
5075
5076    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
5077                                boolean forceDex, boolean defer, boolean inclDependencies) {
5078        ArraySet<String> done;
5079        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
5080            done = new ArraySet<String>();
5081            done.add(pkg.packageName);
5082        } else {
5083            done = null;
5084        }
5085        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
5086    }
5087
5088    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5089        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5090            Slog.w(TAG, "Unable to update from " + oldPkg.name
5091                    + " to " + newPkg.packageName
5092                    + ": old package not in system partition");
5093            return false;
5094        } else if (mPackages.get(oldPkg.name) != null) {
5095            Slog.w(TAG, "Unable to update from " + oldPkg.name
5096                    + " to " + newPkg.packageName
5097                    + ": old package still exists");
5098            return false;
5099        }
5100        return true;
5101    }
5102
5103    File getDataPathForUser(int userId) {
5104        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
5105    }
5106
5107    private File getDataPathForPackage(String packageName, int userId) {
5108        /*
5109         * Until we fully support multiple users, return the directory we
5110         * previously would have. The PackageManagerTests will need to be
5111         * revised when this is changed back..
5112         */
5113        if (userId == 0) {
5114            return new File(mAppDataDir, packageName);
5115        } else {
5116            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
5117                + File.separator + packageName);
5118        }
5119    }
5120
5121    private int createDataDirsLI(String packageName, int uid, String seinfo) {
5122        int[] users = sUserManager.getUserIds();
5123        int res = mInstaller.install(packageName, uid, uid, seinfo);
5124        if (res < 0) {
5125            return res;
5126        }
5127        for (int user : users) {
5128            if (user != 0) {
5129                res = mInstaller.createUserData(packageName,
5130                        UserHandle.getUid(user, uid), user, seinfo);
5131                if (res < 0) {
5132                    return res;
5133                }
5134            }
5135        }
5136        return res;
5137    }
5138
5139    private int removeDataDirsLI(String packageName) {
5140        int[] users = sUserManager.getUserIds();
5141        int res = 0;
5142        for (int user : users) {
5143            int resInner = mInstaller.remove(packageName, user);
5144            if (resInner < 0) {
5145                res = resInner;
5146            }
5147        }
5148
5149        return res;
5150    }
5151
5152    private int deleteCodeCacheDirsLI(String packageName) {
5153        int[] users = sUserManager.getUserIds();
5154        int res = 0;
5155        for (int user : users) {
5156            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
5157            if (resInner < 0) {
5158                res = resInner;
5159            }
5160        }
5161        return res;
5162    }
5163
5164    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5165            PackageParser.Package changingLib) {
5166        if (file.path != null) {
5167            usesLibraryFiles.add(file.path);
5168            return;
5169        }
5170        PackageParser.Package p = mPackages.get(file.apk);
5171        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5172            // If we are doing this while in the middle of updating a library apk,
5173            // then we need to make sure to use that new apk for determining the
5174            // dependencies here.  (We haven't yet finished committing the new apk
5175            // to the package manager state.)
5176            if (p == null || p.packageName.equals(changingLib.packageName)) {
5177                p = changingLib;
5178            }
5179        }
5180        if (p != null) {
5181            usesLibraryFiles.addAll(p.getAllCodePaths());
5182        }
5183    }
5184
5185    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5186            PackageParser.Package changingLib) throws PackageManagerException {
5187        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5188            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5189            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5190            for (int i=0; i<N; i++) {
5191                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5192                if (file == null) {
5193                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5194                            "Package " + pkg.packageName + " requires unavailable shared library "
5195                            + pkg.usesLibraries.get(i) + "; failing!");
5196                }
5197                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5198            }
5199            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5200            for (int i=0; i<N; i++) {
5201                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5202                if (file == null) {
5203                    Slog.w(TAG, "Package " + pkg.packageName
5204                            + " desires unavailable shared library "
5205                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5206                } else {
5207                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5208                }
5209            }
5210            N = usesLibraryFiles.size();
5211            if (N > 0) {
5212                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5213            } else {
5214                pkg.usesLibraryFiles = null;
5215            }
5216        }
5217    }
5218
5219    private static boolean hasString(List<String> list, List<String> which) {
5220        if (list == null) {
5221            return false;
5222        }
5223        for (int i=list.size()-1; i>=0; i--) {
5224            for (int j=which.size()-1; j>=0; j--) {
5225                if (which.get(j).equals(list.get(i))) {
5226                    return true;
5227                }
5228            }
5229        }
5230        return false;
5231    }
5232
5233    private void updateAllSharedLibrariesLPw() {
5234        for (PackageParser.Package pkg : mPackages.values()) {
5235            try {
5236                updateSharedLibrariesLPw(pkg, null);
5237            } catch (PackageManagerException e) {
5238                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5239            }
5240        }
5241    }
5242
5243    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5244            PackageParser.Package changingPkg) {
5245        ArrayList<PackageParser.Package> res = null;
5246        for (PackageParser.Package pkg : mPackages.values()) {
5247            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5248                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5249                if (res == null) {
5250                    res = new ArrayList<PackageParser.Package>();
5251                }
5252                res.add(pkg);
5253                try {
5254                    updateSharedLibrariesLPw(pkg, changingPkg);
5255                } catch (PackageManagerException e) {
5256                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5257                }
5258            }
5259        }
5260        return res;
5261    }
5262
5263    /**
5264     * Derive the value of the {@code cpuAbiOverride} based on the provided
5265     * value and an optional stored value from the package settings.
5266     */
5267    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5268        String cpuAbiOverride = null;
5269
5270        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5271            cpuAbiOverride = null;
5272        } else if (abiOverride != null) {
5273            cpuAbiOverride = abiOverride;
5274        } else if (settings != null) {
5275            cpuAbiOverride = settings.cpuAbiOverrideString;
5276        }
5277
5278        return cpuAbiOverride;
5279    }
5280
5281    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5282            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5283        boolean success = false;
5284        try {
5285            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5286                    currentTime, user);
5287            success = true;
5288            return res;
5289        } finally {
5290            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5291                removeDataDirsLI(pkg.packageName);
5292            }
5293        }
5294    }
5295
5296    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5297            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5298        final File scanFile = new File(pkg.codePath);
5299        if (pkg.applicationInfo.getCodePath() == null ||
5300                pkg.applicationInfo.getResourcePath() == null) {
5301            // Bail out. The resource and code paths haven't been set.
5302            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5303                    "Code and resource paths haven't been set correctly");
5304        }
5305
5306        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5307            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5308        } else {
5309            // Only allow system apps to be flagged as core apps.
5310            pkg.coreApp = false;
5311        }
5312
5313        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5314            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5315        }
5316
5317        if (mCustomResolverComponentName != null &&
5318                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5319            setUpCustomResolverActivity(pkg);
5320        }
5321
5322        if (pkg.packageName.equals("android")) {
5323            synchronized (mPackages) {
5324                if (mAndroidApplication != null) {
5325                    Slog.w(TAG, "*************************************************");
5326                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5327                    Slog.w(TAG, " file=" + scanFile);
5328                    Slog.w(TAG, "*************************************************");
5329                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5330                            "Core android package being redefined.  Skipping.");
5331                }
5332
5333                // Set up information for our fall-back user intent resolution activity.
5334                mPlatformPackage = pkg;
5335                pkg.mVersionCode = mSdkVersion;
5336                mAndroidApplication = pkg.applicationInfo;
5337
5338                if (!mResolverReplaced) {
5339                    mResolveActivity.applicationInfo = mAndroidApplication;
5340                    mResolveActivity.name = ResolverActivity.class.getName();
5341                    mResolveActivity.packageName = mAndroidApplication.packageName;
5342                    mResolveActivity.processName = "system:ui";
5343                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5344                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5345                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5346                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5347                    mResolveActivity.exported = true;
5348                    mResolveActivity.enabled = true;
5349                    mResolveInfo.activityInfo = mResolveActivity;
5350                    mResolveInfo.priority = 0;
5351                    mResolveInfo.preferredOrder = 0;
5352                    mResolveInfo.match = 0;
5353                    mResolveComponentName = new ComponentName(
5354                            mAndroidApplication.packageName, mResolveActivity.name);
5355                }
5356            }
5357        }
5358
5359        if (DEBUG_PACKAGE_SCANNING) {
5360            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5361                Log.d(TAG, "Scanning package " + pkg.packageName);
5362        }
5363
5364        if (mPackages.containsKey(pkg.packageName)
5365                || mSharedLibraries.containsKey(pkg.packageName)) {
5366            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5367                    "Application package " + pkg.packageName
5368                    + " already installed.  Skipping duplicate.");
5369        }
5370
5371        // Initialize package source and resource directories
5372        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5373        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5374
5375        SharedUserSetting suid = null;
5376        PackageSetting pkgSetting = null;
5377
5378        if (!isSystemApp(pkg)) {
5379            // Only system apps can use these features.
5380            pkg.mOriginalPackages = null;
5381            pkg.mRealPackage = null;
5382            pkg.mAdoptPermissions = null;
5383        }
5384
5385        // writer
5386        synchronized (mPackages) {
5387            if (pkg.mSharedUserId != null) {
5388                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5389                if (suid == null) {
5390                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5391                            "Creating application package " + pkg.packageName
5392                            + " for shared user failed");
5393                }
5394                if (DEBUG_PACKAGE_SCANNING) {
5395                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5396                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5397                                + "): packages=" + suid.packages);
5398                }
5399            }
5400
5401            // Check if we are renaming from an original package name.
5402            PackageSetting origPackage = null;
5403            String realName = null;
5404            if (pkg.mOriginalPackages != null) {
5405                // This package may need to be renamed to a previously
5406                // installed name.  Let's check on that...
5407                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5408                if (pkg.mOriginalPackages.contains(renamed)) {
5409                    // This package had originally been installed as the
5410                    // original name, and we have already taken care of
5411                    // transitioning to the new one.  Just update the new
5412                    // one to continue using the old name.
5413                    realName = pkg.mRealPackage;
5414                    if (!pkg.packageName.equals(renamed)) {
5415                        // Callers into this function may have already taken
5416                        // care of renaming the package; only do it here if
5417                        // it is not already done.
5418                        pkg.setPackageName(renamed);
5419                    }
5420
5421                } else {
5422                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5423                        if ((origPackage = mSettings.peekPackageLPr(
5424                                pkg.mOriginalPackages.get(i))) != null) {
5425                            // We do have the package already installed under its
5426                            // original name...  should we use it?
5427                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5428                                // New package is not compatible with original.
5429                                origPackage = null;
5430                                continue;
5431                            } else if (origPackage.sharedUser != null) {
5432                                // Make sure uid is compatible between packages.
5433                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5434                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5435                                            + " to " + pkg.packageName + ": old uid "
5436                                            + origPackage.sharedUser.name
5437                                            + " differs from " + pkg.mSharedUserId);
5438                                    origPackage = null;
5439                                    continue;
5440                                }
5441                            } else {
5442                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5443                                        + pkg.packageName + " to old name " + origPackage.name);
5444                            }
5445                            break;
5446                        }
5447                    }
5448                }
5449            }
5450
5451            if (mTransferedPackages.contains(pkg.packageName)) {
5452                Slog.w(TAG, "Package " + pkg.packageName
5453                        + " was transferred to another, but its .apk remains");
5454            }
5455
5456            // Just create the setting, don't add it yet. For already existing packages
5457            // the PkgSetting exists already and doesn't have to be created.
5458            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5459                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5460                    pkg.applicationInfo.primaryCpuAbi,
5461                    pkg.applicationInfo.secondaryCpuAbi,
5462                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
5463                    user, false);
5464            if (pkgSetting == null) {
5465                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5466                        "Creating application package " + pkg.packageName + " failed");
5467            }
5468
5469            if (pkgSetting.origPackage != null) {
5470                // If we are first transitioning from an original package,
5471                // fix up the new package's name now.  We need to do this after
5472                // looking up the package under its new name, so getPackageLP
5473                // can take care of fiddling things correctly.
5474                pkg.setPackageName(origPackage.name);
5475
5476                // File a report about this.
5477                String msg = "New package " + pkgSetting.realName
5478                        + " renamed to replace old package " + pkgSetting.name;
5479                reportSettingsProblem(Log.WARN, msg);
5480
5481                // Make a note of it.
5482                mTransferedPackages.add(origPackage.name);
5483
5484                // No longer need to retain this.
5485                pkgSetting.origPackage = null;
5486            }
5487
5488            if (realName != null) {
5489                // Make a note of it.
5490                mTransferedPackages.add(pkg.packageName);
5491            }
5492
5493            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5494                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5495            }
5496
5497            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5498                // Check all shared libraries and map to their actual file path.
5499                // We only do this here for apps not on a system dir, because those
5500                // are the only ones that can fail an install due to this.  We
5501                // will take care of the system apps by updating all of their
5502                // library paths after the scan is done.
5503                updateSharedLibrariesLPw(pkg, null);
5504            }
5505
5506            if (mFoundPolicyFile) {
5507                SELinuxMMAC.assignSeinfoValue(pkg);
5508            }
5509
5510            pkg.applicationInfo.uid = pkgSetting.appId;
5511            pkg.mExtras = pkgSetting;
5512            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5513                try {
5514                    verifySignaturesLP(pkgSetting, pkg);
5515                    // We just determined the app is signed correctly, so bring
5516                    // over the latest parsed certs.
5517                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5518                } catch (PackageManagerException e) {
5519                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5520                        throw e;
5521                    }
5522                    // The signature has changed, but this package is in the system
5523                    // image...  let's recover!
5524                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5525                    // However...  if this package is part of a shared user, but it
5526                    // doesn't match the signature of the shared user, let's fail.
5527                    // What this means is that you can't change the signatures
5528                    // associated with an overall shared user, which doesn't seem all
5529                    // that unreasonable.
5530                    if (pkgSetting.sharedUser != null) {
5531                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5532                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5533                            throw new PackageManagerException(
5534                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5535                                            "Signature mismatch for shared user : "
5536                                            + pkgSetting.sharedUser);
5537                        }
5538                    }
5539                    // File a report about this.
5540                    String msg = "System package " + pkg.packageName
5541                        + " signature changed; retaining data.";
5542                    reportSettingsProblem(Log.WARN, msg);
5543                }
5544            } else {
5545                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5546                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5547                            + pkg.packageName + " upgrade keys do not match the "
5548                            + "previously installed version");
5549                } else {
5550                    // We just determined the app is signed correctly, so bring
5551                    // over the latest parsed certs.
5552                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5553                }
5554            }
5555            // Verify that this new package doesn't have any content providers
5556            // that conflict with existing packages.  Only do this if the
5557            // package isn't already installed, since we don't want to break
5558            // things that are installed.
5559            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5560                final int N = pkg.providers.size();
5561                int i;
5562                for (i=0; i<N; i++) {
5563                    PackageParser.Provider p = pkg.providers.get(i);
5564                    if (p.info.authority != null) {
5565                        String names[] = p.info.authority.split(";");
5566                        for (int j = 0; j < names.length; j++) {
5567                            if (mProvidersByAuthority.containsKey(names[j])) {
5568                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5569                                final String otherPackageName =
5570                                        ((other != null && other.getComponentName() != null) ?
5571                                                other.getComponentName().getPackageName() : "?");
5572                                throw new PackageManagerException(
5573                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5574                                                "Can't install because provider name " + names[j]
5575                                                + " (in package " + pkg.applicationInfo.packageName
5576                                                + ") is already used by " + otherPackageName);
5577                            }
5578                        }
5579                    }
5580                }
5581            }
5582
5583            if (pkg.mAdoptPermissions != null) {
5584                // This package wants to adopt ownership of permissions from
5585                // another package.
5586                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5587                    final String origName = pkg.mAdoptPermissions.get(i);
5588                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5589                    if (orig != null) {
5590                        if (verifyPackageUpdateLPr(orig, pkg)) {
5591                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5592                                    + pkg.packageName);
5593                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5594                        }
5595                    }
5596                }
5597            }
5598        }
5599
5600        final String pkgName = pkg.packageName;
5601
5602        final long scanFileTime = scanFile.lastModified();
5603        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5604        pkg.applicationInfo.processName = fixProcessName(
5605                pkg.applicationInfo.packageName,
5606                pkg.applicationInfo.processName,
5607                pkg.applicationInfo.uid);
5608
5609        File dataPath;
5610        if (mPlatformPackage == pkg) {
5611            // The system package is special.
5612            dataPath = new File(Environment.getDataDirectory(), "system");
5613
5614            pkg.applicationInfo.dataDir = dataPath.getPath();
5615
5616        } else {
5617            // This is a normal package, need to make its data directory.
5618            dataPath = getDataPathForPackage(pkg.packageName, 0);
5619
5620            boolean uidError = false;
5621            if (dataPath.exists()) {
5622                int currentUid = 0;
5623                try {
5624                    StructStat stat = Os.stat(dataPath.getPath());
5625                    currentUid = stat.st_uid;
5626                } catch (ErrnoException e) {
5627                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5628                }
5629
5630                // If we have mismatched owners for the data path, we have a problem.
5631                if (currentUid != pkg.applicationInfo.uid) {
5632                    boolean recovered = false;
5633                    if (currentUid == 0) {
5634                        // The directory somehow became owned by root.  Wow.
5635                        // This is probably because the system was stopped while
5636                        // installd was in the middle of messing with its libs
5637                        // directory.  Ask installd to fix that.
5638                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5639                                pkg.applicationInfo.uid);
5640                        if (ret >= 0) {
5641                            recovered = true;
5642                            String msg = "Package " + pkg.packageName
5643                                    + " unexpectedly changed to uid 0; recovered to " +
5644                                    + pkg.applicationInfo.uid;
5645                            reportSettingsProblem(Log.WARN, msg);
5646                        }
5647                    }
5648                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5649                            || (scanFlags&SCAN_BOOTING) != 0)) {
5650                        // If this is a system app, we can at least delete its
5651                        // current data so the application will still work.
5652                        int ret = removeDataDirsLI(pkgName);
5653                        if (ret >= 0) {
5654                            // TODO: Kill the processes first
5655                            // Old data gone!
5656                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5657                                    ? "System package " : "Third party package ";
5658                            String msg = prefix + pkg.packageName
5659                                    + " has changed from uid: "
5660                                    + currentUid + " to "
5661                                    + pkg.applicationInfo.uid + "; old data erased";
5662                            reportSettingsProblem(Log.WARN, msg);
5663                            recovered = true;
5664
5665                            // And now re-install the app.
5666                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5667                                                   pkg.applicationInfo.seinfo);
5668                            if (ret == -1) {
5669                                // Ack should not happen!
5670                                msg = prefix + pkg.packageName
5671                                        + " could not have data directory re-created after delete.";
5672                                reportSettingsProblem(Log.WARN, msg);
5673                                throw new PackageManagerException(
5674                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5675                            }
5676                        }
5677                        if (!recovered) {
5678                            mHasSystemUidErrors = true;
5679                        }
5680                    } else if (!recovered) {
5681                        // If we allow this install to proceed, we will be broken.
5682                        // Abort, abort!
5683                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5684                                "scanPackageLI");
5685                    }
5686                    if (!recovered) {
5687                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5688                            + pkg.applicationInfo.uid + "/fs_"
5689                            + currentUid;
5690                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5691                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5692                        String msg = "Package " + pkg.packageName
5693                                + " has mismatched uid: "
5694                                + currentUid + " on disk, "
5695                                + pkg.applicationInfo.uid + " in settings";
5696                        // writer
5697                        synchronized (mPackages) {
5698                            mSettings.mReadMessages.append(msg);
5699                            mSettings.mReadMessages.append('\n');
5700                            uidError = true;
5701                            if (!pkgSetting.uidError) {
5702                                reportSettingsProblem(Log.ERROR, msg);
5703                            }
5704                        }
5705                    }
5706                }
5707                pkg.applicationInfo.dataDir = dataPath.getPath();
5708                if (mShouldRestoreconData) {
5709                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5710                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5711                                pkg.applicationInfo.uid);
5712                }
5713            } else {
5714                if (DEBUG_PACKAGE_SCANNING) {
5715                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5716                        Log.v(TAG, "Want this data dir: " + dataPath);
5717                }
5718                //invoke installer to do the actual installation
5719                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5720                                           pkg.applicationInfo.seinfo);
5721                if (ret < 0) {
5722                    // Error from installer
5723                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5724                            "Unable to create data dirs [errorCode=" + ret + "]");
5725                }
5726
5727                if (dataPath.exists()) {
5728                    pkg.applicationInfo.dataDir = dataPath.getPath();
5729                } else {
5730                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5731                    pkg.applicationInfo.dataDir = null;
5732                }
5733            }
5734
5735            pkgSetting.uidError = uidError;
5736        }
5737
5738        final String path = scanFile.getPath();
5739        final String codePath = pkg.applicationInfo.getCodePath();
5740        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5741        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5742            setBundledAppAbisAndRoots(pkg, pkgSetting);
5743
5744            // If we haven't found any native libraries for the app, check if it has
5745            // renderscript code. We'll need to force the app to 32 bit if it has
5746            // renderscript bitcode.
5747            if (pkg.applicationInfo.primaryCpuAbi == null
5748                    && pkg.applicationInfo.secondaryCpuAbi == null
5749                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5750                NativeLibraryHelper.Handle handle = null;
5751                try {
5752                    handle = NativeLibraryHelper.Handle.create(scanFile);
5753                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5754                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5755                    }
5756                } catch (IOException ioe) {
5757                    Slog.w(TAG, "Error scanning system app : " + ioe);
5758                } finally {
5759                    IoUtils.closeQuietly(handle);
5760                }
5761            }
5762
5763            setNativeLibraryPaths(pkg);
5764        } else {
5765            // TODO: We can probably be smarter about this stuff. For installed apps,
5766            // we can calculate this information at install time once and for all. For
5767            // system apps, we can probably assume that this information doesn't change
5768            // after the first boot scan. As things stand, we do lots of unnecessary work.
5769
5770            // Give ourselves some initial paths; we'll come back for another
5771            // pass once we've determined ABI below.
5772            setNativeLibraryPaths(pkg);
5773
5774            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5775            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5776            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5777
5778            NativeLibraryHelper.Handle handle = null;
5779            try {
5780                handle = NativeLibraryHelper.Handle.create(scanFile);
5781                // TODO(multiArch): This can be null for apps that didn't go through the
5782                // usual installation process. We can calculate it again, like we
5783                // do during install time.
5784                //
5785                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5786                // unnecessary.
5787                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5788
5789                // Null out the abis so that they can be recalculated.
5790                pkg.applicationInfo.primaryCpuAbi = null;
5791                pkg.applicationInfo.secondaryCpuAbi = null;
5792                if (isMultiArch(pkg.applicationInfo)) {
5793                    // Warn if we've set an abiOverride for multi-lib packages..
5794                    // By definition, we need to copy both 32 and 64 bit libraries for
5795                    // such packages.
5796                    if (pkg.cpuAbiOverride != null
5797                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5798                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5799                    }
5800
5801                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5802                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5803                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5804                        if (isAsec) {
5805                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5806                        } else {
5807                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5808                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5809                                    useIsaSpecificSubdirs);
5810                        }
5811                    }
5812
5813                    maybeThrowExceptionForMultiArchCopy(
5814                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5815
5816                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5817                        if (isAsec) {
5818                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5819                        } else {
5820                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5821                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5822                                    useIsaSpecificSubdirs);
5823                        }
5824                    }
5825
5826                    maybeThrowExceptionForMultiArchCopy(
5827                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5828
5829                    if (abi64 >= 0) {
5830                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5831                    }
5832
5833                    if (abi32 >= 0) {
5834                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5835                        if (abi64 >= 0) {
5836                            pkg.applicationInfo.secondaryCpuAbi = abi;
5837                        } else {
5838                            pkg.applicationInfo.primaryCpuAbi = abi;
5839                        }
5840                    }
5841                } else {
5842                    String[] abiList = (cpuAbiOverride != null) ?
5843                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5844
5845                    // Enable gross and lame hacks for apps that are built with old
5846                    // SDK tools. We must scan their APKs for renderscript bitcode and
5847                    // not launch them if it's present. Don't bother checking on devices
5848                    // that don't have 64 bit support.
5849                    boolean needsRenderScriptOverride = false;
5850                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5851                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5852                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5853                        needsRenderScriptOverride = true;
5854                    }
5855
5856                    final int copyRet;
5857                    if (isAsec) {
5858                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5859                    } else {
5860                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5861                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5862                    }
5863
5864                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5865                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5866                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5867                    }
5868
5869                    if (copyRet >= 0) {
5870                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5871                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5872                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5873                    } else if (needsRenderScriptOverride) {
5874                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5875                    }
5876                }
5877            } catch (IOException ioe) {
5878                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5879            } finally {
5880                IoUtils.closeQuietly(handle);
5881            }
5882
5883            // Now that we've calculated the ABIs and determined if it's an internal app,
5884            // we will go ahead and populate the nativeLibraryPath.
5885            setNativeLibraryPaths(pkg);
5886
5887            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5888            final int[] userIds = sUserManager.getUserIds();
5889            synchronized (mInstallLock) {
5890                // Create a native library symlink only if we have native libraries
5891                // and if the native libraries are 32 bit libraries. We do not provide
5892                // this symlink for 64 bit libraries.
5893                if (pkg.applicationInfo.primaryCpuAbi != null &&
5894                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5895                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5896                    for (int userId : userIds) {
5897                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5898                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5899                                    "Failed linking native library dir (user=" + userId + ")");
5900                        }
5901                    }
5902                }
5903            }
5904        }
5905
5906        // This is a special case for the "system" package, where the ABI is
5907        // dictated by the zygote configuration (and init.rc). We should keep track
5908        // of this ABI so that we can deal with "normal" applications that run under
5909        // the same UID correctly.
5910        if (mPlatformPackage == pkg) {
5911            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5912                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5913        }
5914
5915        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5916        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5917        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5918        // Copy the derived override back to the parsed package, so that we can
5919        // update the package settings accordingly.
5920        pkg.cpuAbiOverride = cpuAbiOverride;
5921
5922        if (DEBUG_ABI_SELECTION) {
5923            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5924                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5925                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5926        }
5927
5928        // Push the derived path down into PackageSettings so we know what to
5929        // clean up at uninstall time.
5930        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5931
5932        if (DEBUG_ABI_SELECTION) {
5933            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5934                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5935                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5936        }
5937
5938        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5939            // We don't do this here during boot because we can do it all
5940            // at once after scanning all existing packages.
5941            //
5942            // We also do this *before* we perform dexopt on this package, so that
5943            // we can avoid redundant dexopts, and also to make sure we've got the
5944            // code and package path correct.
5945            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5946                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5947        }
5948
5949        if ((scanFlags & SCAN_NO_DEX) == 0) {
5950            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5951                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5952                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5953            }
5954        }
5955
5956        if (mFactoryTest && pkg.requestedPermissions.contains(
5957                android.Manifest.permission.FACTORY_TEST)) {
5958            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5959        }
5960
5961        ArrayList<PackageParser.Package> clientLibPkgs = null;
5962
5963        // writer
5964        synchronized (mPackages) {
5965            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5966                // Only system apps can add new shared libraries.
5967                if (pkg.libraryNames != null) {
5968                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5969                        String name = pkg.libraryNames.get(i);
5970                        boolean allowed = false;
5971                        if (isUpdatedSystemApp(pkg)) {
5972                            // New library entries can only be added through the
5973                            // system image.  This is important to get rid of a lot
5974                            // of nasty edge cases: for example if we allowed a non-
5975                            // system update of the app to add a library, then uninstalling
5976                            // the update would make the library go away, and assumptions
5977                            // we made such as through app install filtering would now
5978                            // have allowed apps on the device which aren't compatible
5979                            // with it.  Better to just have the restriction here, be
5980                            // conservative, and create many fewer cases that can negatively
5981                            // impact the user experience.
5982                            final PackageSetting sysPs = mSettings
5983                                    .getDisabledSystemPkgLPr(pkg.packageName);
5984                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5985                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5986                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5987                                        allowed = true;
5988                                        allowed = true;
5989                                        break;
5990                                    }
5991                                }
5992                            }
5993                        } else {
5994                            allowed = true;
5995                        }
5996                        if (allowed) {
5997                            if (!mSharedLibraries.containsKey(name)) {
5998                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5999                            } else if (!name.equals(pkg.packageName)) {
6000                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6001                                        + name + " already exists; skipping");
6002                            }
6003                        } else {
6004                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6005                                    + name + " that is not declared on system image; skipping");
6006                        }
6007                    }
6008                    if ((scanFlags&SCAN_BOOTING) == 0) {
6009                        // If we are not booting, we need to update any applications
6010                        // that are clients of our shared library.  If we are booting,
6011                        // this will all be done once the scan is complete.
6012                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6013                    }
6014                }
6015            }
6016        }
6017
6018        // We also need to dexopt any apps that are dependent on this library.  Note that
6019        // if these fail, we should abort the install since installing the library will
6020        // result in some apps being broken.
6021        if (clientLibPkgs != null) {
6022            if ((scanFlags & SCAN_NO_DEX) == 0) {
6023                for (int i = 0; i < clientLibPkgs.size(); i++) {
6024                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6025                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
6026                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
6027                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6028                                "scanPackageLI failed to dexopt clientLibPkgs");
6029                    }
6030                }
6031            }
6032        }
6033
6034        // Request the ActivityManager to kill the process(only for existing packages)
6035        // so that we do not end up in a confused state while the user is still using the older
6036        // version of the application while the new one gets installed.
6037        if ((scanFlags & SCAN_REPLACING) != 0) {
6038            killApplication(pkg.applicationInfo.packageName,
6039                        pkg.applicationInfo.uid, "update pkg");
6040        }
6041
6042        // Also need to kill any apps that are dependent on the library.
6043        if (clientLibPkgs != null) {
6044            for (int i=0; i<clientLibPkgs.size(); i++) {
6045                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6046                killApplication(clientPkg.applicationInfo.packageName,
6047                        clientPkg.applicationInfo.uid, "update lib");
6048            }
6049        }
6050
6051        // writer
6052        synchronized (mPackages) {
6053            // We don't expect installation to fail beyond this point
6054
6055            // Add the new setting to mSettings
6056            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6057            // Add the new setting to mPackages
6058            mPackages.put(pkg.applicationInfo.packageName, pkg);
6059            // Make sure we don't accidentally delete its data.
6060            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6061            while (iter.hasNext()) {
6062                PackageCleanItem item = iter.next();
6063                if (pkgName.equals(item.packageName)) {
6064                    iter.remove();
6065                }
6066            }
6067
6068            // Take care of first install / last update times.
6069            if (currentTime != 0) {
6070                if (pkgSetting.firstInstallTime == 0) {
6071                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6072                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6073                    pkgSetting.lastUpdateTime = currentTime;
6074                }
6075            } else if (pkgSetting.firstInstallTime == 0) {
6076                // We need *something*.  Take time time stamp of the file.
6077                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6078            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6079                if (scanFileTime != pkgSetting.timeStamp) {
6080                    // A package on the system image has changed; consider this
6081                    // to be an update.
6082                    pkgSetting.lastUpdateTime = scanFileTime;
6083                }
6084            }
6085
6086            // Add the package's KeySets to the global KeySetManagerService
6087            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6088            try {
6089                // Old KeySetData no longer valid.
6090                ksms.removeAppKeySetDataLPw(pkg.packageName);
6091                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6092                if (pkg.mKeySetMapping != null) {
6093                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
6094                            pkg.mKeySetMapping.entrySet()) {
6095                        if (entry.getValue() != null) {
6096                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
6097                                                          entry.getValue(), entry.getKey());
6098                        }
6099                    }
6100                    if (pkg.mUpgradeKeySets != null) {
6101                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
6102                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
6103                        }
6104                    }
6105                }
6106            } catch (NullPointerException e) {
6107                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6108            } catch (IllegalArgumentException e) {
6109                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6110            }
6111
6112            int N = pkg.providers.size();
6113            StringBuilder r = null;
6114            int i;
6115            for (i=0; i<N; i++) {
6116                PackageParser.Provider p = pkg.providers.get(i);
6117                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6118                        p.info.processName, pkg.applicationInfo.uid);
6119                mProviders.addProvider(p);
6120                p.syncable = p.info.isSyncable;
6121                if (p.info.authority != null) {
6122                    String names[] = p.info.authority.split(";");
6123                    p.info.authority = null;
6124                    for (int j = 0; j < names.length; j++) {
6125                        if (j == 1 && p.syncable) {
6126                            // We only want the first authority for a provider to possibly be
6127                            // syncable, so if we already added this provider using a different
6128                            // authority clear the syncable flag. We copy the provider before
6129                            // changing it because the mProviders object contains a reference
6130                            // to a provider that we don't want to change.
6131                            // Only do this for the second authority since the resulting provider
6132                            // object can be the same for all future authorities for this provider.
6133                            p = new PackageParser.Provider(p);
6134                            p.syncable = false;
6135                        }
6136                        if (!mProvidersByAuthority.containsKey(names[j])) {
6137                            mProvidersByAuthority.put(names[j], p);
6138                            if (p.info.authority == null) {
6139                                p.info.authority = names[j];
6140                            } else {
6141                                p.info.authority = p.info.authority + ";" + names[j];
6142                            }
6143                            if (DEBUG_PACKAGE_SCANNING) {
6144                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6145                                    Log.d(TAG, "Registered content provider: " + names[j]
6146                                            + ", className = " + p.info.name + ", isSyncable = "
6147                                            + p.info.isSyncable);
6148                            }
6149                        } else {
6150                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6151                            Slog.w(TAG, "Skipping provider name " + names[j] +
6152                                    " (in package " + pkg.applicationInfo.packageName +
6153                                    "): name already used by "
6154                                    + ((other != null && other.getComponentName() != null)
6155                                            ? other.getComponentName().getPackageName() : "?"));
6156                        }
6157                    }
6158                }
6159                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6160                    if (r == null) {
6161                        r = new StringBuilder(256);
6162                    } else {
6163                        r.append(' ');
6164                    }
6165                    r.append(p.info.name);
6166                }
6167            }
6168            if (r != null) {
6169                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6170            }
6171
6172            N = pkg.services.size();
6173            r = null;
6174            for (i=0; i<N; i++) {
6175                PackageParser.Service s = pkg.services.get(i);
6176                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6177                        s.info.processName, pkg.applicationInfo.uid);
6178                mServices.addService(s);
6179                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6180                    if (r == null) {
6181                        r = new StringBuilder(256);
6182                    } else {
6183                        r.append(' ');
6184                    }
6185                    r.append(s.info.name);
6186                }
6187            }
6188            if (r != null) {
6189                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6190            }
6191
6192            N = pkg.receivers.size();
6193            r = null;
6194            for (i=0; i<N; i++) {
6195                PackageParser.Activity a = pkg.receivers.get(i);
6196                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6197                        a.info.processName, pkg.applicationInfo.uid);
6198                mReceivers.addActivity(a, "receiver");
6199                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6200                    if (r == null) {
6201                        r = new StringBuilder(256);
6202                    } else {
6203                        r.append(' ');
6204                    }
6205                    r.append(a.info.name);
6206                }
6207            }
6208            if (r != null) {
6209                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6210            }
6211
6212            N = pkg.activities.size();
6213            r = null;
6214            for (i=0; i<N; i++) {
6215                PackageParser.Activity a = pkg.activities.get(i);
6216                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6217                        a.info.processName, pkg.applicationInfo.uid);
6218                mActivities.addActivity(a, "activity");
6219                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6220                    if (r == null) {
6221                        r = new StringBuilder(256);
6222                    } else {
6223                        r.append(' ');
6224                    }
6225                    r.append(a.info.name);
6226                }
6227            }
6228            if (r != null) {
6229                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6230            }
6231
6232            N = pkg.permissionGroups.size();
6233            r = null;
6234            for (i=0; i<N; i++) {
6235                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6236                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6237                if (cur == null) {
6238                    mPermissionGroups.put(pg.info.name, pg);
6239                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6240                        if (r == null) {
6241                            r = new StringBuilder(256);
6242                        } else {
6243                            r.append(' ');
6244                        }
6245                        r.append(pg.info.name);
6246                    }
6247                } else {
6248                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6249                            + pg.info.packageName + " ignored: original from "
6250                            + cur.info.packageName);
6251                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6252                        if (r == null) {
6253                            r = new StringBuilder(256);
6254                        } else {
6255                            r.append(' ');
6256                        }
6257                        r.append("DUP:");
6258                        r.append(pg.info.name);
6259                    }
6260                }
6261            }
6262            if (r != null) {
6263                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6264            }
6265
6266            N = pkg.permissions.size();
6267            r = null;
6268            for (i=0; i<N; i++) {
6269                PackageParser.Permission p = pkg.permissions.get(i);
6270                ArrayMap<String, BasePermission> permissionMap =
6271                        p.tree ? mSettings.mPermissionTrees
6272                        : mSettings.mPermissions;
6273                p.group = mPermissionGroups.get(p.info.group);
6274                if (p.info.group == null || p.group != null) {
6275                    BasePermission bp = permissionMap.get(p.info.name);
6276
6277                    // Allow system apps to redefine non-system permissions
6278                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6279                        final boolean currentOwnerIsSystem = (bp.perm != null
6280                                && isSystemApp(bp.perm.owner));
6281                        if (isSystemApp(p.owner)) {
6282                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6283                                // It's a built-in permission and no owner, take ownership now
6284                                bp.packageSetting = pkgSetting;
6285                                bp.perm = p;
6286                                bp.uid = pkg.applicationInfo.uid;
6287                                bp.sourcePackage = p.info.packageName;
6288                            } else if (!currentOwnerIsSystem) {
6289                                String msg = "New decl " + p.owner + " of permission  "
6290                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6291                                reportSettingsProblem(Log.WARN, msg);
6292                                bp = null;
6293                            }
6294                        }
6295                    }
6296
6297                    if (bp == null) {
6298                        bp = new BasePermission(p.info.name, p.info.packageName,
6299                                BasePermission.TYPE_NORMAL);
6300                        permissionMap.put(p.info.name, bp);
6301                    }
6302
6303                    if (bp.perm == null) {
6304                        if (bp.sourcePackage == null
6305                                || bp.sourcePackage.equals(p.info.packageName)) {
6306                            BasePermission tree = findPermissionTreeLP(p.info.name);
6307                            if (tree == null
6308                                    || tree.sourcePackage.equals(p.info.packageName)) {
6309                                bp.packageSetting = pkgSetting;
6310                                bp.perm = p;
6311                                bp.uid = pkg.applicationInfo.uid;
6312                                bp.sourcePackage = p.info.packageName;
6313                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6314                                    if (r == null) {
6315                                        r = new StringBuilder(256);
6316                                    } else {
6317                                        r.append(' ');
6318                                    }
6319                                    r.append(p.info.name);
6320                                }
6321                            } else {
6322                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6323                                        + p.info.packageName + " ignored: base tree "
6324                                        + tree.name + " is from package "
6325                                        + tree.sourcePackage);
6326                            }
6327                        } else {
6328                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6329                                    + p.info.packageName + " ignored: original from "
6330                                    + bp.sourcePackage);
6331                        }
6332                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6333                        if (r == null) {
6334                            r = new StringBuilder(256);
6335                        } else {
6336                            r.append(' ');
6337                        }
6338                        r.append("DUP:");
6339                        r.append(p.info.name);
6340                    }
6341                    if (bp.perm == p) {
6342                        bp.protectionLevel = p.info.protectionLevel;
6343                    }
6344                } else {
6345                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6346                            + p.info.packageName + " ignored: no group "
6347                            + p.group);
6348                }
6349            }
6350            if (r != null) {
6351                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6352            }
6353
6354            N = pkg.instrumentation.size();
6355            r = null;
6356            for (i=0; i<N; i++) {
6357                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6358                a.info.packageName = pkg.applicationInfo.packageName;
6359                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6360                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6361                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6362                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6363                a.info.dataDir = pkg.applicationInfo.dataDir;
6364
6365                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6366                // need other information about the application, like the ABI and what not ?
6367                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6368                mInstrumentation.put(a.getComponentName(), a);
6369                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6370                    if (r == null) {
6371                        r = new StringBuilder(256);
6372                    } else {
6373                        r.append(' ');
6374                    }
6375                    r.append(a.info.name);
6376                }
6377            }
6378            if (r != null) {
6379                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6380            }
6381
6382            if (pkg.protectedBroadcasts != null) {
6383                N = pkg.protectedBroadcasts.size();
6384                for (i=0; i<N; i++) {
6385                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6386                }
6387            }
6388
6389            pkgSetting.setTimeStamp(scanFileTime);
6390
6391            // Create idmap files for pairs of (packages, overlay packages).
6392            // Note: "android", ie framework-res.apk, is handled by native layers.
6393            if (pkg.mOverlayTarget != null) {
6394                // This is an overlay package.
6395                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6396                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6397                        mOverlays.put(pkg.mOverlayTarget,
6398                                new ArrayMap<String, PackageParser.Package>());
6399                    }
6400                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6401                    map.put(pkg.packageName, pkg);
6402                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6403                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6404                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6405                                "scanPackageLI failed to createIdmap");
6406                    }
6407                }
6408            } else if (mOverlays.containsKey(pkg.packageName) &&
6409                    !pkg.packageName.equals("android")) {
6410                // This is a regular package, with one or more known overlay packages.
6411                createIdmapsForPackageLI(pkg);
6412            }
6413        }
6414
6415        return pkg;
6416    }
6417
6418    /**
6419     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6420     * i.e, so that all packages can be run inside a single process if required.
6421     *
6422     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6423     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6424     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6425     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6426     * updating a package that belongs to a shared user.
6427     *
6428     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6429     * adds unnecessary complexity.
6430     */
6431    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6432            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6433        String requiredInstructionSet = null;
6434        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6435            requiredInstructionSet = VMRuntime.getInstructionSet(
6436                     scannedPackage.applicationInfo.primaryCpuAbi);
6437        }
6438
6439        PackageSetting requirer = null;
6440        for (PackageSetting ps : packagesForUser) {
6441            // If packagesForUser contains scannedPackage, we skip it. This will happen
6442            // when scannedPackage is an update of an existing package. Without this check,
6443            // we will never be able to change the ABI of any package belonging to a shared
6444            // user, even if it's compatible with other packages.
6445            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6446                if (ps.primaryCpuAbiString == null) {
6447                    continue;
6448                }
6449
6450                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6451                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6452                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6453                    // this but there's not much we can do.
6454                    String errorMessage = "Instruction set mismatch, "
6455                            + ((requirer == null) ? "[caller]" : requirer)
6456                            + " requires " + requiredInstructionSet + " whereas " + ps
6457                            + " requires " + instructionSet;
6458                    Slog.w(TAG, errorMessage);
6459                }
6460
6461                if (requiredInstructionSet == null) {
6462                    requiredInstructionSet = instructionSet;
6463                    requirer = ps;
6464                }
6465            }
6466        }
6467
6468        if (requiredInstructionSet != null) {
6469            String adjustedAbi;
6470            if (requirer != null) {
6471                // requirer != null implies that either scannedPackage was null or that scannedPackage
6472                // did not require an ABI, in which case we have to adjust scannedPackage to match
6473                // the ABI of the set (which is the same as requirer's ABI)
6474                adjustedAbi = requirer.primaryCpuAbiString;
6475                if (scannedPackage != null) {
6476                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6477                }
6478            } else {
6479                // requirer == null implies that we're updating all ABIs in the set to
6480                // match scannedPackage.
6481                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6482            }
6483
6484            for (PackageSetting ps : packagesForUser) {
6485                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6486                    if (ps.primaryCpuAbiString != null) {
6487                        continue;
6488                    }
6489
6490                    ps.primaryCpuAbiString = adjustedAbi;
6491                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6492                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6493                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6494
6495                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6496                                deferDexOpt, true) == DEX_OPT_FAILED) {
6497                            ps.primaryCpuAbiString = null;
6498                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6499                            return;
6500                        } else {
6501                            mInstaller.rmdex(ps.codePathString,
6502                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6503                        }
6504                    }
6505                }
6506            }
6507        }
6508    }
6509
6510    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6511        synchronized (mPackages) {
6512            mResolverReplaced = true;
6513            // Set up information for custom user intent resolution activity.
6514            mResolveActivity.applicationInfo = pkg.applicationInfo;
6515            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6516            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6517            mResolveActivity.processName = pkg.applicationInfo.packageName;
6518            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6519            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6520                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6521            mResolveActivity.theme = 0;
6522            mResolveActivity.exported = true;
6523            mResolveActivity.enabled = true;
6524            mResolveInfo.activityInfo = mResolveActivity;
6525            mResolveInfo.priority = 0;
6526            mResolveInfo.preferredOrder = 0;
6527            mResolveInfo.match = 0;
6528            mResolveComponentName = mCustomResolverComponentName;
6529            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6530                    mResolveComponentName);
6531        }
6532    }
6533
6534    private static String calculateBundledApkRoot(final String codePathString) {
6535        final File codePath = new File(codePathString);
6536        final File codeRoot;
6537        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6538            codeRoot = Environment.getRootDirectory();
6539        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6540            codeRoot = Environment.getOemDirectory();
6541        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6542            codeRoot = Environment.getVendorDirectory();
6543        } else {
6544            // Unrecognized code path; take its top real segment as the apk root:
6545            // e.g. /something/app/blah.apk => /something
6546            try {
6547                File f = codePath.getCanonicalFile();
6548                File parent = f.getParentFile();    // non-null because codePath is a file
6549                File tmp;
6550                while ((tmp = parent.getParentFile()) != null) {
6551                    f = parent;
6552                    parent = tmp;
6553                }
6554                codeRoot = f;
6555                Slog.w(TAG, "Unrecognized code path "
6556                        + codePath + " - using " + codeRoot);
6557            } catch (IOException e) {
6558                // Can't canonicalize the code path -- shenanigans?
6559                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6560                return Environment.getRootDirectory().getPath();
6561            }
6562        }
6563        return codeRoot.getPath();
6564    }
6565
6566    /**
6567     * Derive and set the location of native libraries for the given package,
6568     * which varies depending on where and how the package was installed.
6569     */
6570    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6571        final ApplicationInfo info = pkg.applicationInfo;
6572        final String codePath = pkg.codePath;
6573        final File codeFile = new File(codePath);
6574        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6575        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6576
6577        info.nativeLibraryRootDir = null;
6578        info.nativeLibraryRootRequiresIsa = false;
6579        info.nativeLibraryDir = null;
6580        info.secondaryNativeLibraryDir = null;
6581
6582        if (isApkFile(codeFile)) {
6583            // Monolithic install
6584            if (bundledApp) {
6585                // If "/system/lib64/apkname" exists, assume that is the per-package
6586                // native library directory to use; otherwise use "/system/lib/apkname".
6587                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6588                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6589                        getPrimaryInstructionSet(info));
6590
6591                // This is a bundled system app so choose the path based on the ABI.
6592                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6593                // is just the default path.
6594                final String apkName = deriveCodePathName(codePath);
6595                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6596                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6597                        apkName).getAbsolutePath();
6598
6599                if (info.secondaryCpuAbi != null) {
6600                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6601                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6602                            secondaryLibDir, apkName).getAbsolutePath();
6603                }
6604            } else if (asecApp) {
6605                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6606                        .getAbsolutePath();
6607            } else {
6608                final String apkName = deriveCodePathName(codePath);
6609                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6610                        .getAbsolutePath();
6611            }
6612
6613            info.nativeLibraryRootRequiresIsa = false;
6614            info.nativeLibraryDir = info.nativeLibraryRootDir;
6615        } else {
6616            // Cluster install
6617            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6618            info.nativeLibraryRootRequiresIsa = true;
6619
6620            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6621                    getPrimaryInstructionSet(info)).getAbsolutePath();
6622
6623            if (info.secondaryCpuAbi != null) {
6624                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6625                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6626            }
6627        }
6628    }
6629
6630    /**
6631     * Calculate the abis and roots for a bundled app. These can uniquely
6632     * be determined from the contents of the system partition, i.e whether
6633     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6634     * of this information, and instead assume that the system was built
6635     * sensibly.
6636     */
6637    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6638                                           PackageSetting pkgSetting) {
6639        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6640
6641        // If "/system/lib64/apkname" exists, assume that is the per-package
6642        // native library directory to use; otherwise use "/system/lib/apkname".
6643        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6644        setBundledAppAbi(pkg, apkRoot, apkName);
6645        // pkgSetting might be null during rescan following uninstall of updates
6646        // to a bundled app, so accommodate that possibility.  The settings in
6647        // that case will be established later from the parsed package.
6648        //
6649        // If the settings aren't null, sync them up with what we've just derived.
6650        // note that apkRoot isn't stored in the package settings.
6651        if (pkgSetting != null) {
6652            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6653            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6654        }
6655    }
6656
6657    /**
6658     * Deduces the ABI of a bundled app and sets the relevant fields on the
6659     * parsed pkg object.
6660     *
6661     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6662     *        under which system libraries are installed.
6663     * @param apkName the name of the installed package.
6664     */
6665    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6666        final File codeFile = new File(pkg.codePath);
6667
6668        final boolean has64BitLibs;
6669        final boolean has32BitLibs;
6670        if (isApkFile(codeFile)) {
6671            // Monolithic install
6672            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6673            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6674        } else {
6675            // Cluster install
6676            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6677            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6678                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6679                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6680                has64BitLibs = (new File(rootDir, isa)).exists();
6681            } else {
6682                has64BitLibs = false;
6683            }
6684            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6685                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6686                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6687                has32BitLibs = (new File(rootDir, isa)).exists();
6688            } else {
6689                has32BitLibs = false;
6690            }
6691        }
6692
6693        if (has64BitLibs && !has32BitLibs) {
6694            // The package has 64 bit libs, but not 32 bit libs. Its primary
6695            // ABI should be 64 bit. We can safely assume here that the bundled
6696            // native libraries correspond to the most preferred ABI in the list.
6697
6698            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6699            pkg.applicationInfo.secondaryCpuAbi = null;
6700        } else if (has32BitLibs && !has64BitLibs) {
6701            // The package has 32 bit libs but not 64 bit libs. Its primary
6702            // ABI should be 32 bit.
6703
6704            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6705            pkg.applicationInfo.secondaryCpuAbi = null;
6706        } else if (has32BitLibs && has64BitLibs) {
6707            // The application has both 64 and 32 bit bundled libraries. We check
6708            // here that the app declares multiArch support, and warn if it doesn't.
6709            //
6710            // We will be lenient here and record both ABIs. The primary will be the
6711            // ABI that's higher on the list, i.e, a device that's configured to prefer
6712            // 64 bit apps will see a 64 bit primary ABI,
6713
6714            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6715                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6716            }
6717
6718            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6719                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6720                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6721            } else {
6722                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6723                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6724            }
6725        } else {
6726            pkg.applicationInfo.primaryCpuAbi = null;
6727            pkg.applicationInfo.secondaryCpuAbi = null;
6728        }
6729    }
6730
6731    private void killApplication(String pkgName, int appId, String reason) {
6732        // Request the ActivityManager to kill the process(only for existing packages)
6733        // so that we do not end up in a confused state while the user is still using the older
6734        // version of the application while the new one gets installed.
6735        IActivityManager am = ActivityManagerNative.getDefault();
6736        if (am != null) {
6737            try {
6738                am.killApplicationWithAppId(pkgName, appId, reason);
6739            } catch (RemoteException e) {
6740            }
6741        }
6742    }
6743
6744    void removePackageLI(PackageSetting ps, boolean chatty) {
6745        if (DEBUG_INSTALL) {
6746            if (chatty)
6747                Log.d(TAG, "Removing package " + ps.name);
6748        }
6749
6750        // writer
6751        synchronized (mPackages) {
6752            mPackages.remove(ps.name);
6753            final PackageParser.Package pkg = ps.pkg;
6754            if (pkg != null) {
6755                cleanPackageDataStructuresLILPw(pkg, chatty);
6756            }
6757        }
6758    }
6759
6760    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6761        if (DEBUG_INSTALL) {
6762            if (chatty)
6763                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6764        }
6765
6766        // writer
6767        synchronized (mPackages) {
6768            mPackages.remove(pkg.applicationInfo.packageName);
6769            cleanPackageDataStructuresLILPw(pkg, chatty);
6770        }
6771    }
6772
6773    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6774        int N = pkg.providers.size();
6775        StringBuilder r = null;
6776        int i;
6777        for (i=0; i<N; i++) {
6778            PackageParser.Provider p = pkg.providers.get(i);
6779            mProviders.removeProvider(p);
6780            if (p.info.authority == null) {
6781
6782                /* There was another ContentProvider with this authority when
6783                 * this app was installed so this authority is null,
6784                 * Ignore it as we don't have to unregister the provider.
6785                 */
6786                continue;
6787            }
6788            String names[] = p.info.authority.split(";");
6789            for (int j = 0; j < names.length; j++) {
6790                if (mProvidersByAuthority.get(names[j]) == p) {
6791                    mProvidersByAuthority.remove(names[j]);
6792                    if (DEBUG_REMOVE) {
6793                        if (chatty)
6794                            Log.d(TAG, "Unregistered content provider: " + names[j]
6795                                    + ", className = " + p.info.name + ", isSyncable = "
6796                                    + p.info.isSyncable);
6797                    }
6798                }
6799            }
6800            if (DEBUG_REMOVE && chatty) {
6801                if (r == null) {
6802                    r = new StringBuilder(256);
6803                } else {
6804                    r.append(' ');
6805                }
6806                r.append(p.info.name);
6807            }
6808        }
6809        if (r != null) {
6810            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6811        }
6812
6813        N = pkg.services.size();
6814        r = null;
6815        for (i=0; i<N; i++) {
6816            PackageParser.Service s = pkg.services.get(i);
6817            mServices.removeService(s);
6818            if (chatty) {
6819                if (r == null) {
6820                    r = new StringBuilder(256);
6821                } else {
6822                    r.append(' ');
6823                }
6824                r.append(s.info.name);
6825            }
6826        }
6827        if (r != null) {
6828            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6829        }
6830
6831        N = pkg.receivers.size();
6832        r = null;
6833        for (i=0; i<N; i++) {
6834            PackageParser.Activity a = pkg.receivers.get(i);
6835            mReceivers.removeActivity(a, "receiver");
6836            if (DEBUG_REMOVE && chatty) {
6837                if (r == null) {
6838                    r = new StringBuilder(256);
6839                } else {
6840                    r.append(' ');
6841                }
6842                r.append(a.info.name);
6843            }
6844        }
6845        if (r != null) {
6846            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6847        }
6848
6849        N = pkg.activities.size();
6850        r = null;
6851        for (i=0; i<N; i++) {
6852            PackageParser.Activity a = pkg.activities.get(i);
6853            mActivities.removeActivity(a, "activity");
6854            if (DEBUG_REMOVE && chatty) {
6855                if (r == null) {
6856                    r = new StringBuilder(256);
6857                } else {
6858                    r.append(' ');
6859                }
6860                r.append(a.info.name);
6861            }
6862        }
6863        if (r != null) {
6864            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6865        }
6866
6867        N = pkg.permissions.size();
6868        r = null;
6869        for (i=0; i<N; i++) {
6870            PackageParser.Permission p = pkg.permissions.get(i);
6871            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6872            if (bp == null) {
6873                bp = mSettings.mPermissionTrees.get(p.info.name);
6874            }
6875            if (bp != null && bp.perm == p) {
6876                bp.perm = null;
6877                if (DEBUG_REMOVE && chatty) {
6878                    if (r == null) {
6879                        r = new StringBuilder(256);
6880                    } else {
6881                        r.append(' ');
6882                    }
6883                    r.append(p.info.name);
6884                }
6885            }
6886            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6887                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6888                if (appOpPerms != null) {
6889                    appOpPerms.remove(pkg.packageName);
6890                }
6891            }
6892        }
6893        if (r != null) {
6894            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6895        }
6896
6897        N = pkg.requestedPermissions.size();
6898        r = null;
6899        for (i=0; i<N; i++) {
6900            String perm = pkg.requestedPermissions.get(i);
6901            BasePermission bp = mSettings.mPermissions.get(perm);
6902            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6903                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6904                if (appOpPerms != null) {
6905                    appOpPerms.remove(pkg.packageName);
6906                    if (appOpPerms.isEmpty()) {
6907                        mAppOpPermissionPackages.remove(perm);
6908                    }
6909                }
6910            }
6911        }
6912        if (r != null) {
6913            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6914        }
6915
6916        N = pkg.instrumentation.size();
6917        r = null;
6918        for (i=0; i<N; i++) {
6919            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6920            mInstrumentation.remove(a.getComponentName());
6921            if (DEBUG_REMOVE && chatty) {
6922                if (r == null) {
6923                    r = new StringBuilder(256);
6924                } else {
6925                    r.append(' ');
6926                }
6927                r.append(a.info.name);
6928            }
6929        }
6930        if (r != null) {
6931            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6932        }
6933
6934        r = null;
6935        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6936            // Only system apps can hold shared libraries.
6937            if (pkg.libraryNames != null) {
6938                for (i=0; i<pkg.libraryNames.size(); i++) {
6939                    String name = pkg.libraryNames.get(i);
6940                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6941                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6942                        mSharedLibraries.remove(name);
6943                        if (DEBUG_REMOVE && chatty) {
6944                            if (r == null) {
6945                                r = new StringBuilder(256);
6946                            } else {
6947                                r.append(' ');
6948                            }
6949                            r.append(name);
6950                        }
6951                    }
6952                }
6953            }
6954        }
6955        if (r != null) {
6956            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6957        }
6958    }
6959
6960    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6961        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6962            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6963                return true;
6964            }
6965        }
6966        return false;
6967    }
6968
6969    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6970    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6971    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6972
6973    private void updatePermissionsLPw(String changingPkg,
6974            PackageParser.Package pkgInfo, int flags) {
6975        // Make sure there are no dangling permission trees.
6976        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6977        while (it.hasNext()) {
6978            final BasePermission bp = it.next();
6979            if (bp.packageSetting == null) {
6980                // We may not yet have parsed the package, so just see if
6981                // we still know about its settings.
6982                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6983            }
6984            if (bp.packageSetting == null) {
6985                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6986                        + " from package " + bp.sourcePackage);
6987                it.remove();
6988            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6989                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6990                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6991                            + " from package " + bp.sourcePackage);
6992                    flags |= UPDATE_PERMISSIONS_ALL;
6993                    it.remove();
6994                }
6995            }
6996        }
6997
6998        // Make sure all dynamic permissions have been assigned to a package,
6999        // and make sure there are no dangling permissions.
7000        it = mSettings.mPermissions.values().iterator();
7001        while (it.hasNext()) {
7002            final BasePermission bp = it.next();
7003            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7004                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7005                        + bp.name + " pkg=" + bp.sourcePackage
7006                        + " info=" + bp.pendingInfo);
7007                if (bp.packageSetting == null && bp.pendingInfo != null) {
7008                    final BasePermission tree = findPermissionTreeLP(bp.name);
7009                    if (tree != null && tree.perm != null) {
7010                        bp.packageSetting = tree.packageSetting;
7011                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7012                                new PermissionInfo(bp.pendingInfo));
7013                        bp.perm.info.packageName = tree.perm.info.packageName;
7014                        bp.perm.info.name = bp.name;
7015                        bp.uid = tree.uid;
7016                    }
7017                }
7018            }
7019            if (bp.packageSetting == null) {
7020                // We may not yet have parsed the package, so just see if
7021                // we still know about its settings.
7022                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7023            }
7024            if (bp.packageSetting == null) {
7025                Slog.w(TAG, "Removing dangling permission: " + bp.name
7026                        + " from package " + bp.sourcePackage);
7027                it.remove();
7028            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7029                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7030                    Slog.i(TAG, "Removing old permission: " + bp.name
7031                            + " from package " + bp.sourcePackage);
7032                    flags |= UPDATE_PERMISSIONS_ALL;
7033                    it.remove();
7034                }
7035            }
7036        }
7037
7038        // Now update the permissions for all packages, in particular
7039        // replace the granted permissions of the system packages.
7040        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7041            for (PackageParser.Package pkg : mPackages.values()) {
7042                if (pkg != pkgInfo) {
7043                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7044                            changingPkg);
7045                }
7046            }
7047        }
7048
7049        if (pkgInfo != null) {
7050            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7051        }
7052    }
7053
7054    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7055            String packageOfInterest) {
7056        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7057        if (ps == null) {
7058            return;
7059        }
7060        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
7061        ArraySet<String> origPermissions = gp.grantedPermissions;
7062        boolean changedPermission = false;
7063
7064        if (replace) {
7065            ps.permissionsFixed = false;
7066            if (gp == ps) {
7067                origPermissions = new ArraySet<String>(gp.grantedPermissions);
7068                gp.grantedPermissions.clear();
7069                gp.gids = mGlobalGids;
7070            }
7071        }
7072
7073        if (gp.gids == null) {
7074            gp.gids = mGlobalGids;
7075        }
7076
7077        final int N = pkg.requestedPermissions.size();
7078        for (int i=0; i<N; i++) {
7079            final String name = pkg.requestedPermissions.get(i);
7080            final boolean required = pkg.requestedPermissionsRequired.get(i);
7081            final BasePermission bp = mSettings.mPermissions.get(name);
7082            if (DEBUG_INSTALL) {
7083                if (gp != ps) {
7084                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7085                }
7086            }
7087
7088            if (bp == null || bp.packageSetting == null) {
7089                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7090                    Slog.w(TAG, "Unknown permission " + name
7091                            + " in package " + pkg.packageName);
7092                }
7093                continue;
7094            }
7095
7096            final String perm = bp.name;
7097            boolean allowed;
7098            boolean allowedSig = false;
7099            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7100                // Keep track of app op permissions.
7101                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7102                if (pkgs == null) {
7103                    pkgs = new ArraySet<>();
7104                    mAppOpPermissionPackages.put(bp.name, pkgs);
7105                }
7106                pkgs.add(pkg.packageName);
7107            }
7108            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7109            if (level == PermissionInfo.PROTECTION_NORMAL
7110                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
7111                // We grant a normal or dangerous permission if any of the following
7112                // are true:
7113                // 1) The permission is required
7114                // 2) The permission is optional, but was granted in the past
7115                // 3) The permission is optional, but was requested by an
7116                //    app in /system (not /data)
7117                //
7118                // Otherwise, reject the permission.
7119                allowed = (required || origPermissions.contains(perm)
7120                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
7121            } else if (bp.packageSetting == null) {
7122                // This permission is invalid; skip it.
7123                allowed = false;
7124            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
7125                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
7126                if (allowed) {
7127                    allowedSig = true;
7128                }
7129            } else {
7130                allowed = false;
7131            }
7132            if (DEBUG_INSTALL) {
7133                if (gp != ps) {
7134                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7135                }
7136            }
7137            if (allowed) {
7138                if (!isSystemApp(ps) && ps.permissionsFixed) {
7139                    // If this is an existing, non-system package, then
7140                    // we can't add any new permissions to it.
7141                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
7142                        // Except...  if this is a permission that was added
7143                        // to the platform (note: need to only do this when
7144                        // updating the platform).
7145                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
7146                    }
7147                }
7148                if (allowed) {
7149                    if (!gp.grantedPermissions.contains(perm)) {
7150                        changedPermission = true;
7151                        gp.grantedPermissions.add(perm);
7152                        gp.gids = appendInts(gp.gids, bp.gids);
7153                    } else if (!ps.haveGids) {
7154                        gp.gids = appendInts(gp.gids, bp.gids);
7155                    }
7156                } else {
7157                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7158                        Slog.w(TAG, "Not granting permission " + perm
7159                                + " to package " + pkg.packageName
7160                                + " because it was previously installed without");
7161                    }
7162                }
7163            } else {
7164                if (gp.grantedPermissions.remove(perm)) {
7165                    changedPermission = true;
7166                    gp.gids = removeInts(gp.gids, bp.gids);
7167                    Slog.i(TAG, "Un-granting permission " + perm
7168                            + " from package " + pkg.packageName
7169                            + " (protectionLevel=" + bp.protectionLevel
7170                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7171                            + ")");
7172                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7173                    // Don't print warning for app op permissions, since it is fine for them
7174                    // not to be granted, there is a UI for the user to decide.
7175                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7176                        Slog.w(TAG, "Not granting permission " + perm
7177                                + " to package " + pkg.packageName
7178                                + " (protectionLevel=" + bp.protectionLevel
7179                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7180                                + ")");
7181                    }
7182                }
7183            }
7184        }
7185
7186        if ((changedPermission || replace) && !ps.permissionsFixed &&
7187                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7188            // This is the first that we have heard about this package, so the
7189            // permissions we have now selected are fixed until explicitly
7190            // changed.
7191            ps.permissionsFixed = true;
7192        }
7193        ps.haveGids = true;
7194    }
7195
7196    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7197        boolean allowed = false;
7198        final int NP = PackageParser.NEW_PERMISSIONS.length;
7199        for (int ip=0; ip<NP; ip++) {
7200            final PackageParser.NewPermissionInfo npi
7201                    = PackageParser.NEW_PERMISSIONS[ip];
7202            if (npi.name.equals(perm)
7203                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7204                allowed = true;
7205                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7206                        + pkg.packageName);
7207                break;
7208            }
7209        }
7210        return allowed;
7211    }
7212
7213    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7214                                          BasePermission bp, ArraySet<String> origPermissions) {
7215        boolean allowed;
7216        allowed = (compareSignatures(
7217                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7218                        == PackageManager.SIGNATURE_MATCH)
7219                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7220                        == PackageManager.SIGNATURE_MATCH);
7221        if (!allowed && (bp.protectionLevel
7222                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7223            if (isSystemApp(pkg)) {
7224                // For updated system applications, a system permission
7225                // is granted only if it had been defined by the original application.
7226                if (isUpdatedSystemApp(pkg)) {
7227                    final PackageSetting sysPs = mSettings
7228                            .getDisabledSystemPkgLPr(pkg.packageName);
7229                    final GrantedPermissions origGp = sysPs.sharedUser != null
7230                            ? sysPs.sharedUser : sysPs;
7231
7232                    if (origGp.grantedPermissions.contains(perm)) {
7233                        // If the original was granted this permission, we take
7234                        // that grant decision as read and propagate it to the
7235                        // update.
7236                        if (sysPs.isPrivileged()) {
7237                            allowed = true;
7238                        }
7239                    } else {
7240                        // The system apk may have been updated with an older
7241                        // version of the one on the data partition, but which
7242                        // granted a new system permission that it didn't have
7243                        // before.  In this case we do want to allow the app to
7244                        // now get the new permission if the ancestral apk is
7245                        // privileged to get it.
7246                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7247                            for (int j=0;
7248                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7249                                if (perm.equals(
7250                                        sysPs.pkg.requestedPermissions.get(j))) {
7251                                    allowed = true;
7252                                    break;
7253                                }
7254                            }
7255                        }
7256                    }
7257                } else {
7258                    allowed = isPrivilegedApp(pkg);
7259                }
7260            }
7261        }
7262        if (!allowed && (bp.protectionLevel
7263                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7264            // For development permissions, a development permission
7265            // is granted only if it was already granted.
7266            allowed = origPermissions.contains(perm);
7267        }
7268        return allowed;
7269    }
7270
7271    final class ActivityIntentResolver
7272            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7273        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7274                boolean defaultOnly, int userId) {
7275            if (!sUserManager.exists(userId)) return null;
7276            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7277            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7278        }
7279
7280        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7281                int userId) {
7282            if (!sUserManager.exists(userId)) return null;
7283            mFlags = flags;
7284            return super.queryIntent(intent, resolvedType,
7285                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7286        }
7287
7288        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7289                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7290            if (!sUserManager.exists(userId)) return null;
7291            if (packageActivities == null) {
7292                return null;
7293            }
7294            mFlags = flags;
7295            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7296            final int N = packageActivities.size();
7297            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7298                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7299
7300            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7301            for (int i = 0; i < N; ++i) {
7302                intentFilters = packageActivities.get(i).intents;
7303                if (intentFilters != null && intentFilters.size() > 0) {
7304                    PackageParser.ActivityIntentInfo[] array =
7305                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7306                    intentFilters.toArray(array);
7307                    listCut.add(array);
7308                }
7309            }
7310            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7311        }
7312
7313        public final void addActivity(PackageParser.Activity a, String type) {
7314            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7315            mActivities.put(a.getComponentName(), a);
7316            if (DEBUG_SHOW_INFO)
7317                Log.v(
7318                TAG, "  " + type + " " +
7319                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7320            if (DEBUG_SHOW_INFO)
7321                Log.v(TAG, "    Class=" + a.info.name);
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 (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7326                    intent.setPriority(0);
7327                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7328                            + a.className + " with priority > 0, forcing to 0");
7329                }
7330                if (DEBUG_SHOW_INFO) {
7331                    Log.v(TAG, "    IntentFilter:");
7332                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7333                }
7334                if (!intent.debugCheck()) {
7335                    Log.w(TAG, "==> For Activity " + a.info.name);
7336                }
7337                addFilter(intent);
7338            }
7339        }
7340
7341        public final void removeActivity(PackageParser.Activity a, String type) {
7342            mActivities.remove(a.getComponentName());
7343            if (DEBUG_SHOW_INFO) {
7344                Log.v(TAG, "  " + type + " "
7345                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7346                                : a.info.name) + ":");
7347                Log.v(TAG, "    Class=" + a.info.name);
7348            }
7349            final int NI = a.intents.size();
7350            for (int j=0; j<NI; j++) {
7351                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7352                if (DEBUG_SHOW_INFO) {
7353                    Log.v(TAG, "    IntentFilter:");
7354                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7355                }
7356                removeFilter(intent);
7357            }
7358        }
7359
7360        @Override
7361        protected boolean allowFilterResult(
7362                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7363            ActivityInfo filterAi = filter.activity.info;
7364            for (int i=dest.size()-1; i>=0; i--) {
7365                ActivityInfo destAi = dest.get(i).activityInfo;
7366                if (destAi.name == filterAi.name
7367                        && destAi.packageName == filterAi.packageName) {
7368                    return false;
7369                }
7370            }
7371            return true;
7372        }
7373
7374        @Override
7375        protected ActivityIntentInfo[] newArray(int size) {
7376            return new ActivityIntentInfo[size];
7377        }
7378
7379        @Override
7380        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7381            if (!sUserManager.exists(userId)) return true;
7382            PackageParser.Package p = filter.activity.owner;
7383            if (p != null) {
7384                PackageSetting ps = (PackageSetting)p.mExtras;
7385                if (ps != null) {
7386                    // System apps are never considered stopped for purposes of
7387                    // filtering, because there may be no way for the user to
7388                    // actually re-launch them.
7389                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7390                            && ps.getStopped(userId);
7391                }
7392            }
7393            return false;
7394        }
7395
7396        @Override
7397        protected boolean isPackageForFilter(String packageName,
7398                PackageParser.ActivityIntentInfo info) {
7399            return packageName.equals(info.activity.owner.packageName);
7400        }
7401
7402        @Override
7403        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7404                int match, int userId) {
7405            if (!sUserManager.exists(userId)) return null;
7406            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7407                return null;
7408            }
7409            final PackageParser.Activity activity = info.activity;
7410            if (mSafeMode && (activity.info.applicationInfo.flags
7411                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7412                return null;
7413            }
7414            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7415            if (ps == null) {
7416                return null;
7417            }
7418            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7419                    ps.readUserState(userId), userId);
7420            if (ai == null) {
7421                return null;
7422            }
7423            final ResolveInfo res = new ResolveInfo();
7424            res.activityInfo = ai;
7425            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7426                res.filter = info;
7427            }
7428            res.priority = info.getPriority();
7429            res.preferredOrder = activity.owner.mPreferredOrder;
7430            //System.out.println("Result: " + res.activityInfo.className +
7431            //                   " = " + res.priority);
7432            res.match = match;
7433            res.isDefault = info.hasDefault;
7434            res.labelRes = info.labelRes;
7435            res.nonLocalizedLabel = info.nonLocalizedLabel;
7436            if (userNeedsBadging(userId)) {
7437                res.noResourceId = true;
7438            } else {
7439                res.icon = info.icon;
7440            }
7441            res.system = isSystemApp(res.activityInfo.applicationInfo);
7442            return res;
7443        }
7444
7445        @Override
7446        protected void sortResults(List<ResolveInfo> results) {
7447            Collections.sort(results, mResolvePrioritySorter);
7448        }
7449
7450        @Override
7451        protected void dumpFilter(PrintWriter out, String prefix,
7452                PackageParser.ActivityIntentInfo filter) {
7453            out.print(prefix); out.print(
7454                    Integer.toHexString(System.identityHashCode(filter.activity)));
7455                    out.print(' ');
7456                    filter.activity.printComponentShortName(out);
7457                    out.print(" filter ");
7458                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7459        }
7460
7461        @Override
7462        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7463            return filter.activity;
7464        }
7465
7466        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7467            PackageParser.Activity activity = (PackageParser.Activity)label;
7468            out.print(prefix); out.print(
7469                    Integer.toHexString(System.identityHashCode(activity)));
7470                    out.print(' ');
7471                    activity.printComponentShortName(out);
7472            if (count > 1) {
7473                out.print(" ("); out.print(count); out.print(" filters)");
7474            }
7475            out.println();
7476        }
7477
7478//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7479//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7480//            final List<ResolveInfo> retList = Lists.newArrayList();
7481//            while (i.hasNext()) {
7482//                final ResolveInfo resolveInfo = i.next();
7483//                if (isEnabledLP(resolveInfo.activityInfo)) {
7484//                    retList.add(resolveInfo);
7485//                }
7486//            }
7487//            return retList;
7488//        }
7489
7490        // Keys are String (activity class name), values are Activity.
7491        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
7492                = new ArrayMap<ComponentName, PackageParser.Activity>();
7493        private int mFlags;
7494    }
7495
7496    private final class ServiceIntentResolver
7497            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7498        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7499                boolean defaultOnly, int userId) {
7500            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7501            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7502        }
7503
7504        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7505                int userId) {
7506            if (!sUserManager.exists(userId)) return null;
7507            mFlags = flags;
7508            return super.queryIntent(intent, resolvedType,
7509                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7510        }
7511
7512        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7513                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7514            if (!sUserManager.exists(userId)) return null;
7515            if (packageServices == null) {
7516                return null;
7517            }
7518            mFlags = flags;
7519            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7520            final int N = packageServices.size();
7521            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7522                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7523
7524            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7525            for (int i = 0; i < N; ++i) {
7526                intentFilters = packageServices.get(i).intents;
7527                if (intentFilters != null && intentFilters.size() > 0) {
7528                    PackageParser.ServiceIntentInfo[] array =
7529                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7530                    intentFilters.toArray(array);
7531                    listCut.add(array);
7532                }
7533            }
7534            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7535        }
7536
7537        public final void addService(PackageParser.Service s) {
7538            mServices.put(s.getComponentName(), s);
7539            if (DEBUG_SHOW_INFO) {
7540                Log.v(TAG, "  "
7541                        + (s.info.nonLocalizedLabel != null
7542                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7543                Log.v(TAG, "    Class=" + s.info.name);
7544            }
7545            final int NI = s.intents.size();
7546            int j;
7547            for (j=0; j<NI; j++) {
7548                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7549                if (DEBUG_SHOW_INFO) {
7550                    Log.v(TAG, "    IntentFilter:");
7551                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7552                }
7553                if (!intent.debugCheck()) {
7554                    Log.w(TAG, "==> For Service " + s.info.name);
7555                }
7556                addFilter(intent);
7557            }
7558        }
7559
7560        public final void removeService(PackageParser.Service s) {
7561            mServices.remove(s.getComponentName());
7562            if (DEBUG_SHOW_INFO) {
7563                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7564                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7565                Log.v(TAG, "    Class=" + s.info.name);
7566            }
7567            final int NI = s.intents.size();
7568            int j;
7569            for (j=0; j<NI; j++) {
7570                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7571                if (DEBUG_SHOW_INFO) {
7572                    Log.v(TAG, "    IntentFilter:");
7573                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7574                }
7575                removeFilter(intent);
7576            }
7577        }
7578
7579        @Override
7580        protected boolean allowFilterResult(
7581                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7582            ServiceInfo filterSi = filter.service.info;
7583            for (int i=dest.size()-1; i>=0; i--) {
7584                ServiceInfo destAi = dest.get(i).serviceInfo;
7585                if (destAi.name == filterSi.name
7586                        && destAi.packageName == filterSi.packageName) {
7587                    return false;
7588                }
7589            }
7590            return true;
7591        }
7592
7593        @Override
7594        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7595            return new PackageParser.ServiceIntentInfo[size];
7596        }
7597
7598        @Override
7599        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7600            if (!sUserManager.exists(userId)) return true;
7601            PackageParser.Package p = filter.service.owner;
7602            if (p != null) {
7603                PackageSetting ps = (PackageSetting)p.mExtras;
7604                if (ps != null) {
7605                    // System apps are never considered stopped for purposes of
7606                    // filtering, because there may be no way for the user to
7607                    // actually re-launch them.
7608                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7609                            && ps.getStopped(userId);
7610                }
7611            }
7612            return false;
7613        }
7614
7615        @Override
7616        protected boolean isPackageForFilter(String packageName,
7617                PackageParser.ServiceIntentInfo info) {
7618            return packageName.equals(info.service.owner.packageName);
7619        }
7620
7621        @Override
7622        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7623                int match, int userId) {
7624            if (!sUserManager.exists(userId)) return null;
7625            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7626            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7627                return null;
7628            }
7629            final PackageParser.Service service = info.service;
7630            if (mSafeMode && (service.info.applicationInfo.flags
7631                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7632                return null;
7633            }
7634            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7635            if (ps == null) {
7636                return null;
7637            }
7638            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7639                    ps.readUserState(userId), userId);
7640            if (si == null) {
7641                return null;
7642            }
7643            final ResolveInfo res = new ResolveInfo();
7644            res.serviceInfo = si;
7645            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7646                res.filter = filter;
7647            }
7648            res.priority = info.getPriority();
7649            res.preferredOrder = service.owner.mPreferredOrder;
7650            //System.out.println("Result: " + res.activityInfo.className +
7651            //                   " = " + res.priority);
7652            res.match = match;
7653            res.isDefault = info.hasDefault;
7654            res.labelRes = info.labelRes;
7655            res.nonLocalizedLabel = info.nonLocalizedLabel;
7656            res.icon = info.icon;
7657            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7658            return res;
7659        }
7660
7661        @Override
7662        protected void sortResults(List<ResolveInfo> results) {
7663            Collections.sort(results, mResolvePrioritySorter);
7664        }
7665
7666        @Override
7667        protected void dumpFilter(PrintWriter out, String prefix,
7668                PackageParser.ServiceIntentInfo filter) {
7669            out.print(prefix); out.print(
7670                    Integer.toHexString(System.identityHashCode(filter.service)));
7671                    out.print(' ');
7672                    filter.service.printComponentShortName(out);
7673                    out.print(" filter ");
7674                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7675        }
7676
7677        @Override
7678        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
7679            return filter.service;
7680        }
7681
7682        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7683            PackageParser.Service service = (PackageParser.Service)label;
7684            out.print(prefix); out.print(
7685                    Integer.toHexString(System.identityHashCode(service)));
7686                    out.print(' ');
7687                    service.printComponentShortName(out);
7688            if (count > 1) {
7689                out.print(" ("); out.print(count); out.print(" filters)");
7690            }
7691            out.println();
7692        }
7693
7694//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7695//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7696//            final List<ResolveInfo> retList = Lists.newArrayList();
7697//            while (i.hasNext()) {
7698//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7699//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7700//                    retList.add(resolveInfo);
7701//                }
7702//            }
7703//            return retList;
7704//        }
7705
7706        // Keys are String (activity class name), values are Activity.
7707        private final ArrayMap<ComponentName, PackageParser.Service> mServices
7708                = new ArrayMap<ComponentName, PackageParser.Service>();
7709        private int mFlags;
7710    };
7711
7712    private final class ProviderIntentResolver
7713            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7714        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7715                boolean defaultOnly, int userId) {
7716            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7717            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7718        }
7719
7720        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7721                int userId) {
7722            if (!sUserManager.exists(userId))
7723                return null;
7724            mFlags = flags;
7725            return super.queryIntent(intent, resolvedType,
7726                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7727        }
7728
7729        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7730                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7731            if (!sUserManager.exists(userId))
7732                return null;
7733            if (packageProviders == null) {
7734                return null;
7735            }
7736            mFlags = flags;
7737            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7738            final int N = packageProviders.size();
7739            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7740                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7741
7742            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7743            for (int i = 0; i < N; ++i) {
7744                intentFilters = packageProviders.get(i).intents;
7745                if (intentFilters != null && intentFilters.size() > 0) {
7746                    PackageParser.ProviderIntentInfo[] array =
7747                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7748                    intentFilters.toArray(array);
7749                    listCut.add(array);
7750                }
7751            }
7752            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7753        }
7754
7755        public final void addProvider(PackageParser.Provider p) {
7756            if (mProviders.containsKey(p.getComponentName())) {
7757                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7758                return;
7759            }
7760
7761            mProviders.put(p.getComponentName(), p);
7762            if (DEBUG_SHOW_INFO) {
7763                Log.v(TAG, "  "
7764                        + (p.info.nonLocalizedLabel != null
7765                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7766                Log.v(TAG, "    Class=" + p.info.name);
7767            }
7768            final int NI = p.intents.size();
7769            int j;
7770            for (j = 0; j < NI; j++) {
7771                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7772                if (DEBUG_SHOW_INFO) {
7773                    Log.v(TAG, "    IntentFilter:");
7774                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7775                }
7776                if (!intent.debugCheck()) {
7777                    Log.w(TAG, "==> For Provider " + p.info.name);
7778                }
7779                addFilter(intent);
7780            }
7781        }
7782
7783        public final void removeProvider(PackageParser.Provider p) {
7784            mProviders.remove(p.getComponentName());
7785            if (DEBUG_SHOW_INFO) {
7786                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7787                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7788                Log.v(TAG, "    Class=" + p.info.name);
7789            }
7790            final int NI = p.intents.size();
7791            int j;
7792            for (j = 0; j < NI; j++) {
7793                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7794                if (DEBUG_SHOW_INFO) {
7795                    Log.v(TAG, "    IntentFilter:");
7796                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7797                }
7798                removeFilter(intent);
7799            }
7800        }
7801
7802        @Override
7803        protected boolean allowFilterResult(
7804                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7805            ProviderInfo filterPi = filter.provider.info;
7806            for (int i = dest.size() - 1; i >= 0; i--) {
7807                ProviderInfo destPi = dest.get(i).providerInfo;
7808                if (destPi.name == filterPi.name
7809                        && destPi.packageName == filterPi.packageName) {
7810                    return false;
7811                }
7812            }
7813            return true;
7814        }
7815
7816        @Override
7817        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7818            return new PackageParser.ProviderIntentInfo[size];
7819        }
7820
7821        @Override
7822        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7823            if (!sUserManager.exists(userId))
7824                return true;
7825            PackageParser.Package p = filter.provider.owner;
7826            if (p != null) {
7827                PackageSetting ps = (PackageSetting) p.mExtras;
7828                if (ps != null) {
7829                    // System apps are never considered stopped for purposes of
7830                    // filtering, because there may be no way for the user to
7831                    // actually re-launch them.
7832                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7833                            && ps.getStopped(userId);
7834                }
7835            }
7836            return false;
7837        }
7838
7839        @Override
7840        protected boolean isPackageForFilter(String packageName,
7841                PackageParser.ProviderIntentInfo info) {
7842            return packageName.equals(info.provider.owner.packageName);
7843        }
7844
7845        @Override
7846        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7847                int match, int userId) {
7848            if (!sUserManager.exists(userId))
7849                return null;
7850            final PackageParser.ProviderIntentInfo info = filter;
7851            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7852                return null;
7853            }
7854            final PackageParser.Provider provider = info.provider;
7855            if (mSafeMode && (provider.info.applicationInfo.flags
7856                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7857                return null;
7858            }
7859            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7860            if (ps == null) {
7861                return null;
7862            }
7863            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7864                    ps.readUserState(userId), userId);
7865            if (pi == null) {
7866                return null;
7867            }
7868            final ResolveInfo res = new ResolveInfo();
7869            res.providerInfo = pi;
7870            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7871                res.filter = filter;
7872            }
7873            res.priority = info.getPriority();
7874            res.preferredOrder = provider.owner.mPreferredOrder;
7875            res.match = match;
7876            res.isDefault = info.hasDefault;
7877            res.labelRes = info.labelRes;
7878            res.nonLocalizedLabel = info.nonLocalizedLabel;
7879            res.icon = info.icon;
7880            res.system = isSystemApp(res.providerInfo.applicationInfo);
7881            return res;
7882        }
7883
7884        @Override
7885        protected void sortResults(List<ResolveInfo> results) {
7886            Collections.sort(results, mResolvePrioritySorter);
7887        }
7888
7889        @Override
7890        protected void dumpFilter(PrintWriter out, String prefix,
7891                PackageParser.ProviderIntentInfo filter) {
7892            out.print(prefix);
7893            out.print(
7894                    Integer.toHexString(System.identityHashCode(filter.provider)));
7895            out.print(' ');
7896            filter.provider.printComponentShortName(out);
7897            out.print(" filter ");
7898            out.println(Integer.toHexString(System.identityHashCode(filter)));
7899        }
7900
7901        @Override
7902        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
7903            return filter.provider;
7904        }
7905
7906        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7907            PackageParser.Provider provider = (PackageParser.Provider)label;
7908            out.print(prefix); out.print(
7909                    Integer.toHexString(System.identityHashCode(provider)));
7910                    out.print(' ');
7911                    provider.printComponentShortName(out);
7912            if (count > 1) {
7913                out.print(" ("); out.print(count); out.print(" filters)");
7914            }
7915            out.println();
7916        }
7917
7918        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
7919                = new ArrayMap<ComponentName, PackageParser.Provider>();
7920        private int mFlags;
7921    };
7922
7923    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7924            new Comparator<ResolveInfo>() {
7925        public int compare(ResolveInfo r1, ResolveInfo r2) {
7926            int v1 = r1.priority;
7927            int v2 = r2.priority;
7928            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7929            if (v1 != v2) {
7930                return (v1 > v2) ? -1 : 1;
7931            }
7932            v1 = r1.preferredOrder;
7933            v2 = r2.preferredOrder;
7934            if (v1 != v2) {
7935                return (v1 > v2) ? -1 : 1;
7936            }
7937            if (r1.isDefault != r2.isDefault) {
7938                return r1.isDefault ? -1 : 1;
7939            }
7940            v1 = r1.match;
7941            v2 = r2.match;
7942            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7943            if (v1 != v2) {
7944                return (v1 > v2) ? -1 : 1;
7945            }
7946            if (r1.system != r2.system) {
7947                return r1.system ? -1 : 1;
7948            }
7949            return 0;
7950        }
7951    };
7952
7953    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7954            new Comparator<ProviderInfo>() {
7955        public int compare(ProviderInfo p1, ProviderInfo p2) {
7956            final int v1 = p1.initOrder;
7957            final int v2 = p2.initOrder;
7958            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7959        }
7960    };
7961
7962    static final void sendPackageBroadcast(String action, String pkg,
7963            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7964            int[] userIds) {
7965        IActivityManager am = ActivityManagerNative.getDefault();
7966        if (am != null) {
7967            try {
7968                if (userIds == null) {
7969                    userIds = am.getRunningUserIds();
7970                }
7971                for (int id : userIds) {
7972                    final Intent intent = new Intent(action,
7973                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7974                    if (extras != null) {
7975                        intent.putExtras(extras);
7976                    }
7977                    if (targetPkg != null) {
7978                        intent.setPackage(targetPkg);
7979                    }
7980                    // Modify the UID when posting to other users
7981                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7982                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7983                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7984                        intent.putExtra(Intent.EXTRA_UID, uid);
7985                    }
7986                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7987                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7988                    if (DEBUG_BROADCASTS) {
7989                        RuntimeException here = new RuntimeException("here");
7990                        here.fillInStackTrace();
7991                        Slog.d(TAG, "Sending to user " + id + ": "
7992                                + intent.toShortString(false, true, false, false)
7993                                + " " + intent.getExtras(), here);
7994                    }
7995                    am.broadcastIntent(null, intent, null, finishedReceiver,
7996                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7997                            finishedReceiver != null, false, id);
7998                }
7999            } catch (RemoteException ex) {
8000            }
8001        }
8002    }
8003
8004    /**
8005     * Check if the external storage media is available. This is true if there
8006     * is a mounted external storage medium or if the external storage is
8007     * emulated.
8008     */
8009    private boolean isExternalMediaAvailable() {
8010        return mMediaMounted || Environment.isExternalStorageEmulated();
8011    }
8012
8013    @Override
8014    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8015        // writer
8016        synchronized (mPackages) {
8017            if (!isExternalMediaAvailable()) {
8018                // If the external storage is no longer mounted at this point,
8019                // the caller may not have been able to delete all of this
8020                // packages files and can not delete any more.  Bail.
8021                return null;
8022            }
8023            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8024            if (lastPackage != null) {
8025                pkgs.remove(lastPackage);
8026            }
8027            if (pkgs.size() > 0) {
8028                return pkgs.get(0);
8029            }
8030        }
8031        return null;
8032    }
8033
8034    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8035        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8036                userId, andCode ? 1 : 0, packageName);
8037        if (mSystemReady) {
8038            msg.sendToTarget();
8039        } else {
8040            if (mPostSystemReadyMessages == null) {
8041                mPostSystemReadyMessages = new ArrayList<>();
8042            }
8043            mPostSystemReadyMessages.add(msg);
8044        }
8045    }
8046
8047    void startCleaningPackages() {
8048        // reader
8049        synchronized (mPackages) {
8050            if (!isExternalMediaAvailable()) {
8051                return;
8052            }
8053            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8054                return;
8055            }
8056        }
8057        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8058        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8059        IActivityManager am = ActivityManagerNative.getDefault();
8060        if (am != null) {
8061            try {
8062                am.startService(null, intent, null, UserHandle.USER_OWNER);
8063            } catch (RemoteException e) {
8064            }
8065        }
8066    }
8067
8068    @Override
8069    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8070            int installFlags, String installerPackageName, VerificationParams verificationParams,
8071            String packageAbiOverride) {
8072        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
8073                packageAbiOverride, UserHandle.getCallingUserId());
8074    }
8075
8076    @Override
8077    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8078            int installFlags, String installerPackageName, VerificationParams verificationParams,
8079            String packageAbiOverride, int userId) {
8080        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8081
8082        final int callingUid = Binder.getCallingUid();
8083        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8084
8085        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8086            try {
8087                if (observer != null) {
8088                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8089                }
8090            } catch (RemoteException re) {
8091            }
8092            return;
8093        }
8094
8095        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8096            installFlags |= PackageManager.INSTALL_FROM_ADB;
8097
8098        } else {
8099            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8100            // about installerPackageName.
8101
8102            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8103            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8104        }
8105
8106        UserHandle user;
8107        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8108            user = UserHandle.ALL;
8109        } else {
8110            user = new UserHandle(userId);
8111        }
8112
8113        verificationParams.setInstallerUid(callingUid);
8114
8115        final File originFile = new File(originPath);
8116        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8117
8118        final Message msg = mHandler.obtainMessage(INIT_COPY);
8119        msg.obj = new InstallParams(origin, observer, installFlags,
8120                installerPackageName, verificationParams, user, packageAbiOverride);
8121        mHandler.sendMessage(msg);
8122    }
8123
8124    void installStage(String packageName, File stagedDir, String stagedCid,
8125            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8126            String installerPackageName, int installerUid, UserHandle user) {
8127        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8128                params.referrerUri, installerUid, null);
8129
8130        final OriginInfo origin;
8131        if (stagedDir != null) {
8132            origin = OriginInfo.fromStagedFile(stagedDir);
8133        } else {
8134            origin = OriginInfo.fromStagedContainer(stagedCid);
8135        }
8136
8137        final Message msg = mHandler.obtainMessage(INIT_COPY);
8138        msg.obj = new InstallParams(origin, observer, params.installFlags,
8139                installerPackageName, verifParams, user, params.abiOverride);
8140        mHandler.sendMessage(msg);
8141    }
8142
8143    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8144        Bundle extras = new Bundle(1);
8145        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8146
8147        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8148                packageName, extras, null, null, new int[] {userId});
8149        try {
8150            IActivityManager am = ActivityManagerNative.getDefault();
8151            final boolean isSystem =
8152                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8153            if (isSystem && am.isUserRunning(userId, false)) {
8154                // The just-installed/enabled app is bundled on the system, so presumed
8155                // to be able to run automatically without needing an explicit launch.
8156                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8157                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8158                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8159                        .setPackage(packageName);
8160                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8161                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8162            }
8163        } catch (RemoteException e) {
8164            // shouldn't happen
8165            Slog.w(TAG, "Unable to bootstrap installed package", e);
8166        }
8167    }
8168
8169    @Override
8170    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8171            int userId) {
8172        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8173        PackageSetting pkgSetting;
8174        final int uid = Binder.getCallingUid();
8175        enforceCrossUserPermission(uid, userId, true, true,
8176                "setApplicationHiddenSetting for user " + userId);
8177
8178        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8179            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8180            return false;
8181        }
8182
8183        long callingId = Binder.clearCallingIdentity();
8184        try {
8185            boolean sendAdded = false;
8186            boolean sendRemoved = false;
8187            // writer
8188            synchronized (mPackages) {
8189                pkgSetting = mSettings.mPackages.get(packageName);
8190                if (pkgSetting == null) {
8191                    return false;
8192                }
8193                if (pkgSetting.getHidden(userId) != hidden) {
8194                    pkgSetting.setHidden(hidden, userId);
8195                    mSettings.writePackageRestrictionsLPr(userId);
8196                    if (hidden) {
8197                        sendRemoved = true;
8198                    } else {
8199                        sendAdded = true;
8200                    }
8201                }
8202            }
8203            if (sendAdded) {
8204                sendPackageAddedForUser(packageName, pkgSetting, userId);
8205                return true;
8206            }
8207            if (sendRemoved) {
8208                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8209                        "hiding pkg");
8210                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8211            }
8212        } finally {
8213            Binder.restoreCallingIdentity(callingId);
8214        }
8215        return false;
8216    }
8217
8218    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8219            int userId) {
8220        final PackageRemovedInfo info = new PackageRemovedInfo();
8221        info.removedPackage = packageName;
8222        info.removedUsers = new int[] {userId};
8223        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8224        info.sendBroadcast(false, false, false);
8225    }
8226
8227    /**
8228     * Returns true if application is not found or there was an error. Otherwise it returns
8229     * the hidden state of the package for the given user.
8230     */
8231    @Override
8232    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8233        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8234        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8235                false, "getApplicationHidden for user " + userId);
8236        PackageSetting pkgSetting;
8237        long callingId = Binder.clearCallingIdentity();
8238        try {
8239            // writer
8240            synchronized (mPackages) {
8241                pkgSetting = mSettings.mPackages.get(packageName);
8242                if (pkgSetting == null) {
8243                    return true;
8244                }
8245                return pkgSetting.getHidden(userId);
8246            }
8247        } finally {
8248            Binder.restoreCallingIdentity(callingId);
8249        }
8250    }
8251
8252    /**
8253     * @hide
8254     */
8255    @Override
8256    public int installExistingPackageAsUser(String packageName, int userId) {
8257        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8258                null);
8259        PackageSetting pkgSetting;
8260        final int uid = Binder.getCallingUid();
8261        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8262                + userId);
8263        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8264            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8265        }
8266
8267        long callingId = Binder.clearCallingIdentity();
8268        try {
8269            boolean sendAdded = false;
8270            Bundle extras = new Bundle(1);
8271
8272            // writer
8273            synchronized (mPackages) {
8274                pkgSetting = mSettings.mPackages.get(packageName);
8275                if (pkgSetting == null) {
8276                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8277                }
8278                if (!pkgSetting.getInstalled(userId)) {
8279                    pkgSetting.setInstalled(true, userId);
8280                    pkgSetting.setHidden(false, userId);
8281                    mSettings.writePackageRestrictionsLPr(userId);
8282                    sendAdded = true;
8283                }
8284            }
8285
8286            if (sendAdded) {
8287                sendPackageAddedForUser(packageName, pkgSetting, userId);
8288            }
8289        } finally {
8290            Binder.restoreCallingIdentity(callingId);
8291        }
8292
8293        return PackageManager.INSTALL_SUCCEEDED;
8294    }
8295
8296    boolean isUserRestricted(int userId, String restrictionKey) {
8297        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8298        if (restrictions.getBoolean(restrictionKey, false)) {
8299            Log.w(TAG, "User is restricted: " + restrictionKey);
8300            return true;
8301        }
8302        return false;
8303    }
8304
8305    @Override
8306    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8307        mContext.enforceCallingOrSelfPermission(
8308                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8309                "Only package verification agents can verify applications");
8310
8311        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8312        final PackageVerificationResponse response = new PackageVerificationResponse(
8313                verificationCode, Binder.getCallingUid());
8314        msg.arg1 = id;
8315        msg.obj = response;
8316        mHandler.sendMessage(msg);
8317    }
8318
8319    @Override
8320    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8321            long millisecondsToDelay) {
8322        mContext.enforceCallingOrSelfPermission(
8323                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8324                "Only package verification agents can extend verification timeouts");
8325
8326        final PackageVerificationState state = mPendingVerification.get(id);
8327        final PackageVerificationResponse response = new PackageVerificationResponse(
8328                verificationCodeAtTimeout, Binder.getCallingUid());
8329
8330        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8331            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8332        }
8333        if (millisecondsToDelay < 0) {
8334            millisecondsToDelay = 0;
8335        }
8336        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8337                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8338            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8339        }
8340
8341        if ((state != null) && !state.timeoutExtended()) {
8342            state.extendTimeout();
8343
8344            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8345            msg.arg1 = id;
8346            msg.obj = response;
8347            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8348        }
8349    }
8350
8351    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8352            int verificationCode, UserHandle user) {
8353        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8354        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8355        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8356        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8357        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8358
8359        mContext.sendBroadcastAsUser(intent, user,
8360                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8361    }
8362
8363    private ComponentName matchComponentForVerifier(String packageName,
8364            List<ResolveInfo> receivers) {
8365        ActivityInfo targetReceiver = null;
8366
8367        final int NR = receivers.size();
8368        for (int i = 0; i < NR; i++) {
8369            final ResolveInfo info = receivers.get(i);
8370            if (info.activityInfo == null) {
8371                continue;
8372            }
8373
8374            if (packageName.equals(info.activityInfo.packageName)) {
8375                targetReceiver = info.activityInfo;
8376                break;
8377            }
8378        }
8379
8380        if (targetReceiver == null) {
8381            return null;
8382        }
8383
8384        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8385    }
8386
8387    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8388            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8389        if (pkgInfo.verifiers.length == 0) {
8390            return null;
8391        }
8392
8393        final int N = pkgInfo.verifiers.length;
8394        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8395        for (int i = 0; i < N; i++) {
8396            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8397
8398            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8399                    receivers);
8400            if (comp == null) {
8401                continue;
8402            }
8403
8404            final int verifierUid = getUidForVerifier(verifierInfo);
8405            if (verifierUid == -1) {
8406                continue;
8407            }
8408
8409            if (DEBUG_VERIFY) {
8410                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8411                        + " with the correct signature");
8412            }
8413            sufficientVerifiers.add(comp);
8414            verificationState.addSufficientVerifier(verifierUid);
8415        }
8416
8417        return sufficientVerifiers;
8418    }
8419
8420    private int getUidForVerifier(VerifierInfo verifierInfo) {
8421        synchronized (mPackages) {
8422            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8423            if (pkg == null) {
8424                return -1;
8425            } else if (pkg.mSignatures.length != 1) {
8426                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8427                        + " has more than one signature; ignoring");
8428                return -1;
8429            }
8430
8431            /*
8432             * If the public key of the package's signature does not match
8433             * our expected public key, then this is a different package and
8434             * we should skip.
8435             */
8436
8437            final byte[] expectedPublicKey;
8438            try {
8439                final Signature verifierSig = pkg.mSignatures[0];
8440                final PublicKey publicKey = verifierSig.getPublicKey();
8441                expectedPublicKey = publicKey.getEncoded();
8442            } catch (CertificateException e) {
8443                return -1;
8444            }
8445
8446            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8447
8448            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8449                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8450                        + " does not have the expected public key; ignoring");
8451                return -1;
8452            }
8453
8454            return pkg.applicationInfo.uid;
8455        }
8456    }
8457
8458    @Override
8459    public void finishPackageInstall(int token) {
8460        enforceSystemOrRoot("Only the system is allowed to finish installs");
8461
8462        if (DEBUG_INSTALL) {
8463            Slog.v(TAG, "BM finishing package install for " + token);
8464        }
8465
8466        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8467        mHandler.sendMessage(msg);
8468    }
8469
8470    /**
8471     * Get the verification agent timeout.
8472     *
8473     * @return verification timeout in milliseconds
8474     */
8475    private long getVerificationTimeout() {
8476        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8477                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8478                DEFAULT_VERIFICATION_TIMEOUT);
8479    }
8480
8481    /**
8482     * Get the default verification agent response code.
8483     *
8484     * @return default verification response code
8485     */
8486    private int getDefaultVerificationResponse() {
8487        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8488                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8489                DEFAULT_VERIFICATION_RESPONSE);
8490    }
8491
8492    /**
8493     * Check whether or not package verification has been enabled.
8494     *
8495     * @return true if verification should be performed
8496     */
8497    private boolean isVerificationEnabled(int userId, int installFlags) {
8498        if (!DEFAULT_VERIFY_ENABLE) {
8499            return false;
8500        }
8501
8502        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8503
8504        // Check if installing from ADB
8505        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8506            // Do not run verification in a test harness environment
8507            if (ActivityManager.isRunningInTestHarness()) {
8508                return false;
8509            }
8510            if (ensureVerifyAppsEnabled) {
8511                return true;
8512            }
8513            // Check if the developer does not want package verification for ADB installs
8514            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8515                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8516                return false;
8517            }
8518        }
8519
8520        if (ensureVerifyAppsEnabled) {
8521            return true;
8522        }
8523
8524        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8525                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8526    }
8527
8528    /**
8529     * Get the "allow unknown sources" setting.
8530     *
8531     * @return the current "allow unknown sources" setting
8532     */
8533    private int getUnknownSourcesSettings() {
8534        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8535                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8536                -1);
8537    }
8538
8539    @Override
8540    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8541        final int uid = Binder.getCallingUid();
8542        // writer
8543        synchronized (mPackages) {
8544            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8545            if (targetPackageSetting == null) {
8546                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8547            }
8548
8549            PackageSetting installerPackageSetting;
8550            if (installerPackageName != null) {
8551                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8552                if (installerPackageSetting == null) {
8553                    throw new IllegalArgumentException("Unknown installer package: "
8554                            + installerPackageName);
8555                }
8556            } else {
8557                installerPackageSetting = null;
8558            }
8559
8560            Signature[] callerSignature;
8561            Object obj = mSettings.getUserIdLPr(uid);
8562            if (obj != null) {
8563                if (obj instanceof SharedUserSetting) {
8564                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8565                } else if (obj instanceof PackageSetting) {
8566                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8567                } else {
8568                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8569                }
8570            } else {
8571                throw new SecurityException("Unknown calling uid " + uid);
8572            }
8573
8574            // Verify: can't set installerPackageName to a package that is
8575            // not signed with the same cert as the caller.
8576            if (installerPackageSetting != null) {
8577                if (compareSignatures(callerSignature,
8578                        installerPackageSetting.signatures.mSignatures)
8579                        != PackageManager.SIGNATURE_MATCH) {
8580                    throw new SecurityException(
8581                            "Caller does not have same cert as new installer package "
8582                            + installerPackageName);
8583                }
8584            }
8585
8586            // Verify: if target already has an installer package, it must
8587            // be signed with the same cert as the caller.
8588            if (targetPackageSetting.installerPackageName != null) {
8589                PackageSetting setting = mSettings.mPackages.get(
8590                        targetPackageSetting.installerPackageName);
8591                // If the currently set package isn't valid, then it's always
8592                // okay to change it.
8593                if (setting != null) {
8594                    if (compareSignatures(callerSignature,
8595                            setting.signatures.mSignatures)
8596                            != PackageManager.SIGNATURE_MATCH) {
8597                        throw new SecurityException(
8598                                "Caller does not have same cert as old installer package "
8599                                + targetPackageSetting.installerPackageName);
8600                    }
8601                }
8602            }
8603
8604            // Okay!
8605            targetPackageSetting.installerPackageName = installerPackageName;
8606            scheduleWriteSettingsLocked();
8607        }
8608    }
8609
8610    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8611        // Queue up an async operation since the package installation may take a little while.
8612        mHandler.post(new Runnable() {
8613            public void run() {
8614                mHandler.removeCallbacks(this);
8615                 // Result object to be returned
8616                PackageInstalledInfo res = new PackageInstalledInfo();
8617                res.returnCode = currentStatus;
8618                res.uid = -1;
8619                res.pkg = null;
8620                res.removedInfo = new PackageRemovedInfo();
8621                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8622                    args.doPreInstall(res.returnCode);
8623                    synchronized (mInstallLock) {
8624                        installPackageLI(args, res);
8625                    }
8626                    args.doPostInstall(res.returnCode, res.uid);
8627                }
8628
8629                // A restore should be performed at this point if (a) the install
8630                // succeeded, (b) the operation is not an update, and (c) the new
8631                // package has not opted out of backup participation.
8632                final boolean update = res.removedInfo.removedPackage != null;
8633                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8634                boolean doRestore = !update
8635                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8636
8637                // Set up the post-install work request bookkeeping.  This will be used
8638                // and cleaned up by the post-install event handling regardless of whether
8639                // there's a restore pass performed.  Token values are >= 1.
8640                int token;
8641                if (mNextInstallToken < 0) mNextInstallToken = 1;
8642                token = mNextInstallToken++;
8643
8644                PostInstallData data = new PostInstallData(args, res);
8645                mRunningInstalls.put(token, data);
8646                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8647
8648                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8649                    // Pass responsibility to the Backup Manager.  It will perform a
8650                    // restore if appropriate, then pass responsibility back to the
8651                    // Package Manager to run the post-install observer callbacks
8652                    // and broadcasts.
8653                    IBackupManager bm = IBackupManager.Stub.asInterface(
8654                            ServiceManager.getService(Context.BACKUP_SERVICE));
8655                    if (bm != null) {
8656                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8657                                + " to BM for possible restore");
8658                        try {
8659                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
8660                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8661                            } else {
8662                                doRestore = false;
8663                            }
8664                        } catch (RemoteException e) {
8665                            // can't happen; the backup manager is local
8666                        } catch (Exception e) {
8667                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8668                            doRestore = false;
8669                        }
8670                    } else {
8671                        Slog.e(TAG, "Backup Manager not found!");
8672                        doRestore = false;
8673                    }
8674                }
8675
8676                if (!doRestore) {
8677                    // No restore possible, or the Backup Manager was mysteriously not
8678                    // available -- just fire the post-install work request directly.
8679                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8680                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8681                    mHandler.sendMessage(msg);
8682                }
8683            }
8684        });
8685    }
8686
8687    private abstract class HandlerParams {
8688        private static final int MAX_RETRIES = 4;
8689
8690        /**
8691         * Number of times startCopy() has been attempted and had a non-fatal
8692         * error.
8693         */
8694        private int mRetries = 0;
8695
8696        /** User handle for the user requesting the information or installation. */
8697        private final UserHandle mUser;
8698
8699        HandlerParams(UserHandle user) {
8700            mUser = user;
8701        }
8702
8703        UserHandle getUser() {
8704            return mUser;
8705        }
8706
8707        final boolean startCopy() {
8708            boolean res;
8709            try {
8710                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8711
8712                if (++mRetries > MAX_RETRIES) {
8713                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8714                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8715                    handleServiceError();
8716                    return false;
8717                } else {
8718                    handleStartCopy();
8719                    res = true;
8720                }
8721            } catch (RemoteException e) {
8722                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8723                mHandler.sendEmptyMessage(MCS_RECONNECT);
8724                res = false;
8725            }
8726            handleReturnCode();
8727            return res;
8728        }
8729
8730        final void serviceError() {
8731            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8732            handleServiceError();
8733            handleReturnCode();
8734        }
8735
8736        abstract void handleStartCopy() throws RemoteException;
8737        abstract void handleServiceError();
8738        abstract void handleReturnCode();
8739    }
8740
8741    class MeasureParams extends HandlerParams {
8742        private final PackageStats mStats;
8743        private boolean mSuccess;
8744
8745        private final IPackageStatsObserver mObserver;
8746
8747        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8748            super(new UserHandle(stats.userHandle));
8749            mObserver = observer;
8750            mStats = stats;
8751        }
8752
8753        @Override
8754        public String toString() {
8755            return "MeasureParams{"
8756                + Integer.toHexString(System.identityHashCode(this))
8757                + " " + mStats.packageName + "}";
8758        }
8759
8760        @Override
8761        void handleStartCopy() throws RemoteException {
8762            synchronized (mInstallLock) {
8763                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8764            }
8765
8766            if (mSuccess) {
8767                final boolean mounted;
8768                if (Environment.isExternalStorageEmulated()) {
8769                    mounted = true;
8770                } else {
8771                    final String status = Environment.getExternalStorageState();
8772                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8773                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8774                }
8775
8776                if (mounted) {
8777                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8778
8779                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8780                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8781
8782                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8783                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8784
8785                    // Always subtract cache size, since it's a subdirectory
8786                    mStats.externalDataSize -= mStats.externalCacheSize;
8787
8788                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8789                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8790
8791                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8792                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8793                }
8794            }
8795        }
8796
8797        @Override
8798        void handleReturnCode() {
8799            if (mObserver != null) {
8800                try {
8801                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8802                } catch (RemoteException e) {
8803                    Slog.i(TAG, "Observer no longer exists.");
8804                }
8805            }
8806        }
8807
8808        @Override
8809        void handleServiceError() {
8810            Slog.e(TAG, "Could not measure application " + mStats.packageName
8811                            + " external storage");
8812        }
8813    }
8814
8815    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8816            throws RemoteException {
8817        long result = 0;
8818        for (File path : paths) {
8819            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8820        }
8821        return result;
8822    }
8823
8824    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8825        for (File path : paths) {
8826            try {
8827                mcs.clearDirectory(path.getAbsolutePath());
8828            } catch (RemoteException e) {
8829            }
8830        }
8831    }
8832
8833    static class OriginInfo {
8834        /**
8835         * Location where install is coming from, before it has been
8836         * copied/renamed into place. This could be a single monolithic APK
8837         * file, or a cluster directory. This location may be untrusted.
8838         */
8839        final File file;
8840        final String cid;
8841
8842        /**
8843         * Flag indicating that {@link #file} or {@link #cid} has already been
8844         * staged, meaning downstream users don't need to defensively copy the
8845         * contents.
8846         */
8847        final boolean staged;
8848
8849        /**
8850         * Flag indicating that {@link #file} or {@link #cid} is an already
8851         * installed app that is being moved.
8852         */
8853        final boolean existing;
8854
8855        final String resolvedPath;
8856        final File resolvedFile;
8857
8858        static OriginInfo fromNothing() {
8859            return new OriginInfo(null, null, false, false);
8860        }
8861
8862        static OriginInfo fromUntrustedFile(File file) {
8863            return new OriginInfo(file, null, false, false);
8864        }
8865
8866        static OriginInfo fromExistingFile(File file) {
8867            return new OriginInfo(file, null, false, true);
8868        }
8869
8870        static OriginInfo fromStagedFile(File file) {
8871            return new OriginInfo(file, null, true, false);
8872        }
8873
8874        static OriginInfo fromStagedContainer(String cid) {
8875            return new OriginInfo(null, cid, true, false);
8876        }
8877
8878        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8879            this.file = file;
8880            this.cid = cid;
8881            this.staged = staged;
8882            this.existing = existing;
8883
8884            if (cid != null) {
8885                resolvedPath = PackageHelper.getSdDir(cid);
8886                resolvedFile = new File(resolvedPath);
8887            } else if (file != null) {
8888                resolvedPath = file.getAbsolutePath();
8889                resolvedFile = file;
8890            } else {
8891                resolvedPath = null;
8892                resolvedFile = null;
8893            }
8894        }
8895    }
8896
8897    class InstallParams extends HandlerParams {
8898        final OriginInfo origin;
8899        final IPackageInstallObserver2 observer;
8900        int installFlags;
8901        final String installerPackageName;
8902        final VerificationParams verificationParams;
8903        private InstallArgs mArgs;
8904        private int mRet;
8905        final String packageAbiOverride;
8906
8907        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8908                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8909                String packageAbiOverride) {
8910            super(user);
8911            this.origin = origin;
8912            this.observer = observer;
8913            this.installFlags = installFlags;
8914            this.installerPackageName = installerPackageName;
8915            this.verificationParams = verificationParams;
8916            this.packageAbiOverride = packageAbiOverride;
8917        }
8918
8919        @Override
8920        public String toString() {
8921            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8922                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8923        }
8924
8925        public ManifestDigest getManifestDigest() {
8926            if (verificationParams == null) {
8927                return null;
8928            }
8929            return verificationParams.getManifestDigest();
8930        }
8931
8932        private int installLocationPolicy(PackageInfoLite pkgLite) {
8933            String packageName = pkgLite.packageName;
8934            int installLocation = pkgLite.installLocation;
8935            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8936            // reader
8937            synchronized (mPackages) {
8938                PackageParser.Package pkg = mPackages.get(packageName);
8939                if (pkg != null) {
8940                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8941                        // Check for downgrading.
8942                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8943                            try {
8944                                checkDowngrade(pkg, pkgLite);
8945                            } catch (PackageManagerException e) {
8946                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
8947                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8948                            }
8949                        }
8950                        // Check for updated system application.
8951                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8952                            if (onSd) {
8953                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8954                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8955                            }
8956                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8957                        } else {
8958                            if (onSd) {
8959                                // Install flag overrides everything.
8960                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8961                            }
8962                            // If current upgrade specifies particular preference
8963                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8964                                // Application explicitly specified internal.
8965                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8966                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8967                                // App explictly prefers external. Let policy decide
8968                            } else {
8969                                // Prefer previous location
8970                                if (isExternal(pkg)) {
8971                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8972                                }
8973                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8974                            }
8975                        }
8976                    } else {
8977                        // Invalid install. Return error code
8978                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8979                    }
8980                }
8981            }
8982            // All the special cases have been taken care of.
8983            // Return result based on recommended install location.
8984            if (onSd) {
8985                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8986            }
8987            return pkgLite.recommendedInstallLocation;
8988        }
8989
8990        /*
8991         * Invoke remote method to get package information and install
8992         * location values. Override install location based on default
8993         * policy if needed and then create install arguments based
8994         * on the install location.
8995         */
8996        public void handleStartCopy() throws RemoteException {
8997            int ret = PackageManager.INSTALL_SUCCEEDED;
8998
8999            // If we're already staged, we've firmly committed to an install location
9000            if (origin.staged) {
9001                if (origin.file != null) {
9002                    installFlags |= PackageManager.INSTALL_INTERNAL;
9003                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9004                } else if (origin.cid != null) {
9005                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9006                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9007                } else {
9008                    throw new IllegalStateException("Invalid stage location");
9009                }
9010            }
9011
9012            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9013            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9014
9015            PackageInfoLite pkgLite = null;
9016
9017            if (onInt && onSd) {
9018                // Check if both bits are set.
9019                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9020                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9021            } else {
9022                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9023                        packageAbiOverride);
9024
9025                /*
9026                 * If we have too little free space, try to free cache
9027                 * before giving up.
9028                 */
9029                if (!origin.staged && pkgLite.recommendedInstallLocation
9030                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9031                    // TODO: focus freeing disk space on the target device
9032                    final StorageManager storage = StorageManager.from(mContext);
9033                    final long lowThreshold = storage.getStorageLowBytes(
9034                            Environment.getDataDirectory());
9035
9036                    final long sizeBytes = mContainerService.calculateInstalledSize(
9037                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9038
9039                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
9040                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9041                                installFlags, packageAbiOverride);
9042                    }
9043
9044                    /*
9045                     * The cache free must have deleted the file we
9046                     * downloaded to install.
9047                     *
9048                     * TODO: fix the "freeCache" call to not delete
9049                     *       the file we care about.
9050                     */
9051                    if (pkgLite.recommendedInstallLocation
9052                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9053                        pkgLite.recommendedInstallLocation
9054                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9055                    }
9056                }
9057            }
9058
9059            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9060                int loc = pkgLite.recommendedInstallLocation;
9061                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9062                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9063                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9064                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9065                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9066                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9067                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9068                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9069                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9070                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9071                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9072                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9073                } else {
9074                    // Override with defaults if needed.
9075                    loc = installLocationPolicy(pkgLite);
9076                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9077                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9078                    } else if (!onSd && !onInt) {
9079                        // Override install location with flags
9080                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9081                            // Set the flag to install on external media.
9082                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9083                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9084                        } else {
9085                            // Make sure the flag for installing on external
9086                            // media is unset
9087                            installFlags |= PackageManager.INSTALL_INTERNAL;
9088                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9089                        }
9090                    }
9091                }
9092            }
9093
9094            final InstallArgs args = createInstallArgs(this);
9095            mArgs = args;
9096
9097            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9098                 /*
9099                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9100                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9101                 */
9102                int userIdentifier = getUser().getIdentifier();
9103                if (userIdentifier == UserHandle.USER_ALL
9104                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9105                    userIdentifier = UserHandle.USER_OWNER;
9106                }
9107
9108                /*
9109                 * Determine if we have any installed package verifiers. If we
9110                 * do, then we'll defer to them to verify the packages.
9111                 */
9112                final int requiredUid = mRequiredVerifierPackage == null ? -1
9113                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9114                if (!origin.existing && requiredUid != -1
9115                        && isVerificationEnabled(userIdentifier, installFlags)) {
9116                    final Intent verification = new Intent(
9117                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9118                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9119                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9120                            PACKAGE_MIME_TYPE);
9121                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9122
9123                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9124                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9125                            0 /* TODO: Which userId? */);
9126
9127                    if (DEBUG_VERIFY) {
9128                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9129                                + verification.toString() + " with " + pkgLite.verifiers.length
9130                                + " optional verifiers");
9131                    }
9132
9133                    final int verificationId = mPendingVerificationToken++;
9134
9135                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9136
9137                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9138                            installerPackageName);
9139
9140                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9141                            installFlags);
9142
9143                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9144                            pkgLite.packageName);
9145
9146                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9147                            pkgLite.versionCode);
9148
9149                    if (verificationParams != null) {
9150                        if (verificationParams.getVerificationURI() != null) {
9151                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9152                                 verificationParams.getVerificationURI());
9153                        }
9154                        if (verificationParams.getOriginatingURI() != null) {
9155                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9156                                  verificationParams.getOriginatingURI());
9157                        }
9158                        if (verificationParams.getReferrer() != null) {
9159                            verification.putExtra(Intent.EXTRA_REFERRER,
9160                                  verificationParams.getReferrer());
9161                        }
9162                        if (verificationParams.getOriginatingUid() >= 0) {
9163                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9164                                  verificationParams.getOriginatingUid());
9165                        }
9166                        if (verificationParams.getInstallerUid() >= 0) {
9167                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9168                                  verificationParams.getInstallerUid());
9169                        }
9170                    }
9171
9172                    final PackageVerificationState verificationState = new PackageVerificationState(
9173                            requiredUid, args);
9174
9175                    mPendingVerification.append(verificationId, verificationState);
9176
9177                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9178                            receivers, verificationState);
9179
9180                    /*
9181                     * If any sufficient verifiers were listed in the package
9182                     * manifest, attempt to ask them.
9183                     */
9184                    if (sufficientVerifiers != null) {
9185                        final int N = sufficientVerifiers.size();
9186                        if (N == 0) {
9187                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9188                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9189                        } else {
9190                            for (int i = 0; i < N; i++) {
9191                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9192
9193                                final Intent sufficientIntent = new Intent(verification);
9194                                sufficientIntent.setComponent(verifierComponent);
9195
9196                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9197                            }
9198                        }
9199                    }
9200
9201                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9202                            mRequiredVerifierPackage, receivers);
9203                    if (ret == PackageManager.INSTALL_SUCCEEDED
9204                            && mRequiredVerifierPackage != null) {
9205                        /*
9206                         * Send the intent to the required verification agent,
9207                         * but only start the verification timeout after the
9208                         * target BroadcastReceivers have run.
9209                         */
9210                        verification.setComponent(requiredVerifierComponent);
9211                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9212                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9213                                new BroadcastReceiver() {
9214                                    @Override
9215                                    public void onReceive(Context context, Intent intent) {
9216                                        final Message msg = mHandler
9217                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9218                                        msg.arg1 = verificationId;
9219                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9220                                    }
9221                                }, null, 0, null, null);
9222
9223                        /*
9224                         * We don't want the copy to proceed until verification
9225                         * succeeds, so null out this field.
9226                         */
9227                        mArgs = null;
9228                    }
9229                } else {
9230                    /*
9231                     * No package verification is enabled, so immediately start
9232                     * the remote call to initiate copy using temporary file.
9233                     */
9234                    ret = args.copyApk(mContainerService, true);
9235                }
9236            }
9237
9238            mRet = ret;
9239        }
9240
9241        @Override
9242        void handleReturnCode() {
9243            // If mArgs is null, then MCS couldn't be reached. When it
9244            // reconnects, it will try again to install. At that point, this
9245            // will succeed.
9246            if (mArgs != null) {
9247                processPendingInstall(mArgs, mRet);
9248            }
9249        }
9250
9251        @Override
9252        void handleServiceError() {
9253            mArgs = createInstallArgs(this);
9254            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9255        }
9256
9257        public boolean isForwardLocked() {
9258            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9259        }
9260    }
9261
9262    /**
9263     * Used during creation of InstallArgs
9264     *
9265     * @param installFlags package installation flags
9266     * @return true if should be installed on external storage
9267     */
9268    private static boolean installOnSd(int installFlags) {
9269        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9270            return false;
9271        }
9272        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9273            return true;
9274        }
9275        return false;
9276    }
9277
9278    /**
9279     * Used during creation of InstallArgs
9280     *
9281     * @param installFlags package installation flags
9282     * @return true if should be installed as forward locked
9283     */
9284    private static boolean installForwardLocked(int installFlags) {
9285        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9286    }
9287
9288    private InstallArgs createInstallArgs(InstallParams params) {
9289        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
9290            return new AsecInstallArgs(params);
9291        } else {
9292            return new FileInstallArgs(params);
9293        }
9294    }
9295
9296    /**
9297     * Create args that describe an existing installed package. Typically used
9298     * when cleaning up old installs, or used as a move source.
9299     */
9300    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9301            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9302        final boolean isInAsec;
9303        if (installOnSd(installFlags)) {
9304            /* Apps on SD card are always in ASEC containers. */
9305            isInAsec = true;
9306        } else if (installForwardLocked(installFlags)
9307                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9308            /*
9309             * Forward-locked apps are only in ASEC containers if they're the
9310             * new style
9311             */
9312            isInAsec = true;
9313        } else {
9314            isInAsec = false;
9315        }
9316
9317        if (isInAsec) {
9318            return new AsecInstallArgs(codePath, instructionSets,
9319                    installOnSd(installFlags), installForwardLocked(installFlags));
9320        } else {
9321            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9322                    instructionSets);
9323        }
9324    }
9325
9326    static abstract class InstallArgs {
9327        /** @see InstallParams#origin */
9328        final OriginInfo origin;
9329
9330        final IPackageInstallObserver2 observer;
9331        // Always refers to PackageManager flags only
9332        final int installFlags;
9333        final String installerPackageName;
9334        final ManifestDigest manifestDigest;
9335        final UserHandle user;
9336        final String abiOverride;
9337
9338        // The list of instruction sets supported by this app. This is currently
9339        // only used during the rmdex() phase to clean up resources. We can get rid of this
9340        // if we move dex files under the common app path.
9341        /* nullable */ String[] instructionSets;
9342
9343        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9344                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9345                String[] instructionSets, String abiOverride) {
9346            this.origin = origin;
9347            this.installFlags = installFlags;
9348            this.observer = observer;
9349            this.installerPackageName = installerPackageName;
9350            this.manifestDigest = manifestDigest;
9351            this.user = user;
9352            this.instructionSets = instructionSets;
9353            this.abiOverride = abiOverride;
9354        }
9355
9356        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9357        abstract int doPreInstall(int status);
9358
9359        /**
9360         * Rename package into final resting place. All paths on the given
9361         * scanned package should be updated to reflect the rename.
9362         */
9363        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9364        abstract int doPostInstall(int status, int uid);
9365
9366        /** @see PackageSettingBase#codePathString */
9367        abstract String getCodePath();
9368        /** @see PackageSettingBase#resourcePathString */
9369        abstract String getResourcePath();
9370        abstract String getLegacyNativeLibraryPath();
9371
9372        // Need installer lock especially for dex file removal.
9373        abstract void cleanUpResourcesLI();
9374        abstract boolean doPostDeleteLI(boolean delete);
9375        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9376
9377        /**
9378         * Called before the source arguments are copied. This is used mostly
9379         * for MoveParams when it needs to read the source file to put it in the
9380         * destination.
9381         */
9382        int doPreCopy() {
9383            return PackageManager.INSTALL_SUCCEEDED;
9384        }
9385
9386        /**
9387         * Called after the source arguments are copied. This is used mostly for
9388         * MoveParams when it needs to read the source file to put it in the
9389         * destination.
9390         *
9391         * @return
9392         */
9393        int doPostCopy(int uid) {
9394            return PackageManager.INSTALL_SUCCEEDED;
9395        }
9396
9397        protected boolean isFwdLocked() {
9398            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9399        }
9400
9401        protected boolean isExternal() {
9402            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9403        }
9404
9405        UserHandle getUser() {
9406            return user;
9407        }
9408    }
9409
9410    /**
9411     * Logic to handle installation of non-ASEC applications, including copying
9412     * and renaming logic.
9413     */
9414    class FileInstallArgs extends InstallArgs {
9415        private File codeFile;
9416        private File resourceFile;
9417        private File legacyNativeLibraryPath;
9418
9419        // Example topology:
9420        // /data/app/com.example/base.apk
9421        // /data/app/com.example/split_foo.apk
9422        // /data/app/com.example/lib/arm/libfoo.so
9423        // /data/app/com.example/lib/arm64/libfoo.so
9424        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9425
9426        /** New install */
9427        FileInstallArgs(InstallParams params) {
9428            super(params.origin, params.observer, params.installFlags,
9429                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9430                    null /* instruction sets */, params.packageAbiOverride);
9431            if (isFwdLocked()) {
9432                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9433            }
9434        }
9435
9436        /** Existing install */
9437        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9438                String[] instructionSets) {
9439            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9440            this.codeFile = (codePath != null) ? new File(codePath) : null;
9441            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9442            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9443                    new File(legacyNativeLibraryPath) : null;
9444        }
9445
9446        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9447            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9448                    isFwdLocked(), abiOverride);
9449
9450            final StorageManager storage = StorageManager.from(mContext);
9451            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9452        }
9453
9454        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9455            if (origin.staged) {
9456                Slog.d(TAG, origin.file + " already staged; skipping copy");
9457                codeFile = origin.file;
9458                resourceFile = origin.file;
9459                return PackageManager.INSTALL_SUCCEEDED;
9460            }
9461
9462            try {
9463                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9464                codeFile = tempDir;
9465                resourceFile = tempDir;
9466            } catch (IOException e) {
9467                Slog.w(TAG, "Failed to create copy file: " + e);
9468                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9469            }
9470
9471            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9472                @Override
9473                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9474                    if (!FileUtils.isValidExtFilename(name)) {
9475                        throw new IllegalArgumentException("Invalid filename: " + name);
9476                    }
9477                    try {
9478                        final File file = new File(codeFile, name);
9479                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9480                                O_RDWR | O_CREAT, 0644);
9481                        Os.chmod(file.getAbsolutePath(), 0644);
9482                        return new ParcelFileDescriptor(fd);
9483                    } catch (ErrnoException e) {
9484                        throw new RemoteException("Failed to open: " + e.getMessage());
9485                    }
9486                }
9487            };
9488
9489            int ret = PackageManager.INSTALL_SUCCEEDED;
9490            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9491            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9492                Slog.e(TAG, "Failed to copy package");
9493                return ret;
9494            }
9495
9496            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9497            NativeLibraryHelper.Handle handle = null;
9498            try {
9499                handle = NativeLibraryHelper.Handle.create(codeFile);
9500                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9501                        abiOverride);
9502            } catch (IOException e) {
9503                Slog.e(TAG, "Copying native libraries failed", e);
9504                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9505            } finally {
9506                IoUtils.closeQuietly(handle);
9507            }
9508
9509            return ret;
9510        }
9511
9512        int doPreInstall(int status) {
9513            if (status != PackageManager.INSTALL_SUCCEEDED) {
9514                cleanUp();
9515            }
9516            return status;
9517        }
9518
9519        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9520            if (status != PackageManager.INSTALL_SUCCEEDED) {
9521                cleanUp();
9522                return false;
9523            } else {
9524                final File beforeCodeFile = codeFile;
9525                final File afterCodeFile = getNextCodePath(pkg.packageName);
9526
9527                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9528                try {
9529                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9530                } catch (ErrnoException e) {
9531                    Slog.d(TAG, "Failed to rename", e);
9532                    return false;
9533                }
9534
9535                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9536                    Slog.d(TAG, "Failed to restorecon");
9537                    return false;
9538                }
9539
9540                // Reflect the rename internally
9541                codeFile = afterCodeFile;
9542                resourceFile = afterCodeFile;
9543
9544                // Reflect the rename in scanned details
9545                pkg.codePath = afterCodeFile.getAbsolutePath();
9546                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9547                        pkg.baseCodePath);
9548                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9549                        pkg.splitCodePaths);
9550
9551                // Reflect the rename in app info
9552                pkg.applicationInfo.setCodePath(pkg.codePath);
9553                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9554                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9555                pkg.applicationInfo.setResourcePath(pkg.codePath);
9556                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9557                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9558
9559                return true;
9560            }
9561        }
9562
9563        int doPostInstall(int status, int uid) {
9564            if (status != PackageManager.INSTALL_SUCCEEDED) {
9565                cleanUp();
9566            }
9567            return status;
9568        }
9569
9570        @Override
9571        String getCodePath() {
9572            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9573        }
9574
9575        @Override
9576        String getResourcePath() {
9577            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9578        }
9579
9580        @Override
9581        String getLegacyNativeLibraryPath() {
9582            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9583        }
9584
9585        private boolean cleanUp() {
9586            if (codeFile == null || !codeFile.exists()) {
9587                return false;
9588            }
9589
9590            if (codeFile.isDirectory()) {
9591                FileUtils.deleteContents(codeFile);
9592            }
9593            codeFile.delete();
9594
9595            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9596                resourceFile.delete();
9597            }
9598
9599            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9600                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9601                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9602                }
9603                legacyNativeLibraryPath.delete();
9604            }
9605
9606            return true;
9607        }
9608
9609        void cleanUpResourcesLI() {
9610            // Try enumerating all code paths before deleting
9611            List<String> allCodePaths = Collections.EMPTY_LIST;
9612            if (codeFile != null && codeFile.exists()) {
9613                try {
9614                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9615                    allCodePaths = pkg.getAllCodePaths();
9616                } catch (PackageParserException e) {
9617                    // Ignored; we tried our best
9618                }
9619            }
9620
9621            cleanUp();
9622
9623            if (!allCodePaths.isEmpty()) {
9624                if (instructionSets == null) {
9625                    throw new IllegalStateException("instructionSet == null");
9626                }
9627                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9628                for (String codePath : allCodePaths) {
9629                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9630                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9631                        if (retCode < 0) {
9632                            Slog.w(TAG, "Couldn't remove dex file for package: "
9633                                    + " at location " + codePath + ", retcode=" + retCode);
9634                            // we don't consider this to be a failure of the core package deletion
9635                        }
9636                    }
9637                }
9638            }
9639        }
9640
9641        boolean doPostDeleteLI(boolean delete) {
9642            // XXX err, shouldn't we respect the delete flag?
9643            cleanUpResourcesLI();
9644            return true;
9645        }
9646    }
9647
9648    private boolean isAsecExternal(String cid) {
9649        final String asecPath = PackageHelper.getSdFilesystem(cid);
9650        return !asecPath.startsWith(mAsecInternalPath);
9651    }
9652
9653    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9654            PackageManagerException {
9655        if (copyRet < 0) {
9656            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9657                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9658                throw new PackageManagerException(copyRet, message);
9659            }
9660        }
9661    }
9662
9663    /**
9664     * Extract the MountService "container ID" from the full code path of an
9665     * .apk.
9666     */
9667    static String cidFromCodePath(String fullCodePath) {
9668        int eidx = fullCodePath.lastIndexOf("/");
9669        String subStr1 = fullCodePath.substring(0, eidx);
9670        int sidx = subStr1.lastIndexOf("/");
9671        return subStr1.substring(sidx+1, eidx);
9672    }
9673
9674    /**
9675     * Logic to handle installation of ASEC applications, including copying and
9676     * renaming logic.
9677     */
9678    class AsecInstallArgs extends InstallArgs {
9679        static final String RES_FILE_NAME = "pkg.apk";
9680        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9681
9682        String cid;
9683        String packagePath;
9684        String resourcePath;
9685        String legacyNativeLibraryDir;
9686
9687        /** New install */
9688        AsecInstallArgs(InstallParams params) {
9689            super(params.origin, params.observer, params.installFlags,
9690                    params.installerPackageName, params.getManifestDigest(),
9691                    params.getUser(), null /* instruction sets */,
9692                    params.packageAbiOverride);
9693        }
9694
9695        /** Existing install */
9696        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9697                        boolean isExternal, boolean isForwardLocked) {
9698            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9699                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9700                    instructionSets, null);
9701            // Hackily pretend we're still looking at a full code path
9702            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9703                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9704            }
9705
9706            // Extract cid from fullCodePath
9707            int eidx = fullCodePath.lastIndexOf("/");
9708            String subStr1 = fullCodePath.substring(0, eidx);
9709            int sidx = subStr1.lastIndexOf("/");
9710            cid = subStr1.substring(sidx+1, eidx);
9711            setMountPath(subStr1);
9712        }
9713
9714        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9715            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9716                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9717                    instructionSets, null);
9718            this.cid = cid;
9719            setMountPath(PackageHelper.getSdDir(cid));
9720        }
9721
9722        void createCopyFile() {
9723            cid = mInstallerService.allocateExternalStageCidLegacy();
9724        }
9725
9726        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9727            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9728                    abiOverride);
9729
9730            final File target;
9731            if (isExternal()) {
9732                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9733            } else {
9734                target = Environment.getDataDirectory();
9735            }
9736
9737            final StorageManager storage = StorageManager.from(mContext);
9738            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9739        }
9740
9741        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9742            if (origin.staged) {
9743                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9744                cid = origin.cid;
9745                setMountPath(PackageHelper.getSdDir(cid));
9746                return PackageManager.INSTALL_SUCCEEDED;
9747            }
9748
9749            if (temp) {
9750                createCopyFile();
9751            } else {
9752                /*
9753                 * Pre-emptively destroy the container since it's destroyed if
9754                 * copying fails due to it existing anyway.
9755                 */
9756                PackageHelper.destroySdDir(cid);
9757            }
9758
9759            final String newMountPath = imcs.copyPackageToContainer(
9760                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9761                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9762
9763            if (newMountPath != null) {
9764                setMountPath(newMountPath);
9765                return PackageManager.INSTALL_SUCCEEDED;
9766            } else {
9767                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9768            }
9769        }
9770
9771        @Override
9772        String getCodePath() {
9773            return packagePath;
9774        }
9775
9776        @Override
9777        String getResourcePath() {
9778            return resourcePath;
9779        }
9780
9781        @Override
9782        String getLegacyNativeLibraryPath() {
9783            return legacyNativeLibraryDir;
9784        }
9785
9786        int doPreInstall(int status) {
9787            if (status != PackageManager.INSTALL_SUCCEEDED) {
9788                // Destroy container
9789                PackageHelper.destroySdDir(cid);
9790            } else {
9791                boolean mounted = PackageHelper.isContainerMounted(cid);
9792                if (!mounted) {
9793                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9794                            Process.SYSTEM_UID);
9795                    if (newMountPath != null) {
9796                        setMountPath(newMountPath);
9797                    } else {
9798                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9799                    }
9800                }
9801            }
9802            return status;
9803        }
9804
9805        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9806            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9807            String newMountPath = null;
9808            if (PackageHelper.isContainerMounted(cid)) {
9809                // Unmount the container
9810                if (!PackageHelper.unMountSdDir(cid)) {
9811                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9812                    return false;
9813                }
9814            }
9815            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9816                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9817                        " which might be stale. Will try to clean up.");
9818                // Clean up the stale container and proceed to recreate.
9819                if (!PackageHelper.destroySdDir(newCacheId)) {
9820                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9821                    return false;
9822                }
9823                // Successfully cleaned up stale container. Try to rename again.
9824                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9825                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9826                            + " inspite of cleaning it up.");
9827                    return false;
9828                }
9829            }
9830            if (!PackageHelper.isContainerMounted(newCacheId)) {
9831                Slog.w(TAG, "Mounting container " + newCacheId);
9832                newMountPath = PackageHelper.mountSdDir(newCacheId,
9833                        getEncryptKey(), Process.SYSTEM_UID);
9834            } else {
9835                newMountPath = PackageHelper.getSdDir(newCacheId);
9836            }
9837            if (newMountPath == null) {
9838                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9839                return false;
9840            }
9841            Log.i(TAG, "Succesfully renamed " + cid +
9842                    " to " + newCacheId +
9843                    " at new path: " + newMountPath);
9844            cid = newCacheId;
9845
9846            final File beforeCodeFile = new File(packagePath);
9847            setMountPath(newMountPath);
9848            final File afterCodeFile = new File(packagePath);
9849
9850            // Reflect the rename in scanned details
9851            pkg.codePath = afterCodeFile.getAbsolutePath();
9852            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9853                    pkg.baseCodePath);
9854            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9855                    pkg.splitCodePaths);
9856
9857            // Reflect the rename in app info
9858            pkg.applicationInfo.setCodePath(pkg.codePath);
9859            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9860            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9861            pkg.applicationInfo.setResourcePath(pkg.codePath);
9862            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9863            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9864
9865            return true;
9866        }
9867
9868        private void setMountPath(String mountPath) {
9869            final File mountFile = new File(mountPath);
9870
9871            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9872            if (monolithicFile.exists()) {
9873                packagePath = monolithicFile.getAbsolutePath();
9874                if (isFwdLocked()) {
9875                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9876                } else {
9877                    resourcePath = packagePath;
9878                }
9879            } else {
9880                packagePath = mountFile.getAbsolutePath();
9881                resourcePath = packagePath;
9882            }
9883
9884            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9885        }
9886
9887        int doPostInstall(int status, int uid) {
9888            if (status != PackageManager.INSTALL_SUCCEEDED) {
9889                cleanUp();
9890            } else {
9891                final int groupOwner;
9892                final String protectedFile;
9893                if (isFwdLocked()) {
9894                    groupOwner = UserHandle.getSharedAppGid(uid);
9895                    protectedFile = RES_FILE_NAME;
9896                } else {
9897                    groupOwner = -1;
9898                    protectedFile = null;
9899                }
9900
9901                if (uid < Process.FIRST_APPLICATION_UID
9902                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9903                    Slog.e(TAG, "Failed to finalize " + cid);
9904                    PackageHelper.destroySdDir(cid);
9905                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9906                }
9907
9908                boolean mounted = PackageHelper.isContainerMounted(cid);
9909                if (!mounted) {
9910                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9911                }
9912            }
9913            return status;
9914        }
9915
9916        private void cleanUp() {
9917            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9918
9919            // Destroy secure container
9920            PackageHelper.destroySdDir(cid);
9921        }
9922
9923        private List<String> getAllCodePaths() {
9924            final File codeFile = new File(getCodePath());
9925            if (codeFile != null && codeFile.exists()) {
9926                try {
9927                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9928                    return pkg.getAllCodePaths();
9929                } catch (PackageParserException e) {
9930                    // Ignored; we tried our best
9931                }
9932            }
9933            return Collections.EMPTY_LIST;
9934        }
9935
9936        void cleanUpResourcesLI() {
9937            // Enumerate all code paths before deleting
9938            cleanUpResourcesLI(getAllCodePaths());
9939        }
9940
9941        private void cleanUpResourcesLI(List<String> allCodePaths) {
9942            cleanUp();
9943
9944            if (!allCodePaths.isEmpty()) {
9945                if (instructionSets == null) {
9946                    throw new IllegalStateException("instructionSet == null");
9947                }
9948                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9949                for (String codePath : allCodePaths) {
9950                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9951                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9952                        if (retCode < 0) {
9953                            Slog.w(TAG, "Couldn't remove dex file for package: "
9954                                    + " at location " + codePath + ", retcode=" + retCode);
9955                            // we don't consider this to be a failure of the core package deletion
9956                        }
9957                    }
9958                }
9959            }
9960        }
9961
9962        boolean matchContainer(String app) {
9963            if (cid.startsWith(app)) {
9964                return true;
9965            }
9966            return false;
9967        }
9968
9969        String getPackageName() {
9970            return getAsecPackageName(cid);
9971        }
9972
9973        boolean doPostDeleteLI(boolean delete) {
9974            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9975            final List<String> allCodePaths = getAllCodePaths();
9976            boolean mounted = PackageHelper.isContainerMounted(cid);
9977            if (mounted) {
9978                // Unmount first
9979                if (PackageHelper.unMountSdDir(cid)) {
9980                    mounted = false;
9981                }
9982            }
9983            if (!mounted && delete) {
9984                cleanUpResourcesLI(allCodePaths);
9985            }
9986            return !mounted;
9987        }
9988
9989        @Override
9990        int doPreCopy() {
9991            if (isFwdLocked()) {
9992                if (!PackageHelper.fixSdPermissions(cid,
9993                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9994                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9995                }
9996            }
9997
9998            return PackageManager.INSTALL_SUCCEEDED;
9999        }
10000
10001        @Override
10002        int doPostCopy(int uid) {
10003            if (isFwdLocked()) {
10004                if (uid < Process.FIRST_APPLICATION_UID
10005                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10006                                RES_FILE_NAME)) {
10007                    Slog.e(TAG, "Failed to finalize " + cid);
10008                    PackageHelper.destroySdDir(cid);
10009                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10010                }
10011            }
10012
10013            return PackageManager.INSTALL_SUCCEEDED;
10014        }
10015    }
10016
10017    static String getAsecPackageName(String packageCid) {
10018        int idx = packageCid.lastIndexOf("-");
10019        if (idx == -1) {
10020            return packageCid;
10021        }
10022        return packageCid.substring(0, idx);
10023    }
10024
10025    // Utility method used to create code paths based on package name and available index.
10026    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
10027        String idxStr = "";
10028        int idx = 1;
10029        // Fall back to default value of idx=1 if prefix is not
10030        // part of oldCodePath
10031        if (oldCodePath != null) {
10032            String subStr = oldCodePath;
10033            // Drop the suffix right away
10034            if (suffix != null && subStr.endsWith(suffix)) {
10035                subStr = subStr.substring(0, subStr.length() - suffix.length());
10036            }
10037            // If oldCodePath already contains prefix find out the
10038            // ending index to either increment or decrement.
10039            int sidx = subStr.lastIndexOf(prefix);
10040            if (sidx != -1) {
10041                subStr = subStr.substring(sidx + prefix.length());
10042                if (subStr != null) {
10043                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10044                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10045                    }
10046                    try {
10047                        idx = Integer.parseInt(subStr);
10048                        if (idx <= 1) {
10049                            idx++;
10050                        } else {
10051                            idx--;
10052                        }
10053                    } catch(NumberFormatException e) {
10054                    }
10055                }
10056            }
10057        }
10058        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10059        return prefix + idxStr;
10060    }
10061
10062    private File getNextCodePath(String packageName) {
10063        int suffix = 1;
10064        File result;
10065        do {
10066            result = new File(mAppInstallDir, packageName + "-" + suffix);
10067            suffix++;
10068        } while (result.exists());
10069        return result;
10070    }
10071
10072    // Utility method used to ignore ADD/REMOVE events
10073    // by directory observer.
10074    private static boolean ignoreCodePath(String fullPathStr) {
10075        String apkName = deriveCodePathName(fullPathStr);
10076        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
10077        if (idx != -1 && ((idx+1) < apkName.length())) {
10078            // Make sure the package ends with a numeral
10079            String version = apkName.substring(idx+1);
10080            try {
10081                Integer.parseInt(version);
10082                return true;
10083            } catch (NumberFormatException e) {}
10084        }
10085        return false;
10086    }
10087
10088    // Utility method that returns the relative package path with respect
10089    // to the installation directory. Like say for /data/data/com.test-1.apk
10090    // string com.test-1 is returned.
10091    static String deriveCodePathName(String codePath) {
10092        if (codePath == null) {
10093            return null;
10094        }
10095        final File codeFile = new File(codePath);
10096        final String name = codeFile.getName();
10097        if (codeFile.isDirectory()) {
10098            return name;
10099        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10100            final int lastDot = name.lastIndexOf('.');
10101            return name.substring(0, lastDot);
10102        } else {
10103            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10104            return null;
10105        }
10106    }
10107
10108    class PackageInstalledInfo {
10109        String name;
10110        int uid;
10111        // The set of users that originally had this package installed.
10112        int[] origUsers;
10113        // The set of users that now have this package installed.
10114        int[] newUsers;
10115        PackageParser.Package pkg;
10116        int returnCode;
10117        String returnMsg;
10118        PackageRemovedInfo removedInfo;
10119
10120        public void setError(int code, String msg) {
10121            returnCode = code;
10122            returnMsg = msg;
10123            Slog.w(TAG, msg);
10124        }
10125
10126        public void setError(String msg, PackageParserException e) {
10127            returnCode = e.error;
10128            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10129            Slog.w(TAG, msg, e);
10130        }
10131
10132        public void setError(String msg, PackageManagerException e) {
10133            returnCode = e.error;
10134            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10135            Slog.w(TAG, msg, e);
10136        }
10137
10138        // In some error cases we want to convey more info back to the observer
10139        String origPackage;
10140        String origPermission;
10141    }
10142
10143    /*
10144     * Install a non-existing package.
10145     */
10146    private void installNewPackageLI(PackageParser.Package pkg,
10147            int parseFlags, int scanFlags, UserHandle user,
10148            String installerPackageName, PackageInstalledInfo res) {
10149        // Remember this for later, in case we need to rollback this install
10150        String pkgName = pkg.packageName;
10151
10152        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10153        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
10154        synchronized(mPackages) {
10155            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10156                // A package with the same name is already installed, though
10157                // it has been renamed to an older name.  The package we
10158                // are trying to install should be installed as an update to
10159                // the existing one, but that has not been requested, so bail.
10160                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10161                        + " without first uninstalling package running as "
10162                        + mSettings.mRenamedPackages.get(pkgName));
10163                return;
10164            }
10165            if (mPackages.containsKey(pkgName)) {
10166                // Don't allow installation over an existing package with the same name.
10167                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10168                        + " without first uninstalling.");
10169                return;
10170            }
10171        }
10172
10173        try {
10174            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10175                    System.currentTimeMillis(), user);
10176
10177            updateSettingsLI(newPackage, installerPackageName, null, null, res);
10178            // delete the partially installed application. the data directory will have to be
10179            // restored if it was already existing
10180            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10181                // remove package from internal structures.  Note that we want deletePackageX to
10182                // delete the package data and cache directories that it created in
10183                // scanPackageLocked, unless those directories existed before we even tried to
10184                // install.
10185                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10186                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10187                                res.removedInfo, true);
10188            }
10189
10190        } catch (PackageManagerException e) {
10191            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10192        }
10193    }
10194
10195    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10196        // Upgrade keysets are being used.  Determine if new package has a superset of the
10197        // required keys.
10198        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10199        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10200        for (int i = 0; i < upgradeKeySets.length; i++) {
10201            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10202            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10203                return true;
10204            }
10205        }
10206        return false;
10207    }
10208
10209    private void replacePackageLI(PackageParser.Package pkg,
10210            int parseFlags, int scanFlags, UserHandle user,
10211            String installerPackageName, PackageInstalledInfo res) {
10212        PackageParser.Package oldPackage;
10213        String pkgName = pkg.packageName;
10214        int[] allUsers;
10215        boolean[] perUserInstalled;
10216
10217        // First find the old package info and check signatures
10218        synchronized(mPackages) {
10219            oldPackage = mPackages.get(pkgName);
10220            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10221            PackageSetting ps = mSettings.mPackages.get(pkgName);
10222            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10223                // default to original signature matching
10224                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10225                    != PackageManager.SIGNATURE_MATCH) {
10226                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10227                            "New package has a different signature: " + pkgName);
10228                    return;
10229                }
10230            } else {
10231                if(!checkUpgradeKeySetLP(ps, pkg)) {
10232                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10233                            "New package not signed by keys specified by upgrade-keysets: "
10234                            + pkgName);
10235                    return;
10236                }
10237            }
10238
10239            // In case of rollback, remember per-user/profile install state
10240            allUsers = sUserManager.getUserIds();
10241            perUserInstalled = new boolean[allUsers.length];
10242            for (int i = 0; i < allUsers.length; i++) {
10243                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10244            }
10245        }
10246
10247        boolean sysPkg = (isSystemApp(oldPackage));
10248        if (sysPkg) {
10249            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10250                    user, allUsers, perUserInstalled, installerPackageName, res);
10251        } else {
10252            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10253                    user, allUsers, perUserInstalled, installerPackageName, res);
10254        }
10255    }
10256
10257    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10258            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10259            int[] allUsers, boolean[] perUserInstalled,
10260            String installerPackageName, PackageInstalledInfo res) {
10261        String pkgName = deletedPackage.packageName;
10262        boolean deletedPkg = true;
10263        boolean updatedSettings = false;
10264
10265        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10266                + deletedPackage);
10267        long origUpdateTime;
10268        if (pkg.mExtras != null) {
10269            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10270        } else {
10271            origUpdateTime = 0;
10272        }
10273
10274        // First delete the existing package while retaining the data directory
10275        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10276                res.removedInfo, true)) {
10277            // If the existing package wasn't successfully deleted
10278            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10279            deletedPkg = false;
10280        } else {
10281            // Successfully deleted the old package; proceed with replace.
10282
10283            // If deleted package lived in a container, give users a chance to
10284            // relinquish resources before killing.
10285            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
10286                if (DEBUG_INSTALL) {
10287                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10288                }
10289                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10290                final ArrayList<String> pkgList = new ArrayList<String>(1);
10291                pkgList.add(deletedPackage.applicationInfo.packageName);
10292                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10293            }
10294
10295            deleteCodeCacheDirsLI(pkgName);
10296            try {
10297                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10298                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10299                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10300                updatedSettings = true;
10301            } catch (PackageManagerException e) {
10302                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10303            }
10304        }
10305
10306        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10307            // remove package from internal structures.  Note that we want deletePackageX to
10308            // delete the package data and cache directories that it created in
10309            // scanPackageLocked, unless those directories existed before we even tried to
10310            // install.
10311            if(updatedSettings) {
10312                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10313                deletePackageLI(
10314                        pkgName, null, true, allUsers, perUserInstalled,
10315                        PackageManager.DELETE_KEEP_DATA,
10316                                res.removedInfo, true);
10317            }
10318            // Since we failed to install the new package we need to restore the old
10319            // package that we deleted.
10320            if (deletedPkg) {
10321                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10322                File restoreFile = new File(deletedPackage.codePath);
10323                // Parse old package
10324                boolean oldOnSd = isExternal(deletedPackage);
10325                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10326                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10327                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10328                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10329                try {
10330                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10331                } catch (PackageManagerException e) {
10332                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10333                            + e.getMessage());
10334                    return;
10335                }
10336                // Restore of old package succeeded. Update permissions.
10337                // writer
10338                synchronized (mPackages) {
10339                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10340                            UPDATE_PERMISSIONS_ALL);
10341                    // can downgrade to reader
10342                    mSettings.writeLPr();
10343                }
10344                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10345            }
10346        }
10347    }
10348
10349    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10350            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10351            int[] allUsers, boolean[] perUserInstalled,
10352            String installerPackageName, PackageInstalledInfo res) {
10353        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10354                + ", old=" + deletedPackage);
10355        boolean disabledSystem = false;
10356        boolean updatedSettings = false;
10357        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10358        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
10359                != 0) {
10360            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10361        }
10362        String packageName = deletedPackage.packageName;
10363        if (packageName == null) {
10364            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10365                    "Attempt to delete null packageName.");
10366            return;
10367        }
10368        PackageParser.Package oldPkg;
10369        PackageSetting oldPkgSetting;
10370        // reader
10371        synchronized (mPackages) {
10372            oldPkg = mPackages.get(packageName);
10373            oldPkgSetting = mSettings.mPackages.get(packageName);
10374            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10375                    (oldPkgSetting == null)) {
10376                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10377                        "Couldn't find package:" + packageName + " information");
10378                return;
10379            }
10380        }
10381
10382        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10383
10384        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10385        res.removedInfo.removedPackage = packageName;
10386        // Remove existing system package
10387        removePackageLI(oldPkgSetting, true);
10388        // writer
10389        synchronized (mPackages) {
10390            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10391            if (!disabledSystem && deletedPackage != null) {
10392                // We didn't need to disable the .apk as a current system package,
10393                // which means we are replacing another update that is already
10394                // installed.  We need to make sure to delete the older one's .apk.
10395                res.removedInfo.args = createInstallArgsForExisting(0,
10396                        deletedPackage.applicationInfo.getCodePath(),
10397                        deletedPackage.applicationInfo.getResourcePath(),
10398                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10399                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10400            } else {
10401                res.removedInfo.args = null;
10402            }
10403        }
10404
10405        // Successfully disabled the old package. Now proceed with re-installation
10406        deleteCodeCacheDirsLI(packageName);
10407
10408        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10409        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10410
10411        PackageParser.Package newPackage = null;
10412        try {
10413            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10414            if (newPackage.mExtras != null) {
10415                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10416                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10417                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10418
10419                // is the update attempting to change shared user? that isn't going to work...
10420                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10421                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10422                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10423                            + " to " + newPkgSetting.sharedUser);
10424                    updatedSettings = true;
10425                }
10426            }
10427
10428            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10429                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10430                updatedSettings = true;
10431            }
10432
10433        } catch (PackageManagerException e) {
10434            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10435        }
10436
10437        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10438            // Re installation failed. Restore old information
10439            // Remove new pkg information
10440            if (newPackage != null) {
10441                removeInstalledPackageLI(newPackage, true);
10442            }
10443            // Add back the old system package
10444            try {
10445                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10446            } catch (PackageManagerException e) {
10447                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10448            }
10449            // Restore the old system information in Settings
10450            synchronized (mPackages) {
10451                if (disabledSystem) {
10452                    mSettings.enableSystemPackageLPw(packageName);
10453                }
10454                if (updatedSettings) {
10455                    mSettings.setInstallerPackageName(packageName,
10456                            oldPkgSetting.installerPackageName);
10457                }
10458                mSettings.writeLPr();
10459            }
10460        }
10461    }
10462
10463    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10464            int[] allUsers, boolean[] perUserInstalled,
10465            PackageInstalledInfo res) {
10466        String pkgName = newPackage.packageName;
10467        synchronized (mPackages) {
10468            //write settings. the installStatus will be incomplete at this stage.
10469            //note that the new package setting would have already been
10470            //added to mPackages. It hasn't been persisted yet.
10471            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10472            mSettings.writeLPr();
10473        }
10474
10475        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10476
10477        synchronized (mPackages) {
10478            updatePermissionsLPw(newPackage.packageName, newPackage,
10479                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10480                            ? UPDATE_PERMISSIONS_ALL : 0));
10481            // For system-bundled packages, we assume that installing an upgraded version
10482            // of the package implies that the user actually wants to run that new code,
10483            // so we enable the package.
10484            if (isSystemApp(newPackage)) {
10485                // NB: implicit assumption that system package upgrades apply to all users
10486                if (DEBUG_INSTALL) {
10487                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10488                }
10489                PackageSetting ps = mSettings.mPackages.get(pkgName);
10490                if (ps != null) {
10491                    if (res.origUsers != null) {
10492                        for (int userHandle : res.origUsers) {
10493                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10494                                    userHandle, installerPackageName);
10495                        }
10496                    }
10497                    // Also convey the prior install/uninstall state
10498                    if (allUsers != null && perUserInstalled != null) {
10499                        for (int i = 0; i < allUsers.length; i++) {
10500                            if (DEBUG_INSTALL) {
10501                                Slog.d(TAG, "    user " + allUsers[i]
10502                                        + " => " + perUserInstalled[i]);
10503                            }
10504                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10505                        }
10506                        // these install state changes will be persisted in the
10507                        // upcoming call to mSettings.writeLPr().
10508                    }
10509                }
10510            }
10511            res.name = pkgName;
10512            res.uid = newPackage.applicationInfo.uid;
10513            res.pkg = newPackage;
10514            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10515            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10516            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10517            //to update install status
10518            mSettings.writeLPr();
10519        }
10520    }
10521
10522    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10523        final int installFlags = args.installFlags;
10524        String installerPackageName = args.installerPackageName;
10525        File tmpPackageFile = new File(args.getCodePath());
10526        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10527        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10528        boolean replace = false;
10529        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10530        // Result object to be returned
10531        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10532
10533        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10534        // Retrieve PackageSettings and parse package
10535        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10536                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10537                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10538        PackageParser pp = new PackageParser();
10539        pp.setSeparateProcesses(mSeparateProcesses);
10540        pp.setDisplayMetrics(mMetrics);
10541
10542        final PackageParser.Package pkg;
10543        try {
10544            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10545        } catch (PackageParserException e) {
10546            res.setError("Failed parse during installPackageLI", e);
10547            return;
10548        }
10549
10550        // Mark that we have an install time CPU ABI override.
10551        pkg.cpuAbiOverride = args.abiOverride;
10552
10553        String pkgName = res.name = pkg.packageName;
10554        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10555            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10556                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10557                return;
10558            }
10559        }
10560
10561        try {
10562            pp.collectCertificates(pkg, parseFlags);
10563            pp.collectManifestDigest(pkg);
10564        } catch (PackageParserException e) {
10565            res.setError("Failed collect during installPackageLI", e);
10566            return;
10567        }
10568
10569        /* If the installer passed in a manifest digest, compare it now. */
10570        if (args.manifestDigest != null) {
10571            if (DEBUG_INSTALL) {
10572                final String parsedManifest = pkg.manifestDigest == null ? "null"
10573                        : pkg.manifestDigest.toString();
10574                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10575                        + parsedManifest);
10576            }
10577
10578            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10579                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10580                return;
10581            }
10582        } else if (DEBUG_INSTALL) {
10583            final String parsedManifest = pkg.manifestDigest == null
10584                    ? "null" : pkg.manifestDigest.toString();
10585            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10586        }
10587
10588        // Get rid of all references to package scan path via parser.
10589        pp = null;
10590        String oldCodePath = null;
10591        boolean systemApp = false;
10592        synchronized (mPackages) {
10593            // Check if installing already existing package
10594            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10595                String oldName = mSettings.mRenamedPackages.get(pkgName);
10596                if (pkg.mOriginalPackages != null
10597                        && pkg.mOriginalPackages.contains(oldName)
10598                        && mPackages.containsKey(oldName)) {
10599                    // This package is derived from an original package,
10600                    // and this device has been updating from that original
10601                    // name.  We must continue using the original name, so
10602                    // rename the new package here.
10603                    pkg.setPackageName(oldName);
10604                    pkgName = pkg.packageName;
10605                    replace = true;
10606                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10607                            + oldName + " pkgName=" + pkgName);
10608                } else if (mPackages.containsKey(pkgName)) {
10609                    // This package, under its official name, already exists
10610                    // on the device; we should replace it.
10611                    replace = true;
10612                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10613                }
10614            }
10615
10616            PackageSetting ps = mSettings.mPackages.get(pkgName);
10617            if (ps != null) {
10618                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10619
10620                // Quick sanity check that we're signed correctly if updating;
10621                // we'll check this again later when scanning, but we want to
10622                // bail early here before tripping over redefined permissions.
10623                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10624                    try {
10625                        verifySignaturesLP(ps, pkg);
10626                    } catch (PackageManagerException e) {
10627                        res.setError(e.error, e.getMessage());
10628                        return;
10629                    }
10630                } else {
10631                    if (!checkUpgradeKeySetLP(ps, pkg)) {
10632                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
10633                                + pkg.packageName + " upgrade keys do not match the "
10634                                + "previously installed version");
10635                        return;
10636                    }
10637                }
10638
10639                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10640                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10641                    systemApp = (ps.pkg.applicationInfo.flags &
10642                            ApplicationInfo.FLAG_SYSTEM) != 0;
10643                }
10644                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10645            }
10646
10647            // Check whether the newly-scanned package wants to define an already-defined perm
10648            int N = pkg.permissions.size();
10649            for (int i = N-1; i >= 0; i--) {
10650                PackageParser.Permission perm = pkg.permissions.get(i);
10651                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10652                if (bp != null) {
10653                    // If the defining package is signed with our cert, it's okay.  This
10654                    // also includes the "updating the same package" case, of course.
10655                    // "updating same package" could also involve key-rotation.
10656                    final boolean sigsOk;
10657                    if (!bp.sourcePackage.equals(pkg.packageName)
10658                            || !(bp.packageSetting instanceof PackageSetting)
10659                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10660                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10661                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10662                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10663                    } else {
10664                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10665                    }
10666                    if (!sigsOk) {
10667                        // If the owning package is the system itself, we log but allow
10668                        // install to proceed; we fail the install on all other permission
10669                        // redefinitions.
10670                        if (!bp.sourcePackage.equals("android")) {
10671                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10672                                    + pkg.packageName + " attempting to redeclare permission "
10673                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10674                            res.origPermission = perm.info.name;
10675                            res.origPackage = bp.sourcePackage;
10676                            return;
10677                        } else {
10678                            Slog.w(TAG, "Package " + pkg.packageName
10679                                    + " attempting to redeclare system permission "
10680                                    + perm.info.name + "; ignoring new declaration");
10681                            pkg.permissions.remove(i);
10682                        }
10683                    }
10684                }
10685            }
10686
10687        }
10688
10689        if (systemApp && onSd) {
10690            // Disable updates to system apps on sdcard
10691            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10692                    "Cannot install updates to system apps on sdcard");
10693            return;
10694        }
10695
10696        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10697            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10698            return;
10699        }
10700
10701        if (replace) {
10702            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10703                    installerPackageName, res);
10704        } else {
10705            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10706                    args.user, installerPackageName, res);
10707        }
10708        synchronized (mPackages) {
10709            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10710            if (ps != null) {
10711                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10712            }
10713        }
10714    }
10715
10716    private static boolean isForwardLocked(PackageParser.Package pkg) {
10717        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK) != 0;
10718    }
10719
10720    private static boolean isForwardLocked(ApplicationInfo info) {
10721        return (info.privateFlags & ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK) != 0;
10722    }
10723
10724    private boolean isForwardLocked(PackageSetting ps) {
10725        return (ps.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK) != 0;
10726    }
10727
10728    private static boolean isMultiArch(PackageSetting ps) {
10729        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10730    }
10731
10732    private static boolean isMultiArch(ApplicationInfo info) {
10733        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10734    }
10735
10736    private static boolean isExternal(PackageParser.Package pkg) {
10737        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10738    }
10739
10740    private static boolean isExternal(PackageSetting ps) {
10741        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10742    }
10743
10744    private static boolean isExternal(ApplicationInfo info) {
10745        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10746    }
10747
10748    private static boolean isSystemApp(PackageParser.Package pkg) {
10749        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10750    }
10751
10752    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10753        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
10754    }
10755
10756    private static boolean isSystemApp(ApplicationInfo info) {
10757        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10758    }
10759
10760    private static boolean isSystemApp(PackageSetting ps) {
10761        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10762    }
10763
10764    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10765        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10766    }
10767
10768    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10769        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10770    }
10771
10772    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10773        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10774    }
10775
10776    private int packageFlagsToInstallFlags(PackageSetting ps) {
10777        int installFlags = 0;
10778        if (isExternal(ps)) {
10779            installFlags |= PackageManager.INSTALL_EXTERNAL;
10780        }
10781        if (isForwardLocked(ps)) {
10782            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10783        }
10784        return installFlags;
10785    }
10786
10787    private void deleteTempPackageFiles() {
10788        final FilenameFilter filter = new FilenameFilter() {
10789            public boolean accept(File dir, String name) {
10790                return name.startsWith("vmdl") && name.endsWith(".tmp");
10791            }
10792        };
10793        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10794            file.delete();
10795        }
10796    }
10797
10798    @Override
10799    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10800            int flags) {
10801        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10802                flags);
10803    }
10804
10805    @Override
10806    public void deletePackage(final String packageName,
10807            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10808        mContext.enforceCallingOrSelfPermission(
10809                android.Manifest.permission.DELETE_PACKAGES, null);
10810        final int uid = Binder.getCallingUid();
10811        if (UserHandle.getUserId(uid) != userId) {
10812            mContext.enforceCallingPermission(
10813                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10814                    "deletePackage for user " + userId);
10815        }
10816        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10817            try {
10818                observer.onPackageDeleted(packageName,
10819                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10820            } catch (RemoteException re) {
10821            }
10822            return;
10823        }
10824
10825        boolean uninstallBlocked = false;
10826        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10827            int[] users = sUserManager.getUserIds();
10828            for (int i = 0; i < users.length; ++i) {
10829                if (getBlockUninstallForUser(packageName, users[i])) {
10830                    uninstallBlocked = true;
10831                    break;
10832                }
10833            }
10834        } else {
10835            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10836        }
10837        if (uninstallBlocked) {
10838            try {
10839                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10840                        null);
10841            } catch (RemoteException re) {
10842            }
10843            return;
10844        }
10845
10846        if (DEBUG_REMOVE) {
10847            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10848        }
10849        // Queue up an async operation since the package deletion may take a little while.
10850        mHandler.post(new Runnable() {
10851            public void run() {
10852                mHandler.removeCallbacks(this);
10853                final int returnCode = deletePackageX(packageName, userId, flags);
10854                if (observer != null) {
10855                    try {
10856                        observer.onPackageDeleted(packageName, returnCode, null);
10857                    } catch (RemoteException e) {
10858                        Log.i(TAG, "Observer no longer exists.");
10859                    } //end catch
10860                } //end if
10861            } //end run
10862        });
10863    }
10864
10865    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10866        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10867                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10868        try {
10869            if (dpm != null) {
10870                if (dpm.isDeviceOwner(packageName)) {
10871                    return true;
10872                }
10873                int[] users;
10874                if (userId == UserHandle.USER_ALL) {
10875                    users = sUserManager.getUserIds();
10876                } else {
10877                    users = new int[]{userId};
10878                }
10879                for (int i = 0; i < users.length; ++i) {
10880                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10881                        return true;
10882                    }
10883                }
10884            }
10885        } catch (RemoteException e) {
10886        }
10887        return false;
10888    }
10889
10890    /**
10891     *  This method is an internal method that could be get invoked either
10892     *  to delete an installed package or to clean up a failed installation.
10893     *  After deleting an installed package, a broadcast is sent to notify any
10894     *  listeners that the package has been installed. For cleaning up a failed
10895     *  installation, the broadcast is not necessary since the package's
10896     *  installation wouldn't have sent the initial broadcast either
10897     *  The key steps in deleting a package are
10898     *  deleting the package information in internal structures like mPackages,
10899     *  deleting the packages base directories through installd
10900     *  updating mSettings to reflect current status
10901     *  persisting settings for later use
10902     *  sending a broadcast if necessary
10903     */
10904    private int deletePackageX(String packageName, int userId, int flags) {
10905        final PackageRemovedInfo info = new PackageRemovedInfo();
10906        final boolean res;
10907
10908        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10909                ? UserHandle.ALL : new UserHandle(userId);
10910
10911        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10912            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10913            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10914        }
10915
10916        boolean removedForAllUsers = false;
10917        boolean systemUpdate = false;
10918
10919        // for the uninstall-updates case and restricted profiles, remember the per-
10920        // userhandle installed state
10921        int[] allUsers;
10922        boolean[] perUserInstalled;
10923        synchronized (mPackages) {
10924            PackageSetting ps = mSettings.mPackages.get(packageName);
10925            allUsers = sUserManager.getUserIds();
10926            perUserInstalled = new boolean[allUsers.length];
10927            for (int i = 0; i < allUsers.length; i++) {
10928                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10929            }
10930        }
10931
10932        synchronized (mInstallLock) {
10933            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10934            res = deletePackageLI(packageName, removeForUser,
10935                    true, allUsers, perUserInstalled,
10936                    flags | REMOVE_CHATTY, info, true);
10937            systemUpdate = info.isRemovedPackageSystemUpdate;
10938            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10939                removedForAllUsers = true;
10940            }
10941            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10942                    + " removedForAllUsers=" + removedForAllUsers);
10943        }
10944
10945        if (res) {
10946            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10947
10948            // If the removed package was a system update, the old system package
10949            // was re-enabled; we need to broadcast this information
10950            if (systemUpdate) {
10951                Bundle extras = new Bundle(1);
10952                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10953                        ? info.removedAppId : info.uid);
10954                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10955
10956                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10957                        extras, null, null, null);
10958                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10959                        extras, null, null, null);
10960                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10961                        null, packageName, null, null);
10962            }
10963        }
10964        // Force a gc here.
10965        Runtime.getRuntime().gc();
10966        // Delete the resources here after sending the broadcast to let
10967        // other processes clean up before deleting resources.
10968        if (info.args != null) {
10969            synchronized (mInstallLock) {
10970                info.args.doPostDeleteLI(true);
10971            }
10972        }
10973
10974        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10975    }
10976
10977    static class PackageRemovedInfo {
10978        String removedPackage;
10979        int uid = -1;
10980        int removedAppId = -1;
10981        int[] removedUsers = null;
10982        boolean isRemovedPackageSystemUpdate = false;
10983        // Clean up resources deleted packages.
10984        InstallArgs args = null;
10985
10986        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10987            Bundle extras = new Bundle(1);
10988            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10989            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10990            if (replacing) {
10991                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10992            }
10993            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10994            if (removedPackage != null) {
10995                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10996                        extras, null, null, removedUsers);
10997                if (fullRemove && !replacing) {
10998                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10999                            extras, null, null, removedUsers);
11000                }
11001            }
11002            if (removedAppId >= 0) {
11003                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
11004                        removedUsers);
11005            }
11006        }
11007    }
11008
11009    /*
11010     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
11011     * flag is not set, the data directory is removed as well.
11012     * make sure this flag is set for partially installed apps. If not its meaningless to
11013     * delete a partially installed application.
11014     */
11015    private void removePackageDataLI(PackageSetting ps,
11016            int[] allUserHandles, boolean[] perUserInstalled,
11017            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
11018        String packageName = ps.name;
11019        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
11020        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
11021        // Retrieve object to delete permissions for shared user later on
11022        final PackageSetting deletedPs;
11023        // reader
11024        synchronized (mPackages) {
11025            deletedPs = mSettings.mPackages.get(packageName);
11026            if (outInfo != null) {
11027                outInfo.removedPackage = packageName;
11028                outInfo.removedUsers = deletedPs != null
11029                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
11030                        : null;
11031            }
11032        }
11033        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11034            removeDataDirsLI(packageName);
11035            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
11036        }
11037        // writer
11038        synchronized (mPackages) {
11039            if (deletedPs != null) {
11040                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11041                    if (outInfo != null) {
11042                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
11043                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
11044                    }
11045                    if (deletedPs != null) {
11046                        updatePermissionsLPw(deletedPs.name, null, 0);
11047                        if (deletedPs.sharedUser != null) {
11048                            // remove permissions associated with package
11049                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
11050                        }
11051                    }
11052                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
11053                }
11054                // make sure to preserve per-user disabled state if this removal was just
11055                // a downgrade of a system app to the factory package
11056                if (allUserHandles != null && perUserInstalled != null) {
11057                    if (DEBUG_REMOVE) {
11058                        Slog.d(TAG, "Propagating install state across downgrade");
11059                    }
11060                    for (int i = 0; i < allUserHandles.length; i++) {
11061                        if (DEBUG_REMOVE) {
11062                            Slog.d(TAG, "    user " + allUserHandles[i]
11063                                    + " => " + perUserInstalled[i]);
11064                        }
11065                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11066                    }
11067                }
11068            }
11069            // can downgrade to reader
11070            if (writeSettings) {
11071                // Save settings now
11072                mSettings.writeLPr();
11073            }
11074        }
11075        if (outInfo != null) {
11076            // A user ID was deleted here. Go through all users and remove it
11077            // from KeyStore.
11078            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
11079        }
11080    }
11081
11082    static boolean locationIsPrivileged(File path) {
11083        try {
11084            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
11085                    .getCanonicalPath();
11086            return path.getCanonicalPath().startsWith(privilegedAppDir);
11087        } catch (IOException e) {
11088            Slog.e(TAG, "Unable to access code path " + path);
11089        }
11090        return false;
11091    }
11092
11093    /*
11094     * Tries to delete system package.
11095     */
11096    private boolean deleteSystemPackageLI(PackageSetting newPs,
11097            int[] allUserHandles, boolean[] perUserInstalled,
11098            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
11099        final boolean applyUserRestrictions
11100                = (allUserHandles != null) && (perUserInstalled != null);
11101        PackageSetting disabledPs = null;
11102        // Confirm if the system package has been updated
11103        // An updated system app can be deleted. This will also have to restore
11104        // the system pkg from system partition
11105        // reader
11106        synchronized (mPackages) {
11107            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
11108        }
11109        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
11110                + " disabledPs=" + disabledPs);
11111        if (disabledPs == null) {
11112            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
11113            return false;
11114        } else if (DEBUG_REMOVE) {
11115            Slog.d(TAG, "Deleting system pkg from data partition");
11116        }
11117        if (DEBUG_REMOVE) {
11118            if (applyUserRestrictions) {
11119                Slog.d(TAG, "Remembering install states:");
11120                for (int i = 0; i < allUserHandles.length; i++) {
11121                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
11122                }
11123            }
11124        }
11125        // Delete the updated package
11126        outInfo.isRemovedPackageSystemUpdate = true;
11127        if (disabledPs.versionCode < newPs.versionCode) {
11128            // Delete data for downgrades
11129            flags &= ~PackageManager.DELETE_KEEP_DATA;
11130        } else {
11131            // Preserve data by setting flag
11132            flags |= PackageManager.DELETE_KEEP_DATA;
11133        }
11134        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
11135                allUserHandles, perUserInstalled, outInfo, writeSettings);
11136        if (!ret) {
11137            return false;
11138        }
11139        // writer
11140        synchronized (mPackages) {
11141            // Reinstate the old system package
11142            mSettings.enableSystemPackageLPw(newPs.name);
11143            // Remove any native libraries from the upgraded package.
11144            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
11145        }
11146        // Install the system package
11147        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
11148        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
11149        if (locationIsPrivileged(disabledPs.codePath)) {
11150            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11151        }
11152
11153        final PackageParser.Package newPkg;
11154        try {
11155            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
11156        } catch (PackageManagerException e) {
11157            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
11158            return false;
11159        }
11160
11161        // writer
11162        synchronized (mPackages) {
11163            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
11164            updatePermissionsLPw(newPkg.packageName, newPkg,
11165                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
11166            if (applyUserRestrictions) {
11167                if (DEBUG_REMOVE) {
11168                    Slog.d(TAG, "Propagating install state across reinstall");
11169                }
11170                for (int i = 0; i < allUserHandles.length; i++) {
11171                    if (DEBUG_REMOVE) {
11172                        Slog.d(TAG, "    user " + allUserHandles[i]
11173                                + " => " + perUserInstalled[i]);
11174                    }
11175                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11176                }
11177                // Regardless of writeSettings we need to ensure that this restriction
11178                // state propagation is persisted
11179                mSettings.writeAllUsersPackageRestrictionsLPr();
11180            }
11181            // can downgrade to reader here
11182            if (writeSettings) {
11183                mSettings.writeLPr();
11184            }
11185        }
11186        return true;
11187    }
11188
11189    private boolean deleteInstalledPackageLI(PackageSetting ps,
11190            boolean deleteCodeAndResources, int flags,
11191            int[] allUserHandles, boolean[] perUserInstalled,
11192            PackageRemovedInfo outInfo, boolean writeSettings) {
11193        if (outInfo != null) {
11194            outInfo.uid = ps.appId;
11195        }
11196
11197        // Delete package data from internal structures and also remove data if flag is set
11198        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
11199
11200        // Delete application code and resources
11201        if (deleteCodeAndResources && (outInfo != null)) {
11202            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
11203                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
11204                    getAppDexInstructionSets(ps));
11205            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
11206        }
11207        return true;
11208    }
11209
11210    @Override
11211    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11212            int userId) {
11213        mContext.enforceCallingOrSelfPermission(
11214                android.Manifest.permission.DELETE_PACKAGES, null);
11215        synchronized (mPackages) {
11216            PackageSetting ps = mSettings.mPackages.get(packageName);
11217            if (ps == null) {
11218                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11219                return false;
11220            }
11221            if (!ps.getInstalled(userId)) {
11222                // Can't block uninstall for an app that is not installed or enabled.
11223                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11224                return false;
11225            }
11226            ps.setBlockUninstall(blockUninstall, userId);
11227            mSettings.writePackageRestrictionsLPr(userId);
11228        }
11229        return true;
11230    }
11231
11232    @Override
11233    public boolean getBlockUninstallForUser(String packageName, int userId) {
11234        synchronized (mPackages) {
11235            PackageSetting ps = mSettings.mPackages.get(packageName);
11236            if (ps == null) {
11237                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11238                return false;
11239            }
11240            return ps.getBlockUninstall(userId);
11241        }
11242    }
11243
11244    /*
11245     * This method handles package deletion in general
11246     */
11247    private boolean deletePackageLI(String packageName, UserHandle user,
11248            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11249            int flags, PackageRemovedInfo outInfo,
11250            boolean writeSettings) {
11251        if (packageName == null) {
11252            Slog.w(TAG, "Attempt to delete null packageName.");
11253            return false;
11254        }
11255        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11256        PackageSetting ps;
11257        boolean dataOnly = false;
11258        int removeUser = -1;
11259        int appId = -1;
11260        synchronized (mPackages) {
11261            ps = mSettings.mPackages.get(packageName);
11262            if (ps == null) {
11263                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11264                return false;
11265            }
11266            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11267                    && user.getIdentifier() != UserHandle.USER_ALL) {
11268                // The caller is asking that the package only be deleted for a single
11269                // user.  To do this, we just mark its uninstalled state and delete
11270                // its data.  If this is a system app, we only allow this to happen if
11271                // they have set the special DELETE_SYSTEM_APP which requests different
11272                // semantics than normal for uninstalling system apps.
11273                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11274                ps.setUserState(user.getIdentifier(),
11275                        COMPONENT_ENABLED_STATE_DEFAULT,
11276                        false, //installed
11277                        true,  //stopped
11278                        true,  //notLaunched
11279                        false, //hidden
11280                        null, null, null,
11281                        false // blockUninstall
11282                        );
11283                if (!isSystemApp(ps)) {
11284                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11285                        // Other user still have this package installed, so all
11286                        // we need to do is clear this user's data and save that
11287                        // it is uninstalled.
11288                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11289                        removeUser = user.getIdentifier();
11290                        appId = ps.appId;
11291                        mSettings.writePackageRestrictionsLPr(removeUser);
11292                    } else {
11293                        // We need to set it back to 'installed' so the uninstall
11294                        // broadcasts will be sent correctly.
11295                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11296                        ps.setInstalled(true, user.getIdentifier());
11297                    }
11298                } else {
11299                    // This is a system app, so we assume that the
11300                    // other users still have this package installed, so all
11301                    // we need to do is clear this user's data and save that
11302                    // it is uninstalled.
11303                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11304                    removeUser = user.getIdentifier();
11305                    appId = ps.appId;
11306                    mSettings.writePackageRestrictionsLPr(removeUser);
11307                }
11308            }
11309        }
11310
11311        if (removeUser >= 0) {
11312            // From above, we determined that we are deleting this only
11313            // for a single user.  Continue the work here.
11314            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11315            if (outInfo != null) {
11316                outInfo.removedPackage = packageName;
11317                outInfo.removedAppId = appId;
11318                outInfo.removedUsers = new int[] {removeUser};
11319            }
11320            mInstaller.clearUserData(packageName, removeUser);
11321            removeKeystoreDataIfNeeded(removeUser, appId);
11322            schedulePackageCleaning(packageName, removeUser, false);
11323            return true;
11324        }
11325
11326        if (dataOnly) {
11327            // Delete application data first
11328            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11329            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11330            return true;
11331        }
11332
11333        boolean ret = false;
11334        if (isSystemApp(ps)) {
11335            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11336            // When an updated system application is deleted we delete the existing resources as well and
11337            // fall back to existing code in system partition
11338            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11339                    flags, outInfo, writeSettings);
11340        } else {
11341            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11342            // Kill application pre-emptively especially for apps on sd.
11343            killApplication(packageName, ps.appId, "uninstall pkg");
11344            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11345                    allUserHandles, perUserInstalled,
11346                    outInfo, writeSettings);
11347        }
11348
11349        return ret;
11350    }
11351
11352    private final class ClearStorageConnection implements ServiceConnection {
11353        IMediaContainerService mContainerService;
11354
11355        @Override
11356        public void onServiceConnected(ComponentName name, IBinder service) {
11357            synchronized (this) {
11358                mContainerService = IMediaContainerService.Stub.asInterface(service);
11359                notifyAll();
11360            }
11361        }
11362
11363        @Override
11364        public void onServiceDisconnected(ComponentName name) {
11365        }
11366    }
11367
11368    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11369        final boolean mounted;
11370        if (Environment.isExternalStorageEmulated()) {
11371            mounted = true;
11372        } else {
11373            final String status = Environment.getExternalStorageState();
11374
11375            mounted = status.equals(Environment.MEDIA_MOUNTED)
11376                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11377        }
11378
11379        if (!mounted) {
11380            return;
11381        }
11382
11383        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11384        int[] users;
11385        if (userId == UserHandle.USER_ALL) {
11386            users = sUserManager.getUserIds();
11387        } else {
11388            users = new int[] { userId };
11389        }
11390        final ClearStorageConnection conn = new ClearStorageConnection();
11391        if (mContext.bindServiceAsUser(
11392                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11393            try {
11394                for (int curUser : users) {
11395                    long timeout = SystemClock.uptimeMillis() + 5000;
11396                    synchronized (conn) {
11397                        long now = SystemClock.uptimeMillis();
11398                        while (conn.mContainerService == null && now < timeout) {
11399                            try {
11400                                conn.wait(timeout - now);
11401                            } catch (InterruptedException e) {
11402                            }
11403                        }
11404                    }
11405                    if (conn.mContainerService == null) {
11406                        return;
11407                    }
11408
11409                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11410                    clearDirectory(conn.mContainerService,
11411                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11412                    if (allData) {
11413                        clearDirectory(conn.mContainerService,
11414                                userEnv.buildExternalStorageAppDataDirs(packageName));
11415                        clearDirectory(conn.mContainerService,
11416                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11417                    }
11418                }
11419            } finally {
11420                mContext.unbindService(conn);
11421            }
11422        }
11423    }
11424
11425    @Override
11426    public void clearApplicationUserData(final String packageName,
11427            final IPackageDataObserver observer, final int userId) {
11428        mContext.enforceCallingOrSelfPermission(
11429                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11430        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11431        // Queue up an async operation since the package deletion may take a little while.
11432        mHandler.post(new Runnable() {
11433            public void run() {
11434                mHandler.removeCallbacks(this);
11435                final boolean succeeded;
11436                synchronized (mInstallLock) {
11437                    succeeded = clearApplicationUserDataLI(packageName, userId);
11438                }
11439                clearExternalStorageDataSync(packageName, userId, true);
11440                if (succeeded) {
11441                    // invoke DeviceStorageMonitor's update method to clear any notifications
11442                    DeviceStorageMonitorInternal
11443                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11444                    if (dsm != null) {
11445                        dsm.checkMemory();
11446                    }
11447                }
11448                if(observer != null) {
11449                    try {
11450                        observer.onRemoveCompleted(packageName, succeeded);
11451                    } catch (RemoteException e) {
11452                        Log.i(TAG, "Observer no longer exists.");
11453                    }
11454                } //end if observer
11455            } //end run
11456        });
11457    }
11458
11459    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11460        if (packageName == null) {
11461            Slog.w(TAG, "Attempt to delete null packageName.");
11462            return false;
11463        }
11464
11465        // Try finding details about the requested package
11466        PackageParser.Package pkg;
11467        synchronized (mPackages) {
11468            pkg = mPackages.get(packageName);
11469            if (pkg == null) {
11470                final PackageSetting ps = mSettings.mPackages.get(packageName);
11471                if (ps != null) {
11472                    pkg = ps.pkg;
11473                }
11474            }
11475        }
11476
11477        if (pkg == null) {
11478            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11479        }
11480
11481        // Always delete data directories for package, even if we found no other
11482        // record of app. This helps users recover from UID mismatches without
11483        // resorting to a full data wipe.
11484        int retCode = mInstaller.clearUserData(packageName, userId);
11485        if (retCode < 0) {
11486            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11487            return false;
11488        }
11489
11490        if (pkg == null) {
11491            return false;
11492        }
11493
11494        if (pkg != null && pkg.applicationInfo != null) {
11495            final int appId = pkg.applicationInfo.uid;
11496            removeKeystoreDataIfNeeded(userId, appId);
11497        }
11498
11499        // Create a native library symlink only if we have native libraries
11500        // and if the native libraries are 32 bit libraries. We do not provide
11501        // this symlink for 64 bit libraries.
11502        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11503                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11504            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11505            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11506                Slog.w(TAG, "Failed linking native library dir");
11507                return false;
11508            }
11509        }
11510
11511        return true;
11512    }
11513
11514    /**
11515     * Remove entries from the keystore daemon. Will only remove it if the
11516     * {@code appId} is valid.
11517     */
11518    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11519        if (appId < 0) {
11520            return;
11521        }
11522
11523        final KeyStore keyStore = KeyStore.getInstance();
11524        if (keyStore != null) {
11525            if (userId == UserHandle.USER_ALL) {
11526                for (final int individual : sUserManager.getUserIds()) {
11527                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11528                }
11529            } else {
11530                keyStore.clearUid(UserHandle.getUid(userId, appId));
11531            }
11532        } else {
11533            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11534        }
11535    }
11536
11537    @Override
11538    public void deleteApplicationCacheFiles(final String packageName,
11539            final IPackageDataObserver observer) {
11540        mContext.enforceCallingOrSelfPermission(
11541                android.Manifest.permission.DELETE_CACHE_FILES, null);
11542        // Queue up an async operation since the package deletion may take a little while.
11543        final int userId = UserHandle.getCallingUserId();
11544        mHandler.post(new Runnable() {
11545            public void run() {
11546                mHandler.removeCallbacks(this);
11547                final boolean succeded;
11548                synchronized (mInstallLock) {
11549                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11550                }
11551                clearExternalStorageDataSync(packageName, userId, false);
11552                if(observer != null) {
11553                    try {
11554                        observer.onRemoveCompleted(packageName, succeded);
11555                    } catch (RemoteException e) {
11556                        Log.i(TAG, "Observer no longer exists.");
11557                    }
11558                } //end if observer
11559            } //end run
11560        });
11561    }
11562
11563    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11564        if (packageName == null) {
11565            Slog.w(TAG, "Attempt to delete null packageName.");
11566            return false;
11567        }
11568        PackageParser.Package p;
11569        synchronized (mPackages) {
11570            p = mPackages.get(packageName);
11571        }
11572        if (p == null) {
11573            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11574            return false;
11575        }
11576        final ApplicationInfo applicationInfo = p.applicationInfo;
11577        if (applicationInfo == null) {
11578            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11579            return false;
11580        }
11581        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11582        if (retCode < 0) {
11583            Slog.w(TAG, "Couldn't remove cache files for package: "
11584                       + packageName + " u" + userId);
11585            return false;
11586        }
11587        return true;
11588    }
11589
11590    @Override
11591    public void getPackageSizeInfo(final String packageName, int userHandle,
11592            final IPackageStatsObserver observer) {
11593        mContext.enforceCallingOrSelfPermission(
11594                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11595        if (packageName == null) {
11596            throw new IllegalArgumentException("Attempt to get size of null packageName");
11597        }
11598
11599        PackageStats stats = new PackageStats(packageName, userHandle);
11600
11601        /*
11602         * Queue up an async operation since the package measurement may take a
11603         * little while.
11604         */
11605        Message msg = mHandler.obtainMessage(INIT_COPY);
11606        msg.obj = new MeasureParams(stats, observer);
11607        mHandler.sendMessage(msg);
11608    }
11609
11610    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11611            PackageStats pStats) {
11612        if (packageName == null) {
11613            Slog.w(TAG, "Attempt to get size of null packageName.");
11614            return false;
11615        }
11616        PackageParser.Package p;
11617        boolean dataOnly = false;
11618        String libDirRoot = null;
11619        String asecPath = null;
11620        PackageSetting ps = null;
11621        synchronized (mPackages) {
11622            p = mPackages.get(packageName);
11623            ps = mSettings.mPackages.get(packageName);
11624            if(p == null) {
11625                dataOnly = true;
11626                if((ps == null) || (ps.pkg == null)) {
11627                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11628                    return false;
11629                }
11630                p = ps.pkg;
11631            }
11632            if (ps != null) {
11633                libDirRoot = ps.legacyNativeLibraryPathString;
11634            }
11635            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11636                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11637                if (secureContainerId != null) {
11638                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11639                }
11640            }
11641        }
11642        String publicSrcDir = null;
11643        if(!dataOnly) {
11644            final ApplicationInfo applicationInfo = p.applicationInfo;
11645            if (applicationInfo == null) {
11646                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11647                return false;
11648            }
11649            if (isForwardLocked(p)) {
11650                publicSrcDir = applicationInfo.getBaseResourcePath();
11651            }
11652        }
11653        // TODO: extend to measure size of split APKs
11654        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11655        // not just the first level.
11656        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11657        // just the primary.
11658        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11659        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11660                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11661        if (res < 0) {
11662            return false;
11663        }
11664
11665        // Fix-up for forward-locked applications in ASEC containers.
11666        if (!isExternal(p)) {
11667            pStats.codeSize += pStats.externalCodeSize;
11668            pStats.externalCodeSize = 0L;
11669        }
11670
11671        return true;
11672    }
11673
11674
11675    @Override
11676    public void addPackageToPreferred(String packageName) {
11677        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11678    }
11679
11680    @Override
11681    public void removePackageFromPreferred(String packageName) {
11682        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11683    }
11684
11685    @Override
11686    public List<PackageInfo> getPreferredPackages(int flags) {
11687        return new ArrayList<PackageInfo>();
11688    }
11689
11690    private int getUidTargetSdkVersionLockedLPr(int uid) {
11691        Object obj = mSettings.getUserIdLPr(uid);
11692        if (obj instanceof SharedUserSetting) {
11693            final SharedUserSetting sus = (SharedUserSetting) obj;
11694            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11695            final Iterator<PackageSetting> it = sus.packages.iterator();
11696            while (it.hasNext()) {
11697                final PackageSetting ps = it.next();
11698                if (ps.pkg != null) {
11699                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11700                    if (v < vers) vers = v;
11701                }
11702            }
11703            return vers;
11704        } else if (obj instanceof PackageSetting) {
11705            final PackageSetting ps = (PackageSetting) obj;
11706            if (ps.pkg != null) {
11707                return ps.pkg.applicationInfo.targetSdkVersion;
11708            }
11709        }
11710        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11711    }
11712
11713    @Override
11714    public void addPreferredActivity(IntentFilter filter, int match,
11715            ComponentName[] set, ComponentName activity, int userId) {
11716        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11717                "Adding preferred");
11718    }
11719
11720    private void addPreferredActivityInternal(IntentFilter filter, int match,
11721            ComponentName[] set, ComponentName activity, boolean always, int userId,
11722            String opname) {
11723        // writer
11724        int callingUid = Binder.getCallingUid();
11725        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11726        if (filter.countActions() == 0) {
11727            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11728            return;
11729        }
11730        synchronized (mPackages) {
11731            if (mContext.checkCallingOrSelfPermission(
11732                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11733                    != PackageManager.PERMISSION_GRANTED) {
11734                if (getUidTargetSdkVersionLockedLPr(callingUid)
11735                        < Build.VERSION_CODES.FROYO) {
11736                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11737                            + callingUid);
11738                    return;
11739                }
11740                mContext.enforceCallingOrSelfPermission(
11741                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11742            }
11743
11744            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11745            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11746                    + userId + ":");
11747            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11748            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11749            scheduleWritePackageRestrictionsLocked(userId);
11750        }
11751    }
11752
11753    @Override
11754    public void replacePreferredActivity(IntentFilter filter, int match,
11755            ComponentName[] set, ComponentName activity, int userId) {
11756        if (filter.countActions() != 1) {
11757            throw new IllegalArgumentException(
11758                    "replacePreferredActivity expects filter to have only 1 action.");
11759        }
11760        if (filter.countDataAuthorities() != 0
11761                || filter.countDataPaths() != 0
11762                || filter.countDataSchemes() > 1
11763                || filter.countDataTypes() != 0) {
11764            throw new IllegalArgumentException(
11765                    "replacePreferredActivity expects filter to have no data authorities, " +
11766                    "paths, or types; and at most one scheme.");
11767        }
11768
11769        final int callingUid = Binder.getCallingUid();
11770        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11771        synchronized (mPackages) {
11772            if (mContext.checkCallingOrSelfPermission(
11773                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11774                    != PackageManager.PERMISSION_GRANTED) {
11775                if (getUidTargetSdkVersionLockedLPr(callingUid)
11776                        < Build.VERSION_CODES.FROYO) {
11777                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11778                            + Binder.getCallingUid());
11779                    return;
11780                }
11781                mContext.enforceCallingOrSelfPermission(
11782                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11783            }
11784
11785            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11786            if (pir != null) {
11787                // Get all of the existing entries that exactly match this filter.
11788                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11789                if (existing != null && existing.size() == 1) {
11790                    PreferredActivity cur = existing.get(0);
11791                    if (DEBUG_PREFERRED) {
11792                        Slog.i(TAG, "Checking replace of preferred:");
11793                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11794                        if (!cur.mPref.mAlways) {
11795                            Slog.i(TAG, "  -- CUR; not mAlways!");
11796                        } else {
11797                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11798                            Slog.i(TAG, "  -- CUR: mSet="
11799                                    + Arrays.toString(cur.mPref.mSetComponents));
11800                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11801                            Slog.i(TAG, "  -- NEW: mMatch="
11802                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11803                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11804                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11805                        }
11806                    }
11807                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11808                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11809                            && cur.mPref.sameSet(set)) {
11810                        // Setting the preferred activity to what it happens to be already
11811                        if (DEBUG_PREFERRED) {
11812                            Slog.i(TAG, "Replacing with same preferred activity "
11813                                    + cur.mPref.mShortComponent + " for user "
11814                                    + userId + ":");
11815                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11816                        }
11817                        return;
11818                    }
11819                }
11820
11821                if (existing != null) {
11822                    if (DEBUG_PREFERRED) {
11823                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11824                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11825                    }
11826                    for (int i = 0; i < existing.size(); i++) {
11827                        PreferredActivity pa = existing.get(i);
11828                        if (DEBUG_PREFERRED) {
11829                            Slog.i(TAG, "Removing existing preferred activity "
11830                                    + pa.mPref.mComponent + ":");
11831                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11832                        }
11833                        pir.removeFilter(pa);
11834                    }
11835                }
11836            }
11837            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11838                    "Replacing preferred");
11839        }
11840    }
11841
11842    @Override
11843    public void clearPackagePreferredActivities(String packageName) {
11844        final int uid = Binder.getCallingUid();
11845        // writer
11846        synchronized (mPackages) {
11847            PackageParser.Package pkg = mPackages.get(packageName);
11848            if (pkg == null || pkg.applicationInfo.uid != uid) {
11849                if (mContext.checkCallingOrSelfPermission(
11850                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11851                        != PackageManager.PERMISSION_GRANTED) {
11852                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11853                            < Build.VERSION_CODES.FROYO) {
11854                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11855                                + Binder.getCallingUid());
11856                        return;
11857                    }
11858                    mContext.enforceCallingOrSelfPermission(
11859                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11860                }
11861            }
11862
11863            int user = UserHandle.getCallingUserId();
11864            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11865                scheduleWritePackageRestrictionsLocked(user);
11866            }
11867        }
11868    }
11869
11870    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11871    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11872        ArrayList<PreferredActivity> removed = null;
11873        boolean changed = false;
11874        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11875            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11876            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11877            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11878                continue;
11879            }
11880            Iterator<PreferredActivity> it = pir.filterIterator();
11881            while (it.hasNext()) {
11882                PreferredActivity pa = it.next();
11883                // Mark entry for removal only if it matches the package name
11884                // and the entry is of type "always".
11885                if (packageName == null ||
11886                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11887                                && pa.mPref.mAlways)) {
11888                    if (removed == null) {
11889                        removed = new ArrayList<PreferredActivity>();
11890                    }
11891                    removed.add(pa);
11892                }
11893            }
11894            if (removed != null) {
11895                for (int j=0; j<removed.size(); j++) {
11896                    PreferredActivity pa = removed.get(j);
11897                    pir.removeFilter(pa);
11898                }
11899                changed = true;
11900            }
11901        }
11902        return changed;
11903    }
11904
11905    @Override
11906    public void resetPreferredActivities(int userId) {
11907        /* TODO: Actually use userId. Why is it being passed in? */
11908        mContext.enforceCallingOrSelfPermission(
11909                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11910        // writer
11911        synchronized (mPackages) {
11912            int user = UserHandle.getCallingUserId();
11913            clearPackagePreferredActivitiesLPw(null, user);
11914            mSettings.readDefaultPreferredAppsLPw(this, user);
11915            scheduleWritePackageRestrictionsLocked(user);
11916        }
11917    }
11918
11919    @Override
11920    public int getPreferredActivities(List<IntentFilter> outFilters,
11921            List<ComponentName> outActivities, String packageName) {
11922
11923        int num = 0;
11924        final int userId = UserHandle.getCallingUserId();
11925        // reader
11926        synchronized (mPackages) {
11927            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11928            if (pir != null) {
11929                final Iterator<PreferredActivity> it = pir.filterIterator();
11930                while (it.hasNext()) {
11931                    final PreferredActivity pa = it.next();
11932                    if (packageName == null
11933                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11934                                    && pa.mPref.mAlways)) {
11935                        if (outFilters != null) {
11936                            outFilters.add(new IntentFilter(pa));
11937                        }
11938                        if (outActivities != null) {
11939                            outActivities.add(pa.mPref.mComponent);
11940                        }
11941                    }
11942                }
11943            }
11944        }
11945
11946        return num;
11947    }
11948
11949    @Override
11950    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11951            int userId) {
11952        int callingUid = Binder.getCallingUid();
11953        if (callingUid != Process.SYSTEM_UID) {
11954            throw new SecurityException(
11955                    "addPersistentPreferredActivity can only be run by the system");
11956        }
11957        if (filter.countActions() == 0) {
11958            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11959            return;
11960        }
11961        synchronized (mPackages) {
11962            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11963                    " :");
11964            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11965            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11966                    new PersistentPreferredActivity(filter, activity));
11967            scheduleWritePackageRestrictionsLocked(userId);
11968        }
11969    }
11970
11971    @Override
11972    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11973        int callingUid = Binder.getCallingUid();
11974        if (callingUid != Process.SYSTEM_UID) {
11975            throw new SecurityException(
11976                    "clearPackagePersistentPreferredActivities can only be run by the system");
11977        }
11978        ArrayList<PersistentPreferredActivity> removed = null;
11979        boolean changed = false;
11980        synchronized (mPackages) {
11981            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11982                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11983                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11984                        .valueAt(i);
11985                if (userId != thisUserId) {
11986                    continue;
11987                }
11988                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11989                while (it.hasNext()) {
11990                    PersistentPreferredActivity ppa = it.next();
11991                    // Mark entry for removal only if it matches the package name.
11992                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11993                        if (removed == null) {
11994                            removed = new ArrayList<PersistentPreferredActivity>();
11995                        }
11996                        removed.add(ppa);
11997                    }
11998                }
11999                if (removed != null) {
12000                    for (int j=0; j<removed.size(); j++) {
12001                        PersistentPreferredActivity ppa = removed.get(j);
12002                        ppir.removeFilter(ppa);
12003                    }
12004                    changed = true;
12005                }
12006            }
12007
12008            if (changed) {
12009                scheduleWritePackageRestrictionsLocked(userId);
12010            }
12011        }
12012    }
12013
12014    @Override
12015    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
12016            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
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        if (intentFilter.countActions() == 0) {
12023            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
12024            return;
12025        }
12026        synchronized (mPackages) {
12027            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
12028                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
12029            CrossProfileIntentResolver resolver =
12030                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12031            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
12032            // We have all those whose filter is equal. Now checking if the rest is equal as well.
12033            if (existing != null) {
12034                int size = existing.size();
12035                for (int i = 0; i < size; i++) {
12036                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
12037                        return;
12038                    }
12039                }
12040            }
12041            resolver.addFilter(newFilter);
12042            scheduleWritePackageRestrictionsLocked(sourceUserId);
12043        }
12044    }
12045
12046    @Override
12047    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
12048            int ownerUserId) {
12049        mContext.enforceCallingOrSelfPermission(
12050                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12051        int callingUid = Binder.getCallingUid();
12052        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
12053        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12054        int callingUserId = UserHandle.getUserId(callingUid);
12055        synchronized (mPackages) {
12056            CrossProfileIntentResolver resolver =
12057                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12058            ArraySet<CrossProfileIntentFilter> set =
12059                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
12060            for (CrossProfileIntentFilter filter : set) {
12061                if (filter.getOwnerPackage().equals(ownerPackage)
12062                        && filter.getOwnerUserId() == callingUserId) {
12063                    resolver.removeFilter(filter);
12064                }
12065            }
12066            scheduleWritePackageRestrictionsLocked(sourceUserId);
12067        }
12068    }
12069
12070    // Enforcing that callingUid is owning pkg on userId
12071    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
12072        // The system owns everything.
12073        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
12074            return;
12075        }
12076        int callingUserId = UserHandle.getUserId(callingUid);
12077        if (callingUserId != userId) {
12078            throw new SecurityException("calling uid " + callingUid
12079                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
12080                    + callingUserId);
12081        }
12082        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
12083        if (pi == null) {
12084            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
12085                    + callingUserId);
12086        }
12087        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
12088            throw new SecurityException("Calling uid " + callingUid
12089                    + " does not own package " + pkg);
12090        }
12091    }
12092
12093    @Override
12094    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
12095        Intent intent = new Intent(Intent.ACTION_MAIN);
12096        intent.addCategory(Intent.CATEGORY_HOME);
12097
12098        final int callingUserId = UserHandle.getCallingUserId();
12099        List<ResolveInfo> list = queryIntentActivities(intent, null,
12100                PackageManager.GET_META_DATA, callingUserId);
12101        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
12102                true, false, false, callingUserId);
12103
12104        allHomeCandidates.clear();
12105        if (list != null) {
12106            for (ResolveInfo ri : list) {
12107                allHomeCandidates.add(ri);
12108            }
12109        }
12110        return (preferred == null || preferred.activityInfo == null)
12111                ? null
12112                : new ComponentName(preferred.activityInfo.packageName,
12113                        preferred.activityInfo.name);
12114    }
12115
12116    @Override
12117    public void setApplicationEnabledSetting(String appPackageName,
12118            int newState, int flags, int userId, String callingPackage) {
12119        if (!sUserManager.exists(userId)) return;
12120        if (callingPackage == null) {
12121            callingPackage = Integer.toString(Binder.getCallingUid());
12122        }
12123        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
12124    }
12125
12126    @Override
12127    public void setComponentEnabledSetting(ComponentName componentName,
12128            int newState, int flags, int userId) {
12129        if (!sUserManager.exists(userId)) return;
12130        setEnabledSetting(componentName.getPackageName(),
12131                componentName.getClassName(), newState, flags, userId, null);
12132    }
12133
12134    private void setEnabledSetting(final String packageName, String className, int newState,
12135            final int flags, int userId, String callingPackage) {
12136        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
12137              || newState == COMPONENT_ENABLED_STATE_ENABLED
12138              || newState == COMPONENT_ENABLED_STATE_DISABLED
12139              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
12140              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
12141            throw new IllegalArgumentException("Invalid new component state: "
12142                    + newState);
12143        }
12144        PackageSetting pkgSetting;
12145        final int uid = Binder.getCallingUid();
12146        final int permission = mContext.checkCallingOrSelfPermission(
12147                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12148        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
12149        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12150        boolean sendNow = false;
12151        boolean isApp = (className == null);
12152        String componentName = isApp ? packageName : className;
12153        int packageUid = -1;
12154        ArrayList<String> components;
12155
12156        // writer
12157        synchronized (mPackages) {
12158            pkgSetting = mSettings.mPackages.get(packageName);
12159            if (pkgSetting == null) {
12160                if (className == null) {
12161                    throw new IllegalArgumentException(
12162                            "Unknown package: " + packageName);
12163                }
12164                throw new IllegalArgumentException(
12165                        "Unknown component: " + packageName
12166                        + "/" + className);
12167            }
12168            // Allow root and verify that userId is not being specified by a different user
12169            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
12170                throw new SecurityException(
12171                        "Permission Denial: attempt to change component state from pid="
12172                        + Binder.getCallingPid()
12173                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
12174            }
12175            if (className == null) {
12176                // We're dealing with an application/package level state change
12177                if (pkgSetting.getEnabled(userId) == newState) {
12178                    // Nothing to do
12179                    return;
12180                }
12181                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
12182                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
12183                    // Don't care about who enables an app.
12184                    callingPackage = null;
12185                }
12186                pkgSetting.setEnabled(newState, userId, callingPackage);
12187                // pkgSetting.pkg.mSetEnabled = newState;
12188            } else {
12189                // We're dealing with a component level state change
12190                // First, verify that this is a valid class name.
12191                PackageParser.Package pkg = pkgSetting.pkg;
12192                if (pkg == null || !pkg.hasComponentClassName(className)) {
12193                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
12194                        throw new IllegalArgumentException("Component class " + className
12195                                + " does not exist in " + packageName);
12196                    } else {
12197                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
12198                                + className + " does not exist in " + packageName);
12199                    }
12200                }
12201                switch (newState) {
12202                case COMPONENT_ENABLED_STATE_ENABLED:
12203                    if (!pkgSetting.enableComponentLPw(className, userId)) {
12204                        return;
12205                    }
12206                    break;
12207                case COMPONENT_ENABLED_STATE_DISABLED:
12208                    if (!pkgSetting.disableComponentLPw(className, userId)) {
12209                        return;
12210                    }
12211                    break;
12212                case COMPONENT_ENABLED_STATE_DEFAULT:
12213                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
12214                        return;
12215                    }
12216                    break;
12217                default:
12218                    Slog.e(TAG, "Invalid new component state: " + newState);
12219                    return;
12220                }
12221            }
12222            mSettings.writePackageRestrictionsLPr(userId);
12223            components = mPendingBroadcasts.get(userId, packageName);
12224            final boolean newPackage = components == null;
12225            if (newPackage) {
12226                components = new ArrayList<String>();
12227            }
12228            if (!components.contains(componentName)) {
12229                components.add(componentName);
12230            }
12231            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12232                sendNow = true;
12233                // Purge entry from pending broadcast list if another one exists already
12234                // since we are sending one right away.
12235                mPendingBroadcasts.remove(userId, packageName);
12236            } else {
12237                if (newPackage) {
12238                    mPendingBroadcasts.put(userId, packageName, components);
12239                }
12240                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12241                    // Schedule a message
12242                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12243                }
12244            }
12245        }
12246
12247        long callingId = Binder.clearCallingIdentity();
12248        try {
12249            if (sendNow) {
12250                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12251                sendPackageChangedBroadcast(packageName,
12252                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12253            }
12254        } finally {
12255            Binder.restoreCallingIdentity(callingId);
12256        }
12257    }
12258
12259    private void sendPackageChangedBroadcast(String packageName,
12260            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12261        if (DEBUG_INSTALL)
12262            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12263                    + componentNames);
12264        Bundle extras = new Bundle(4);
12265        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12266        String nameList[] = new String[componentNames.size()];
12267        componentNames.toArray(nameList);
12268        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12269        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12270        extras.putInt(Intent.EXTRA_UID, packageUid);
12271        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12272                new int[] {UserHandle.getUserId(packageUid)});
12273    }
12274
12275    @Override
12276    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12277        if (!sUserManager.exists(userId)) return;
12278        final int uid = Binder.getCallingUid();
12279        final int permission = mContext.checkCallingOrSelfPermission(
12280                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12281        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12282        enforceCrossUserPermission(uid, userId, true, true, "stop package");
12283        // writer
12284        synchronized (mPackages) {
12285            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12286                    uid, userId)) {
12287                scheduleWritePackageRestrictionsLocked(userId);
12288            }
12289        }
12290    }
12291
12292    @Override
12293    public String getInstallerPackageName(String packageName) {
12294        // reader
12295        synchronized (mPackages) {
12296            return mSettings.getInstallerPackageNameLPr(packageName);
12297        }
12298    }
12299
12300    @Override
12301    public int getApplicationEnabledSetting(String packageName, int userId) {
12302        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12303        int uid = Binder.getCallingUid();
12304        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
12305        // reader
12306        synchronized (mPackages) {
12307            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12308        }
12309    }
12310
12311    @Override
12312    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12313        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12314        int uid = Binder.getCallingUid();
12315        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
12316        // reader
12317        synchronized (mPackages) {
12318            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12319        }
12320    }
12321
12322    @Override
12323    public void enterSafeMode() {
12324        enforceSystemOrRoot("Only the system can request entering safe mode");
12325
12326        if (!mSystemReady) {
12327            mSafeMode = true;
12328        }
12329    }
12330
12331    @Override
12332    public void systemReady() {
12333        mSystemReady = true;
12334
12335        // Read the compatibilty setting when the system is ready.
12336        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12337                mContext.getContentResolver(),
12338                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12339        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12340        if (DEBUG_SETTINGS) {
12341            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12342        }
12343
12344        synchronized (mPackages) {
12345            // Verify that all of the preferred activity components actually
12346            // exist.  It is possible for applications to be updated and at
12347            // that point remove a previously declared activity component that
12348            // had been set as a preferred activity.  We try to clean this up
12349            // the next time we encounter that preferred activity, but it is
12350            // possible for the user flow to never be able to return to that
12351            // situation so here we do a sanity check to make sure we haven't
12352            // left any junk around.
12353            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12354            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12355                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12356                removed.clear();
12357                for (PreferredActivity pa : pir.filterSet()) {
12358                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12359                        removed.add(pa);
12360                    }
12361                }
12362                if (removed.size() > 0) {
12363                    for (int r=0; r<removed.size(); r++) {
12364                        PreferredActivity pa = removed.get(r);
12365                        Slog.w(TAG, "Removing dangling preferred activity: "
12366                                + pa.mPref.mComponent);
12367                        pir.removeFilter(pa);
12368                    }
12369                    mSettings.writePackageRestrictionsLPr(
12370                            mSettings.mPreferredActivities.keyAt(i));
12371                }
12372            }
12373        }
12374        sUserManager.systemReady();
12375
12376        // Kick off any messages waiting for system ready
12377        if (mPostSystemReadyMessages != null) {
12378            for (Message msg : mPostSystemReadyMessages) {
12379                msg.sendToTarget();
12380            }
12381            mPostSystemReadyMessages = null;
12382        }
12383    }
12384
12385    @Override
12386    public boolean isSafeMode() {
12387        return mSafeMode;
12388    }
12389
12390    @Override
12391    public boolean hasSystemUidErrors() {
12392        return mHasSystemUidErrors;
12393    }
12394
12395    static String arrayToString(int[] array) {
12396        StringBuffer buf = new StringBuffer(128);
12397        buf.append('[');
12398        if (array != null) {
12399            for (int i=0; i<array.length; i++) {
12400                if (i > 0) buf.append(", ");
12401                buf.append(array[i]);
12402            }
12403        }
12404        buf.append(']');
12405        return buf.toString();
12406    }
12407
12408    static class DumpState {
12409        public static final int DUMP_LIBS = 1 << 0;
12410        public static final int DUMP_FEATURES = 1 << 1;
12411        public static final int DUMP_RESOLVERS = 1 << 2;
12412        public static final int DUMP_PERMISSIONS = 1 << 3;
12413        public static final int DUMP_PACKAGES = 1 << 4;
12414        public static final int DUMP_SHARED_USERS = 1 << 5;
12415        public static final int DUMP_MESSAGES = 1 << 6;
12416        public static final int DUMP_PROVIDERS = 1 << 7;
12417        public static final int DUMP_VERIFIERS = 1 << 8;
12418        public static final int DUMP_PREFERRED = 1 << 9;
12419        public static final int DUMP_PREFERRED_XML = 1 << 10;
12420        public static final int DUMP_KEYSETS = 1 << 11;
12421        public static final int DUMP_VERSION = 1 << 12;
12422        public static final int DUMP_INSTALLS = 1 << 13;
12423
12424        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12425
12426        private int mTypes;
12427
12428        private int mOptions;
12429
12430        private boolean mTitlePrinted;
12431
12432        private SharedUserSetting mSharedUser;
12433
12434        public boolean isDumping(int type) {
12435            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12436                return true;
12437            }
12438
12439            return (mTypes & type) != 0;
12440        }
12441
12442        public void setDump(int type) {
12443            mTypes |= type;
12444        }
12445
12446        public boolean isOptionEnabled(int option) {
12447            return (mOptions & option) != 0;
12448        }
12449
12450        public void setOptionEnabled(int option) {
12451            mOptions |= option;
12452        }
12453
12454        public boolean onTitlePrinted() {
12455            final boolean printed = mTitlePrinted;
12456            mTitlePrinted = true;
12457            return printed;
12458        }
12459
12460        public boolean getTitlePrinted() {
12461            return mTitlePrinted;
12462        }
12463
12464        public void setTitlePrinted(boolean enabled) {
12465            mTitlePrinted = enabled;
12466        }
12467
12468        public SharedUserSetting getSharedUser() {
12469            return mSharedUser;
12470        }
12471
12472        public void setSharedUser(SharedUserSetting user) {
12473            mSharedUser = user;
12474        }
12475    }
12476
12477    @Override
12478    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12479        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12480                != PackageManager.PERMISSION_GRANTED) {
12481            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12482                    + Binder.getCallingPid()
12483                    + ", uid=" + Binder.getCallingUid()
12484                    + " without permission "
12485                    + android.Manifest.permission.DUMP);
12486            return;
12487        }
12488
12489        DumpState dumpState = new DumpState();
12490        boolean fullPreferred = false;
12491        boolean checkin = false;
12492
12493        String packageName = null;
12494
12495        int opti = 0;
12496        while (opti < args.length) {
12497            String opt = args[opti];
12498            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12499                break;
12500            }
12501            opti++;
12502
12503            if ("-a".equals(opt)) {
12504                // Right now we only know how to print all.
12505            } else if ("-h".equals(opt)) {
12506                pw.println("Package manager dump options:");
12507                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12508                pw.println("    --checkin: dump for a checkin");
12509                pw.println("    -f: print details of intent filters");
12510                pw.println("    -h: print this help");
12511                pw.println("  cmd may be one of:");
12512                pw.println("    l[ibraries]: list known shared libraries");
12513                pw.println("    f[ibraries]: list device features");
12514                pw.println("    k[eysets]: print known keysets");
12515                pw.println("    r[esolvers]: dump intent resolvers");
12516                pw.println("    perm[issions]: dump permissions");
12517                pw.println("    pref[erred]: print preferred package settings");
12518                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12519                pw.println("    prov[iders]: dump content providers");
12520                pw.println("    p[ackages]: dump installed packages");
12521                pw.println("    s[hared-users]: dump shared user IDs");
12522                pw.println("    m[essages]: print collected runtime messages");
12523                pw.println("    v[erifiers]: print package verifier info");
12524                pw.println("    version: print database version info");
12525                pw.println("    write: write current settings now");
12526                pw.println("    <package.name>: info about given package");
12527                pw.println("    installs: details about install sessions");
12528                return;
12529            } else if ("--checkin".equals(opt)) {
12530                checkin = true;
12531            } else if ("-f".equals(opt)) {
12532                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12533            } else {
12534                pw.println("Unknown argument: " + opt + "; use -h for help");
12535            }
12536        }
12537
12538        // Is the caller requesting to dump a particular piece of data?
12539        if (opti < args.length) {
12540            String cmd = args[opti];
12541            opti++;
12542            // Is this a package name?
12543            if ("android".equals(cmd) || cmd.contains(".")) {
12544                packageName = cmd;
12545                // When dumping a single package, we always dump all of its
12546                // filter information since the amount of data will be reasonable.
12547                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12548            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12549                dumpState.setDump(DumpState.DUMP_LIBS);
12550            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12551                dumpState.setDump(DumpState.DUMP_FEATURES);
12552            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12553                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12554            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12555                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12556            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12557                dumpState.setDump(DumpState.DUMP_PREFERRED);
12558            } else if ("preferred-xml".equals(cmd)) {
12559                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12560                if (opti < args.length && "--full".equals(args[opti])) {
12561                    fullPreferred = true;
12562                    opti++;
12563                }
12564            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12565                dumpState.setDump(DumpState.DUMP_PACKAGES);
12566            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12567                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12568            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12569                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12570            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12571                dumpState.setDump(DumpState.DUMP_MESSAGES);
12572            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12573                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12574            } else if ("version".equals(cmd)) {
12575                dumpState.setDump(DumpState.DUMP_VERSION);
12576            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12577                dumpState.setDump(DumpState.DUMP_KEYSETS);
12578            } else if ("installs".equals(cmd)) {
12579                dumpState.setDump(DumpState.DUMP_INSTALLS);
12580            } else if ("write".equals(cmd)) {
12581                synchronized (mPackages) {
12582                    mSettings.writeLPr();
12583                    pw.println("Settings written.");
12584                    return;
12585                }
12586            }
12587        }
12588
12589        if (checkin) {
12590            pw.println("vers,1");
12591        }
12592
12593        // reader
12594        synchronized (mPackages) {
12595            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12596                if (!checkin) {
12597                    if (dumpState.onTitlePrinted())
12598                        pw.println();
12599                    pw.println("Database versions:");
12600                    pw.print("  SDK Version:");
12601                    pw.print(" internal=");
12602                    pw.print(mSettings.mInternalSdkPlatform);
12603                    pw.print(" external=");
12604                    pw.println(mSettings.mExternalSdkPlatform);
12605                    pw.print("  DB Version:");
12606                    pw.print(" internal=");
12607                    pw.print(mSettings.mInternalDatabaseVersion);
12608                    pw.print(" external=");
12609                    pw.println(mSettings.mExternalDatabaseVersion);
12610                }
12611            }
12612
12613            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12614                if (!checkin) {
12615                    if (dumpState.onTitlePrinted())
12616                        pw.println();
12617                    pw.println("Verifiers:");
12618                    pw.print("  Required: ");
12619                    pw.print(mRequiredVerifierPackage);
12620                    pw.print(" (uid=");
12621                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12622                    pw.println(")");
12623                } else if (mRequiredVerifierPackage != null) {
12624                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12625                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12626                }
12627            }
12628
12629            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12630                boolean printedHeader = false;
12631                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12632                while (it.hasNext()) {
12633                    String name = it.next();
12634                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12635                    if (!checkin) {
12636                        if (!printedHeader) {
12637                            if (dumpState.onTitlePrinted())
12638                                pw.println();
12639                            pw.println("Libraries:");
12640                            printedHeader = true;
12641                        }
12642                        pw.print("  ");
12643                    } else {
12644                        pw.print("lib,");
12645                    }
12646                    pw.print(name);
12647                    if (!checkin) {
12648                        pw.print(" -> ");
12649                    }
12650                    if (ent.path != null) {
12651                        if (!checkin) {
12652                            pw.print("(jar) ");
12653                            pw.print(ent.path);
12654                        } else {
12655                            pw.print(",jar,");
12656                            pw.print(ent.path);
12657                        }
12658                    } else {
12659                        if (!checkin) {
12660                            pw.print("(apk) ");
12661                            pw.print(ent.apk);
12662                        } else {
12663                            pw.print(",apk,");
12664                            pw.print(ent.apk);
12665                        }
12666                    }
12667                    pw.println();
12668                }
12669            }
12670
12671            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12672                if (dumpState.onTitlePrinted())
12673                    pw.println();
12674                if (!checkin) {
12675                    pw.println("Features:");
12676                }
12677                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12678                while (it.hasNext()) {
12679                    String name = it.next();
12680                    if (!checkin) {
12681                        pw.print("  ");
12682                    } else {
12683                        pw.print("feat,");
12684                    }
12685                    pw.println(name);
12686                }
12687            }
12688
12689            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12690                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12691                        : "Activity Resolver Table:", "  ", packageName,
12692                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12693                    dumpState.setTitlePrinted(true);
12694                }
12695                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12696                        : "Receiver Resolver Table:", "  ", packageName,
12697                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12698                    dumpState.setTitlePrinted(true);
12699                }
12700                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12701                        : "Service Resolver Table:", "  ", packageName,
12702                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12703                    dumpState.setTitlePrinted(true);
12704                }
12705                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12706                        : "Provider Resolver Table:", "  ", packageName,
12707                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12708                    dumpState.setTitlePrinted(true);
12709                }
12710            }
12711
12712            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12713                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12714                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12715                    int user = mSettings.mPreferredActivities.keyAt(i);
12716                    if (pir.dump(pw,
12717                            dumpState.getTitlePrinted()
12718                                ? "\nPreferred Activities User " + user + ":"
12719                                : "Preferred Activities User " + user + ":", "  ",
12720                            packageName, true, false)) {
12721                        dumpState.setTitlePrinted(true);
12722                    }
12723                }
12724            }
12725
12726            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12727                pw.flush();
12728                FileOutputStream fout = new FileOutputStream(fd);
12729                BufferedOutputStream str = new BufferedOutputStream(fout);
12730                XmlSerializer serializer = new FastXmlSerializer();
12731                try {
12732                    serializer.setOutput(str, "utf-8");
12733                    serializer.startDocument(null, true);
12734                    serializer.setFeature(
12735                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12736                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12737                    serializer.endDocument();
12738                    serializer.flush();
12739                } catch (IllegalArgumentException e) {
12740                    pw.println("Failed writing: " + e);
12741                } catch (IllegalStateException e) {
12742                    pw.println("Failed writing: " + e);
12743                } catch (IOException e) {
12744                    pw.println("Failed writing: " + e);
12745                }
12746            }
12747
12748            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12749                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12750                if (packageName == null) {
12751                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12752                        if (iperm == 0) {
12753                            if (dumpState.onTitlePrinted())
12754                                pw.println();
12755                            pw.println("AppOp Permissions:");
12756                        }
12757                        pw.print("  AppOp Permission ");
12758                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12759                        pw.println(":");
12760                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12761                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12762                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12763                        }
12764                    }
12765                }
12766            }
12767
12768            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12769                boolean printedSomething = false;
12770                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12771                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12772                        continue;
12773                    }
12774                    if (!printedSomething) {
12775                        if (dumpState.onTitlePrinted())
12776                            pw.println();
12777                        pw.println("Registered ContentProviders:");
12778                        printedSomething = true;
12779                    }
12780                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12781                    pw.print("    "); pw.println(p.toString());
12782                }
12783                printedSomething = false;
12784                for (Map.Entry<String, PackageParser.Provider> entry :
12785                        mProvidersByAuthority.entrySet()) {
12786                    PackageParser.Provider p = entry.getValue();
12787                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12788                        continue;
12789                    }
12790                    if (!printedSomething) {
12791                        if (dumpState.onTitlePrinted())
12792                            pw.println();
12793                        pw.println("ContentProvider Authorities:");
12794                        printedSomething = true;
12795                    }
12796                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12797                    pw.print("    "); pw.println(p.toString());
12798                    if (p.info != null && p.info.applicationInfo != null) {
12799                        final String appInfo = p.info.applicationInfo.toString();
12800                        pw.print("      applicationInfo="); pw.println(appInfo);
12801                    }
12802                }
12803            }
12804
12805            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12806                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12807            }
12808
12809            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12810                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12811            }
12812
12813            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12814                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
12815            }
12816
12817            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12818                // XXX should handle packageName != null by dumping only install data that
12819                // the given package is involved with.
12820                if (dumpState.onTitlePrinted()) pw.println();
12821                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12822            }
12823
12824            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12825                if (dumpState.onTitlePrinted()) pw.println();
12826                mSettings.dumpReadMessagesLPr(pw, dumpState);
12827
12828                pw.println();
12829                pw.println("Package warning messages:");
12830                BufferedReader in = null;
12831                String line = null;
12832                try {
12833                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12834                    while ((line = in.readLine()) != null) {
12835                        if (line.contains("ignored: updated version")) continue;
12836                        pw.println(line);
12837                    }
12838                } catch (IOException ignored) {
12839                } finally {
12840                    IoUtils.closeQuietly(in);
12841                }
12842            }
12843
12844            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
12845                BufferedReader in = null;
12846                String line = null;
12847                try {
12848                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12849                    while ((line = in.readLine()) != null) {
12850                        if (line.contains("ignored: updated version")) continue;
12851                        pw.print("msg,");
12852                        pw.println(line);
12853                    }
12854                } catch (IOException ignored) {
12855                } finally {
12856                    IoUtils.closeQuietly(in);
12857                }
12858            }
12859        }
12860    }
12861
12862    // ------- apps on sdcard specific code -------
12863    static final boolean DEBUG_SD_INSTALL = false;
12864
12865    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12866
12867    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12868
12869    private boolean mMediaMounted = false;
12870
12871    static String getEncryptKey() {
12872        try {
12873            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12874                    SD_ENCRYPTION_KEYSTORE_NAME);
12875            if (sdEncKey == null) {
12876                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12877                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12878                if (sdEncKey == null) {
12879                    Slog.e(TAG, "Failed to create encryption keys");
12880                    return null;
12881                }
12882            }
12883            return sdEncKey;
12884        } catch (NoSuchAlgorithmException nsae) {
12885            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12886            return null;
12887        } catch (IOException ioe) {
12888            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12889            return null;
12890        }
12891    }
12892
12893    /*
12894     * Update media status on PackageManager.
12895     */
12896    @Override
12897    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12898        int callingUid = Binder.getCallingUid();
12899        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12900            throw new SecurityException("Media status can only be updated by the system");
12901        }
12902        // reader; this apparently protects mMediaMounted, but should probably
12903        // be a different lock in that case.
12904        synchronized (mPackages) {
12905            Log.i(TAG, "Updating external media status from "
12906                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12907                    + (mediaStatus ? "mounted" : "unmounted"));
12908            if (DEBUG_SD_INSTALL)
12909                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12910                        + ", mMediaMounted=" + mMediaMounted);
12911            if (mediaStatus == mMediaMounted) {
12912                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12913                        : 0, -1);
12914                mHandler.sendMessage(msg);
12915                return;
12916            }
12917            mMediaMounted = mediaStatus;
12918        }
12919        // Queue up an async operation since the package installation may take a
12920        // little while.
12921        mHandler.post(new Runnable() {
12922            public void run() {
12923                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12924            }
12925        });
12926    }
12927
12928    /**
12929     * Called by MountService when the initial ASECs to scan are available.
12930     * Should block until all the ASEC containers are finished being scanned.
12931     */
12932    public void scanAvailableAsecs() {
12933        updateExternalMediaStatusInner(true, false, false);
12934        if (mShouldRestoreconData) {
12935            SELinuxMMAC.setRestoreconDone();
12936            mShouldRestoreconData = false;
12937        }
12938    }
12939
12940    /*
12941     * Collect information of applications on external media, map them against
12942     * existing containers and update information based on current mount status.
12943     * Please note that we always have to report status if reportStatus has been
12944     * set to true especially when unloading packages.
12945     */
12946    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12947            boolean externalStorage) {
12948        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12949        int[] uidArr = EmptyArray.INT;
12950
12951        final String[] list = PackageHelper.getSecureContainerList();
12952        if (ArrayUtils.isEmpty(list)) {
12953            Log.i(TAG, "No secure containers found");
12954        } else {
12955            // Process list of secure containers and categorize them
12956            // as active or stale based on their package internal state.
12957
12958            // reader
12959            synchronized (mPackages) {
12960                for (String cid : list) {
12961                    // Leave stages untouched for now; installer service owns them
12962                    if (PackageInstallerService.isStageName(cid)) continue;
12963
12964                    if (DEBUG_SD_INSTALL)
12965                        Log.i(TAG, "Processing container " + cid);
12966                    String pkgName = getAsecPackageName(cid);
12967                    if (pkgName == null) {
12968                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12969                        continue;
12970                    }
12971                    if (DEBUG_SD_INSTALL)
12972                        Log.i(TAG, "Looking for pkg : " + pkgName);
12973
12974                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12975                    if (ps == null) {
12976                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12977                        continue;
12978                    }
12979
12980                    /*
12981                     * Skip packages that are not external if we're unmounting
12982                     * external storage.
12983                     */
12984                    if (externalStorage && !isMounted && !isExternal(ps)) {
12985                        continue;
12986                    }
12987
12988                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12989                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12990                    // The package status is changed only if the code path
12991                    // matches between settings and the container id.
12992                    if (ps.codePathString != null
12993                            && ps.codePathString.startsWith(args.getCodePath())) {
12994                        if (DEBUG_SD_INSTALL) {
12995                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12996                                    + " at code path: " + ps.codePathString);
12997                        }
12998
12999                        // We do have a valid package installed on sdcard
13000                        processCids.put(args, ps.codePathString);
13001                        final int uid = ps.appId;
13002                        if (uid != -1) {
13003                            uidArr = ArrayUtils.appendInt(uidArr, uid);
13004                        }
13005                    } else {
13006                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
13007                                + ps.codePathString);
13008                    }
13009                }
13010            }
13011
13012            Arrays.sort(uidArr);
13013        }
13014
13015        // Process packages with valid entries.
13016        if (isMounted) {
13017            if (DEBUG_SD_INSTALL)
13018                Log.i(TAG, "Loading packages");
13019            loadMediaPackages(processCids, uidArr);
13020            startCleaningPackages();
13021            mInstallerService.onSecureContainersAvailable();
13022        } else {
13023            if (DEBUG_SD_INSTALL)
13024                Log.i(TAG, "Unloading packages");
13025            unloadMediaPackages(processCids, uidArr, reportStatus);
13026        }
13027    }
13028
13029    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13030            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13031        int size = pkgList.size();
13032        if (size > 0) {
13033            // Send broadcasts here
13034            Bundle extras = new Bundle();
13035            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
13036                    .toArray(new String[size]));
13037            if (uidArr != null) {
13038                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
13039            }
13040            if (replacing) {
13041                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
13042            }
13043            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
13044                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
13045            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
13046        }
13047    }
13048
13049   /*
13050     * Look at potentially valid container ids from processCids If package
13051     * information doesn't match the one on record or package scanning fails,
13052     * the cid is added to list of removeCids. We currently don't delete stale
13053     * containers.
13054     */
13055    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
13056        ArrayList<String> pkgList = new ArrayList<String>();
13057        Set<AsecInstallArgs> keys = processCids.keySet();
13058
13059        for (AsecInstallArgs args : keys) {
13060            String codePath = processCids.get(args);
13061            if (DEBUG_SD_INSTALL)
13062                Log.i(TAG, "Loading container : " + args.cid);
13063            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13064            try {
13065                // Make sure there are no container errors first.
13066                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
13067                    Slog.e(TAG, "Failed to mount cid : " + args.cid
13068                            + " when installing from sdcard");
13069                    continue;
13070                }
13071                // Check code path here.
13072                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
13073                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
13074                            + " does not match one in settings " + codePath);
13075                    continue;
13076                }
13077                // Parse package
13078                int parseFlags = mDefParseFlags;
13079                if (args.isExternal()) {
13080                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
13081                }
13082                if (args.isFwdLocked()) {
13083                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
13084                }
13085
13086                synchronized (mInstallLock) {
13087                    PackageParser.Package pkg = null;
13088                    try {
13089                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
13090                    } catch (PackageManagerException e) {
13091                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
13092                    }
13093                    // Scan the package
13094                    if (pkg != null) {
13095                        /*
13096                         * TODO why is the lock being held? doPostInstall is
13097                         * called in other places without the lock. This needs
13098                         * to be straightened out.
13099                         */
13100                        // writer
13101                        synchronized (mPackages) {
13102                            retCode = PackageManager.INSTALL_SUCCEEDED;
13103                            pkgList.add(pkg.packageName);
13104                            // Post process args
13105                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
13106                                    pkg.applicationInfo.uid);
13107                        }
13108                    } else {
13109                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
13110                    }
13111                }
13112
13113            } finally {
13114                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
13115                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
13116                }
13117            }
13118        }
13119        // writer
13120        synchronized (mPackages) {
13121            // If the platform SDK has changed since the last time we booted,
13122            // we need to re-grant app permission to catch any new ones that
13123            // appear. This is really a hack, and means that apps can in some
13124            // cases get permissions that the user didn't initially explicitly
13125            // allow... it would be nice to have some better way to handle
13126            // this situation.
13127            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
13128            if (regrantPermissions)
13129                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
13130                        + mSdkVersion + "; regranting permissions for external storage");
13131            mSettings.mExternalSdkPlatform = mSdkVersion;
13132
13133            // Make sure group IDs have been assigned, and any permission
13134            // changes in other apps are accounted for
13135            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
13136                    | (regrantPermissions
13137                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
13138                            : 0));
13139
13140            mSettings.updateExternalDatabaseVersion();
13141
13142            // can downgrade to reader
13143            // Persist settings
13144            mSettings.writeLPr();
13145        }
13146        // Send a broadcast to let everyone know we are done processing
13147        if (pkgList.size() > 0) {
13148            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13149        }
13150    }
13151
13152   /*
13153     * Utility method to unload a list of specified containers
13154     */
13155    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
13156        // Just unmount all valid containers.
13157        for (AsecInstallArgs arg : cidArgs) {
13158            synchronized (mInstallLock) {
13159                arg.doPostDeleteLI(false);
13160           }
13161       }
13162   }
13163
13164    /*
13165     * Unload packages mounted on external media. This involves deleting package
13166     * data from internal structures, sending broadcasts about diabled packages,
13167     * gc'ing to free up references, unmounting all secure containers
13168     * corresponding to packages on external media, and posting a
13169     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
13170     * that we always have to post this message if status has been requested no
13171     * matter what.
13172     */
13173    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
13174            final boolean reportStatus) {
13175        if (DEBUG_SD_INSTALL)
13176            Log.i(TAG, "unloading media packages");
13177        ArrayList<String> pkgList = new ArrayList<String>();
13178        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
13179        final Set<AsecInstallArgs> keys = processCids.keySet();
13180        for (AsecInstallArgs args : keys) {
13181            String pkgName = args.getPackageName();
13182            if (DEBUG_SD_INSTALL)
13183                Log.i(TAG, "Trying to unload pkg : " + pkgName);
13184            // Delete package internally
13185            PackageRemovedInfo outInfo = new PackageRemovedInfo();
13186            synchronized (mInstallLock) {
13187                boolean res = deletePackageLI(pkgName, null, false, null, null,
13188                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
13189                if (res) {
13190                    pkgList.add(pkgName);
13191                } else {
13192                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
13193                    failedList.add(args);
13194                }
13195            }
13196        }
13197
13198        // reader
13199        synchronized (mPackages) {
13200            // We didn't update the settings after removing each package;
13201            // write them now for all packages.
13202            mSettings.writeLPr();
13203        }
13204
13205        // We have to absolutely send UPDATED_MEDIA_STATUS only
13206        // after confirming that all the receivers processed the ordered
13207        // broadcast when packages get disabled, force a gc to clean things up.
13208        // and unload all the containers.
13209        if (pkgList.size() > 0) {
13210            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
13211                    new IIntentReceiver.Stub() {
13212                public void performReceive(Intent intent, int resultCode, String data,
13213                        Bundle extras, boolean ordered, boolean sticky,
13214                        int sendingUser) throws RemoteException {
13215                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
13216                            reportStatus ? 1 : 0, 1, keys);
13217                    mHandler.sendMessage(msg);
13218                }
13219            });
13220        } else {
13221            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
13222                    keys);
13223            mHandler.sendMessage(msg);
13224        }
13225    }
13226
13227    /** Binder call */
13228    @Override
13229    public void movePackage(final String packageName, final IPackageMoveObserver observer,
13230            final int flags) {
13231        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
13232        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
13233        int returnCode = PackageManager.MOVE_SUCCEEDED;
13234        int currInstallFlags = 0;
13235        int newInstallFlags = 0;
13236
13237        File codeFile = null;
13238        String installerPackageName = null;
13239        String packageAbiOverride = null;
13240
13241        // reader
13242        synchronized (mPackages) {
13243            final PackageParser.Package pkg = mPackages.get(packageName);
13244            final PackageSetting ps = mSettings.mPackages.get(packageName);
13245            if (pkg == null || ps == null) {
13246                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13247            } else {
13248                // Disable moving fwd locked apps and system packages
13249                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
13250                    Slog.w(TAG, "Cannot move system application");
13251                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
13252                } else if (pkg.mOperationPending) {
13253                    Slog.w(TAG, "Attempt to move package which has pending operations");
13254                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
13255                } else {
13256                    // Find install location first
13257                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13258                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13259                        Slog.w(TAG, "Ambigous flags specified for move location.");
13260                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13261                    } else {
13262                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13263                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13264                        currInstallFlags = isExternal(pkg)
13265                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13266
13267                        if (newInstallFlags == currInstallFlags) {
13268                            Slog.w(TAG, "No move required. Trying to move to same location");
13269                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13270                        } else {
13271                            if (isForwardLocked(pkg)) {
13272                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13273                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13274                            }
13275                        }
13276                    }
13277                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13278                        pkg.mOperationPending = true;
13279                    }
13280                }
13281
13282                codeFile = new File(pkg.codePath);
13283                installerPackageName = ps.installerPackageName;
13284                packageAbiOverride = ps.cpuAbiOverrideString;
13285            }
13286        }
13287
13288        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13289            try {
13290                observer.packageMoved(packageName, returnCode);
13291            } catch (RemoteException ignored) {
13292            }
13293            return;
13294        }
13295
13296        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
13297            @Override
13298            public void onUserActionRequired(Intent intent) throws RemoteException {
13299                throw new IllegalStateException();
13300            }
13301
13302            @Override
13303            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
13304                    Bundle extras) throws RemoteException {
13305                Slog.d(TAG, "Install result for move: "
13306                        + PackageManager.installStatusToString(returnCode, msg));
13307
13308                // We usually have a new package now after the install, but if
13309                // we failed we need to clear the pending flag on the original
13310                // package object.
13311                synchronized (mPackages) {
13312                    final PackageParser.Package pkg = mPackages.get(packageName);
13313                    if (pkg != null) {
13314                        pkg.mOperationPending = false;
13315                    }
13316                }
13317
13318                final int status = PackageManager.installStatusToPublicStatus(returnCode);
13319                switch (status) {
13320                    case PackageInstaller.STATUS_SUCCESS:
13321                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
13322                        break;
13323                    case PackageInstaller.STATUS_FAILURE_STORAGE:
13324                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
13325                        break;
13326                    default:
13327                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
13328                        break;
13329                }
13330            }
13331        };
13332
13333        // Treat a move like reinstalling an existing app, which ensures that we
13334        // process everythign uniformly, like unpacking native libraries.
13335        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
13336
13337        final Message msg = mHandler.obtainMessage(INIT_COPY);
13338        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
13339        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
13340                installerPackageName, null, user, packageAbiOverride);
13341        mHandler.sendMessage(msg);
13342    }
13343
13344    @Override
13345    public boolean setInstallLocation(int loc) {
13346        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13347                null);
13348        if (getInstallLocation() == loc) {
13349            return true;
13350        }
13351        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13352                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13353            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13354                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13355            return true;
13356        }
13357        return false;
13358   }
13359
13360    @Override
13361    public int getInstallLocation() {
13362        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13363                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13364                PackageHelper.APP_INSTALL_AUTO);
13365    }
13366
13367    /** Called by UserManagerService */
13368    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13369        mDirtyUsers.remove(userHandle);
13370        mSettings.removeUserLPw(userHandle);
13371        mPendingBroadcasts.remove(userHandle);
13372        if (mInstaller != null) {
13373            // Technically, we shouldn't be doing this with the package lock
13374            // held.  However, this is very rare, and there is already so much
13375            // other disk I/O going on, that we'll let it slide for now.
13376            mInstaller.removeUserDataDirs(userHandle);
13377        }
13378        mUserNeedsBadging.delete(userHandle);
13379        removeUnusedPackagesLILPw(userManager, userHandle);
13380    }
13381
13382    /**
13383     * We're removing userHandle and would like to remove any downloaded packages
13384     * that are no longer in use by any other user.
13385     * @param userHandle the user being removed
13386     */
13387    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13388        final boolean DEBUG_CLEAN_APKS = false;
13389        int [] users = userManager.getUserIdsLPr();
13390        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13391        while (psit.hasNext()) {
13392            PackageSetting ps = psit.next();
13393            if (ps.pkg == null) {
13394                continue;
13395            }
13396            final String packageName = ps.pkg.packageName;
13397            // Skip over if system app
13398            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13399                continue;
13400            }
13401            if (DEBUG_CLEAN_APKS) {
13402                Slog.i(TAG, "Checking package " + packageName);
13403            }
13404            boolean keep = false;
13405            for (int i = 0; i < users.length; i++) {
13406                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13407                    keep = true;
13408                    if (DEBUG_CLEAN_APKS) {
13409                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13410                                + users[i]);
13411                    }
13412                    break;
13413                }
13414            }
13415            if (!keep) {
13416                if (DEBUG_CLEAN_APKS) {
13417                    Slog.i(TAG, "  Removing package " + packageName);
13418                }
13419                mHandler.post(new Runnable() {
13420                    public void run() {
13421                        deletePackageX(packageName, userHandle, 0);
13422                    } //end run
13423                });
13424            }
13425        }
13426    }
13427
13428    /** Called by UserManagerService */
13429    void createNewUserLILPw(int userHandle, File path) {
13430        if (mInstaller != null) {
13431            mInstaller.createUserConfig(userHandle);
13432            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13433        }
13434    }
13435
13436    @Override
13437    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13438        mContext.enforceCallingOrSelfPermission(
13439                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13440                "Only package verification agents can read the verifier device identity");
13441
13442        synchronized (mPackages) {
13443            return mSettings.getVerifierDeviceIdentityLPw();
13444        }
13445    }
13446
13447    @Override
13448    public void setPermissionEnforced(String permission, boolean enforced) {
13449        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13450        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13451            synchronized (mPackages) {
13452                if (mSettings.mReadExternalStorageEnforced == null
13453                        || mSettings.mReadExternalStorageEnforced != enforced) {
13454                    mSettings.mReadExternalStorageEnforced = enforced;
13455                    mSettings.writeLPr();
13456                }
13457            }
13458            // kill any non-foreground processes so we restart them and
13459            // grant/revoke the GID.
13460            final IActivityManager am = ActivityManagerNative.getDefault();
13461            if (am != null) {
13462                final long token = Binder.clearCallingIdentity();
13463                try {
13464                    am.killProcessesBelowForeground("setPermissionEnforcement");
13465                } catch (RemoteException e) {
13466                } finally {
13467                    Binder.restoreCallingIdentity(token);
13468                }
13469            }
13470        } else {
13471            throw new IllegalArgumentException("No selective enforcement for " + permission);
13472        }
13473    }
13474
13475    @Override
13476    @Deprecated
13477    public boolean isPermissionEnforced(String permission) {
13478        return true;
13479    }
13480
13481    @Override
13482    public boolean isStorageLow() {
13483        final long token = Binder.clearCallingIdentity();
13484        try {
13485            final DeviceStorageMonitorInternal
13486                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13487            if (dsm != null) {
13488                return dsm.isMemoryLow();
13489            } else {
13490                return false;
13491            }
13492        } finally {
13493            Binder.restoreCallingIdentity(token);
13494        }
13495    }
13496
13497    @Override
13498    public IPackageInstaller getPackageInstaller() {
13499        return mInstallerService;
13500    }
13501
13502    private boolean userNeedsBadging(int userId) {
13503        int index = mUserNeedsBadging.indexOfKey(userId);
13504        if (index < 0) {
13505            final UserInfo userInfo;
13506            final long token = Binder.clearCallingIdentity();
13507            try {
13508                userInfo = sUserManager.getUserInfo(userId);
13509            } finally {
13510                Binder.restoreCallingIdentity(token);
13511            }
13512            final boolean b;
13513            if (userInfo != null && userInfo.isManagedProfile()) {
13514                b = true;
13515            } else {
13516                b = false;
13517            }
13518            mUserNeedsBadging.put(userId, b);
13519            return b;
13520        }
13521        return mUserNeedsBadging.valueAt(index);
13522    }
13523
13524    @Override
13525    public KeySet getKeySetByAlias(String packageName, String alias) {
13526        if (packageName == null || alias == null) {
13527            return null;
13528        }
13529        synchronized(mPackages) {
13530            final PackageParser.Package pkg = mPackages.get(packageName);
13531            if (pkg == null) {
13532                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13533                throw new IllegalArgumentException("Unknown package: " + packageName);
13534            }
13535            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13536            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13537        }
13538    }
13539
13540    @Override
13541    public KeySet getSigningKeySet(String packageName) {
13542        if (packageName == null) {
13543            return null;
13544        }
13545        synchronized(mPackages) {
13546            final PackageParser.Package pkg = mPackages.get(packageName);
13547            if (pkg == null) {
13548                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13549                throw new IllegalArgumentException("Unknown package: " + packageName);
13550            }
13551            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13552                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13553                throw new SecurityException("May not access signing KeySet of other apps.");
13554            }
13555            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13556            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13557        }
13558    }
13559
13560    @Override
13561    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13562        if (packageName == null || ks == null) {
13563            return false;
13564        }
13565        synchronized(mPackages) {
13566            final PackageParser.Package pkg = mPackages.get(packageName);
13567            if (pkg == null) {
13568                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13569                throw new IllegalArgumentException("Unknown package: " + packageName);
13570            }
13571            IBinder ksh = ks.getToken();
13572            if (ksh instanceof KeySetHandle) {
13573                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13574                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13575            }
13576            return false;
13577        }
13578    }
13579
13580    @Override
13581    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13582        if (packageName == null || ks == null) {
13583            return false;
13584        }
13585        synchronized(mPackages) {
13586            final PackageParser.Package pkg = mPackages.get(packageName);
13587            if (pkg == null) {
13588                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13589                throw new IllegalArgumentException("Unknown package: " + packageName);
13590            }
13591            IBinder ksh = ks.getToken();
13592            if (ksh instanceof KeySetHandle) {
13593                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13594                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13595            }
13596            return false;
13597        }
13598    }
13599
13600    public void getUsageStatsIfNoPackageUsageInfo() {
13601        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
13602            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
13603            if (usm == null) {
13604                throw new IllegalStateException("UsageStatsManager must be initialized");
13605            }
13606            long now = System.currentTimeMillis();
13607            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
13608            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
13609                String packageName = entry.getKey();
13610                PackageParser.Package pkg = mPackages.get(packageName);
13611                if (pkg == null) {
13612                    continue;
13613                }
13614                UsageStats usage = entry.getValue();
13615                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
13616                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
13617            }
13618        }
13619    }
13620
13621    /**
13622     * Check and throw if the given before/after packages would be considered a
13623     * downgrade.
13624     */
13625    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
13626            throws PackageManagerException {
13627        if (after.versionCode < before.mVersionCode) {
13628            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13629                    "Update version code " + after.versionCode + " is older than current "
13630                    + before.mVersionCode);
13631        } else if (after.versionCode == before.mVersionCode) {
13632            if (after.baseRevisionCode < before.baseRevisionCode) {
13633                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13634                        "Update base revision code " + after.baseRevisionCode
13635                        + " is older than current " + before.baseRevisionCode);
13636            }
13637
13638            if (!ArrayUtils.isEmpty(after.splitNames)) {
13639                for (int i = 0; i < after.splitNames.length; i++) {
13640                    final String splitName = after.splitNames[i];
13641                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
13642                    if (j != -1) {
13643                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
13644                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13645                                    "Update split " + splitName + " revision code "
13646                                    + after.splitRevisionCodes[i] + " is older than current "
13647                                    + before.splitRevisionCodes[j]);
13648                        }
13649                    }
13650                }
13651            }
13652        }
13653    }
13654}
13655