PackageManagerService.java revision df890b4df04f77baaa0051b6cc0d92c82acf3aa9
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
46import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
47import static android.content.pm.PackageParser.isApkFile;
48import static android.os.Process.PACKAGE_INFO_GID;
49import static android.os.Process.SYSTEM_UID;
50import static android.system.OsConstants.O_CREAT;
51import static android.system.OsConstants.O_RDWR;
52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
53import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
54import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
55import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
56import static com.android.internal.util.ArrayUtils.appendInt;
57import static com.android.internal.util.ArrayUtils.removeInt;
58
59import android.util.ArrayMap;
60
61import com.android.internal.R;
62import com.android.internal.app.IMediaContainerService;
63import com.android.internal.app.ResolverActivity;
64import com.android.internal.content.NativeLibraryHelper;
65import com.android.internal.content.PackageHelper;
66import com.android.internal.os.IParcelFileDescriptorFactory;
67import com.android.internal.util.ArrayUtils;
68import com.android.internal.util.FastPrintWriter;
69import com.android.internal.util.FastXmlSerializer;
70import com.android.internal.util.IndentingPrintWriter;
71import com.android.server.EventLogTags;
72import com.android.server.IntentResolver;
73import com.android.server.LocalServices;
74import com.android.server.ServiceThread;
75import com.android.server.SystemConfig;
76import com.android.server.Watchdog;
77import com.android.server.pm.Settings.DatabaseVersion;
78import com.android.server.storage.DeviceStorageMonitorInternal;
79
80import org.xmlpull.v1.XmlSerializer;
81
82import android.app.ActivityManager;
83import android.app.ActivityManagerNative;
84import android.app.AppGlobals;
85import android.app.IActivityManager;
86import android.app.admin.IDevicePolicyManager;
87import android.app.backup.IBackupManager;
88import android.app.usage.UsageStats;
89import android.app.usage.UsageStatsManager;
90import android.content.BroadcastReceiver;
91import android.content.ComponentName;
92import android.content.Context;
93import android.content.IIntentReceiver;
94import android.content.Intent;
95import android.content.IntentFilter;
96import android.content.IntentSender;
97import android.content.IntentSender.SendIntentException;
98import android.content.ServiceConnection;
99import android.content.pm.ActivityInfo;
100import android.content.pm.ApplicationInfo;
101import android.content.pm.FeatureInfo;
102import android.content.pm.IPackageDataObserver;
103import android.content.pm.IPackageDeleteObserver;
104import android.content.pm.IPackageDeleteObserver2;
105import android.content.pm.IPackageInstallObserver2;
106import android.content.pm.IPackageInstaller;
107import android.content.pm.IPackageManager;
108import android.content.pm.IPackageMoveObserver;
109import android.content.pm.IPackageStatsObserver;
110import android.content.pm.InstrumentationInfo;
111import android.content.pm.KeySet;
112import android.content.pm.ManifestDigest;
113import android.content.pm.PackageCleanItem;
114import android.content.pm.PackageInfo;
115import android.content.pm.PackageInfoLite;
116import android.content.pm.PackageInstaller;
117import android.content.pm.PackageManager;
118import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
119import android.content.pm.PackageParser.ActivityIntentInfo;
120import android.content.pm.PackageParser.PackageLite;
121import android.content.pm.PackageParser.PackageParserException;
122import android.content.pm.PackageParser;
123import android.content.pm.PackageStats;
124import android.content.pm.PackageUserState;
125import android.content.pm.ParceledListSlice;
126import android.content.pm.PermissionGroupInfo;
127import android.content.pm.PermissionInfo;
128import android.content.pm.ProviderInfo;
129import android.content.pm.ResolveInfo;
130import android.content.pm.ServiceInfo;
131import android.content.pm.Signature;
132import android.content.pm.UserInfo;
133import android.content.pm.VerificationParams;
134import android.content.pm.VerifierDeviceIdentity;
135import android.content.pm.VerifierInfo;
136import android.content.res.Resources;
137import android.hardware.display.DisplayManager;
138import android.net.Uri;
139import android.os.Binder;
140import android.os.Build;
141import android.os.Bundle;
142import android.os.Environment;
143import android.os.Environment.UserEnvironment;
144import android.os.storage.IMountService;
145import android.os.storage.StorageManager;
146import android.os.Debug;
147import android.os.FileUtils;
148import android.os.Handler;
149import android.os.IBinder;
150import android.os.Looper;
151import android.os.Message;
152import android.os.Parcel;
153import android.os.ParcelFileDescriptor;
154import android.os.Process;
155import android.os.RemoteException;
156import android.os.SELinux;
157import android.os.ServiceManager;
158import android.os.SystemClock;
159import android.os.SystemProperties;
160import android.os.UserHandle;
161import android.os.UserManager;
162import android.security.KeyStore;
163import android.security.SystemKeyStore;
164import android.system.ErrnoException;
165import android.system.Os;
166import android.system.StructStat;
167import android.text.TextUtils;
168import android.text.format.DateUtils;
169import android.util.ArraySet;
170import android.util.AtomicFile;
171import android.util.DisplayMetrics;
172import android.util.EventLog;
173import android.util.ExceptionUtils;
174import android.util.Log;
175import android.util.LogPrinter;
176import android.util.PrintStreamPrinter;
177import android.util.Slog;
178import android.util.SparseArray;
179import android.util.SparseBooleanArray;
180import android.view.Display;
181
182import java.io.BufferedInputStream;
183import java.io.BufferedOutputStream;
184import java.io.BufferedReader;
185import java.io.File;
186import java.io.FileDescriptor;
187import java.io.FileInputStream;
188import java.io.FileNotFoundException;
189import java.io.FileOutputStream;
190import java.io.FileReader;
191import java.io.FilenameFilter;
192import java.io.IOException;
193import java.io.InputStream;
194import java.io.PrintWriter;
195import java.nio.charset.StandardCharsets;
196import java.security.NoSuchAlgorithmException;
197import java.security.PublicKey;
198import java.security.cert.CertificateEncodingException;
199import java.security.cert.CertificateException;
200import java.text.SimpleDateFormat;
201import java.util.ArrayList;
202import java.util.Arrays;
203import java.util.Collection;
204import java.util.Collections;
205import java.util.Comparator;
206import java.util.Date;
207import java.util.Iterator;
208import java.util.List;
209import java.util.Map;
210import java.util.Objects;
211import java.util.Set;
212import java.util.concurrent.atomic.AtomicBoolean;
213import java.util.concurrent.atomic.AtomicLong;
214
215import dalvik.system.DexFile;
216import dalvik.system.StaleDexCacheError;
217import dalvik.system.VMRuntime;
218
219import libcore.io.IoUtils;
220import libcore.util.EmptyArray;
221
222/**
223 * Keep track of all those .apks everywhere.
224 *
225 * This is very central to the platform's security; please run the unit
226 * tests whenever making modifications here:
227 *
228mmm frameworks/base/tests/AndroidTests
229adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
230adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
231 *
232 * {@hide}
233 */
234public class PackageManagerService extends IPackageManager.Stub {
235    static final String TAG = "PackageManager";
236    static final boolean DEBUG_SETTINGS = false;
237    static final boolean DEBUG_PREFERRED = false;
238    static final boolean DEBUG_UPGRADE = false;
239    private static final boolean DEBUG_INSTALL = false;
240    private static final boolean DEBUG_REMOVE = false;
241    private static final boolean DEBUG_BROADCASTS = false;
242    private static final boolean DEBUG_SHOW_INFO = false;
243    private static final boolean DEBUG_PACKAGE_INFO = false;
244    private static final boolean DEBUG_INTENT_MATCHING = false;
245    private static final boolean DEBUG_PACKAGE_SCANNING = false;
246    private static final boolean DEBUG_VERIFY = false;
247    private static final boolean DEBUG_DEXOPT = false;
248    private static final boolean DEBUG_ABI_SELECTION = false;
249
250    private static final int RADIO_UID = Process.PHONE_UID;
251    private static final int LOG_UID = Process.LOG_UID;
252    private static final int NFC_UID = Process.NFC_UID;
253    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
254    private static final int SHELL_UID = Process.SHELL_UID;
255
256    // Cap the size of permission trees that 3rd party apps can define
257    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
258
259    // Suffix used during package installation when copying/moving
260    // package apks to install directory.
261    private static final String INSTALL_PACKAGE_SUFFIX = "-";
262
263    static final int SCAN_NO_DEX = 1<<1;
264    static final int SCAN_FORCE_DEX = 1<<2;
265    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
266    static final int SCAN_NEW_INSTALL = 1<<4;
267    static final int SCAN_NO_PATHS = 1<<5;
268    static final int SCAN_UPDATE_TIME = 1<<6;
269    static final int SCAN_DEFER_DEX = 1<<7;
270    static final int SCAN_BOOTING = 1<<8;
271    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
272    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
273    static final int SCAN_REPLACING = 1<<11;
274
275    static final int REMOVE_CHATTY = 1<<16;
276
277    /**
278     * Timeout (in milliseconds) after which the watchdog should declare that
279     * our handler thread is wedged.  The usual default for such things is one
280     * minute but we sometimes do very lengthy I/O operations on this thread,
281     * such as installing multi-gigabyte applications, so ours needs to be longer.
282     */
283    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
284
285    /**
286     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
287     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
288     * settings entry if available, otherwise we use the hardcoded default.  If it's been
289     * more than this long since the last fstrim, we force one during the boot sequence.
290     *
291     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
292     * one gets run at the next available charging+idle time.  This final mandatory
293     * no-fstrim check kicks in only of the other scheduling criteria is never met.
294     */
295    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
296
297    /**
298     * Whether verification is enabled by default.
299     */
300    private static final boolean DEFAULT_VERIFY_ENABLE = true;
301
302    /**
303     * The default maximum time to wait for the verification agent to return in
304     * milliseconds.
305     */
306    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
307
308    /**
309     * The default response for package verification timeout.
310     *
311     * This can be either PackageManager.VERIFICATION_ALLOW or
312     * PackageManager.VERIFICATION_REJECT.
313     */
314    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
315
316    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
317
318    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
319            DEFAULT_CONTAINER_PACKAGE,
320            "com.android.defcontainer.DefaultContainerService");
321
322    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
323
324    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
325
326    private static String sPreferredInstructionSet;
327
328    final ServiceThread mHandlerThread;
329
330    private static final String IDMAP_PREFIX = "/data/resource-cache/";
331    private static final String IDMAP_SUFFIX = "@idmap";
332
333    final PackageHandler mHandler;
334
335    /**
336     * Messages for {@link #mHandler} that need to wait for system ready before
337     * being dispatched.
338     */
339    private ArrayList<Message> mPostSystemReadyMessages;
340
341    final int mSdkVersion = Build.VERSION.SDK_INT;
342
343    final Context mContext;
344    final boolean mFactoryTest;
345    final boolean mOnlyCore;
346    final boolean mLazyDexOpt;
347    final long mDexOptLRUThresholdInMills;
348    final DisplayMetrics mMetrics;
349    final int mDefParseFlags;
350    final String[] mSeparateProcesses;
351    final boolean mIsUpgrade;
352
353    // This is where all application persistent data goes.
354    final File mAppDataDir;
355
356    // This is where all application persistent data goes for secondary users.
357    final File mUserAppDataDir;
358
359    /** The location for ASEC container files on internal storage. */
360    final String mAsecInternalPath;
361
362    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
363    // LOCK HELD.  Can be called with mInstallLock held.
364    final Installer mInstaller;
365
366    /** Directory where installed third-party apps stored */
367    final File mAppInstallDir;
368
369    /**
370     * Directory to which applications installed internally have their
371     * 32 bit native libraries copied.
372     */
373    private File mAppLib32InstallDir;
374
375    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
376    // apps.
377    final File mDrmAppPrivateInstallDir;
378
379    // ----------------------------------------------------------------
380
381    // Lock for state used when installing and doing other long running
382    // operations.  Methods that must be called with this lock held have
383    // the suffix "LI".
384    final Object mInstallLock = new Object();
385
386    // ----------------------------------------------------------------
387
388    // Keys are String (package name), values are Package.  This also serves
389    // as the lock for the global state.  Methods that must be called with
390    // this lock held have the prefix "LP".
391    final ArrayMap<String, PackageParser.Package> mPackages =
392            new ArrayMap<String, PackageParser.Package>();
393
394    // Tracks available target package names -> overlay package paths.
395    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
396        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
397
398    final Settings mSettings;
399    boolean mRestoredSettings;
400
401    // System configuration read by SystemConfig.
402    final int[] mGlobalGids;
403    final SparseArray<ArraySet<String>> mSystemPermissions;
404    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
405
406    // If mac_permissions.xml was found for seinfo labeling.
407    boolean mFoundPolicyFile;
408
409    // If a recursive restorecon of /data/data/<pkg> is needed.
410    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
411
412    public static final class SharedLibraryEntry {
413        public final String path;
414        public final String apk;
415
416        SharedLibraryEntry(String _path, String _apk) {
417            path = _path;
418            apk = _apk;
419        }
420    }
421
422    // Currently known shared libraries.
423    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
424            new ArrayMap<String, SharedLibraryEntry>();
425
426    // All available activities, for your resolving pleasure.
427    final ActivityIntentResolver mActivities =
428            new ActivityIntentResolver();
429
430    // All available receivers, for your resolving pleasure.
431    final ActivityIntentResolver mReceivers =
432            new ActivityIntentResolver();
433
434    // All available services, for your resolving pleasure.
435    final ServiceIntentResolver mServices = new ServiceIntentResolver();
436
437    // All available providers, for your resolving pleasure.
438    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
439
440    // Mapping from provider base names (first directory in content URI codePath)
441    // to the provider information.
442    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
443            new ArrayMap<String, PackageParser.Provider>();
444
445    // Mapping from instrumentation class names to info about them.
446    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
447            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
448
449    // Mapping from permission names to info about them.
450    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
451            new ArrayMap<String, PackageParser.PermissionGroup>();
452
453    // Packages whose data we have transfered into another package, thus
454    // should no longer exist.
455    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
456
457    // Broadcast actions that are only available to the system.
458    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
459
460    /** List of packages waiting for verification. */
461    final SparseArray<PackageVerificationState> mPendingVerification
462            = new SparseArray<PackageVerificationState>();
463
464    /** Set of packages associated with each app op permission. */
465    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
466
467    final PackageInstallerService mInstallerService;
468
469    ArraySet<PackageParser.Package> mDeferredDexOpt = null;
470
471    // Cache of users who need badging.
472    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
473
474    /** Token for keys in mPendingVerification. */
475    private int mPendingVerificationToken = 0;
476
477    volatile boolean mSystemReady;
478    volatile boolean mSafeMode;
479    volatile boolean mHasSystemUidErrors;
480
481    ApplicationInfo mAndroidApplication;
482    final ActivityInfo mResolveActivity = new ActivityInfo();
483    final ResolveInfo mResolveInfo = new ResolveInfo();
484    ComponentName mResolveComponentName;
485    PackageParser.Package mPlatformPackage;
486    ComponentName mCustomResolverComponentName;
487
488    boolean mResolverReplaced = false;
489
490    // Set of pending broadcasts for aggregating enable/disable of components.
491    static class PendingPackageBroadcasts {
492        // for each user id, a map of <package name -> components within that package>
493        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
494
495        public PendingPackageBroadcasts() {
496            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
497        }
498
499        public ArrayList<String> get(int userId, String packageName) {
500            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
501            return packages.get(packageName);
502        }
503
504        public void put(int userId, String packageName, ArrayList<String> components) {
505            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
506            packages.put(packageName, components);
507        }
508
509        public void remove(int userId, String packageName) {
510            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
511            if (packages != null) {
512                packages.remove(packageName);
513            }
514        }
515
516        public void remove(int userId) {
517            mUidMap.remove(userId);
518        }
519
520        public int userIdCount() {
521            return mUidMap.size();
522        }
523
524        public int userIdAt(int n) {
525            return mUidMap.keyAt(n);
526        }
527
528        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
529            return mUidMap.get(userId);
530        }
531
532        public int size() {
533            // total number of pending broadcast entries across all userIds
534            int num = 0;
535            for (int i = 0; i< mUidMap.size(); i++) {
536                num += mUidMap.valueAt(i).size();
537            }
538            return num;
539        }
540
541        public void clear() {
542            mUidMap.clear();
543        }
544
545        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
546            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
547            if (map == null) {
548                map = new ArrayMap<String, ArrayList<String>>();
549                mUidMap.put(userId, map);
550            }
551            return map;
552        }
553    }
554    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
555
556    // Service Connection to remote media container service to copy
557    // package uri's from external media onto secure containers
558    // or internal storage.
559    private IMediaContainerService mContainerService = null;
560
561    static final int SEND_PENDING_BROADCAST = 1;
562    static final int MCS_BOUND = 3;
563    static final int END_COPY = 4;
564    static final int INIT_COPY = 5;
565    static final int MCS_UNBIND = 6;
566    static final int START_CLEANING_PACKAGE = 7;
567    static final int FIND_INSTALL_LOC = 8;
568    static final int POST_INSTALL = 9;
569    static final int MCS_RECONNECT = 10;
570    static final int MCS_GIVE_UP = 11;
571    static final int UPDATED_MEDIA_STATUS = 12;
572    static final int WRITE_SETTINGS = 13;
573    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
574    static final int PACKAGE_VERIFIED = 15;
575    static final int CHECK_PENDING_VERIFICATION = 16;
576
577    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
578
579    // Delay time in millisecs
580    static final int BROADCAST_DELAY = 10 * 1000;
581
582    static UserManagerService sUserManager;
583
584    // Stores a list of users whose package restrictions file needs to be updated
585    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
586
587    final private DefaultContainerConnection mDefContainerConn =
588            new DefaultContainerConnection();
589    class DefaultContainerConnection implements ServiceConnection {
590        public void onServiceConnected(ComponentName name, IBinder service) {
591            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
592            IMediaContainerService imcs =
593                IMediaContainerService.Stub.asInterface(service);
594            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
595        }
596
597        public void onServiceDisconnected(ComponentName name) {
598            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
599        }
600    };
601
602    // Recordkeeping of restore-after-install operations that are currently in flight
603    // between the Package Manager and the Backup Manager
604    class PostInstallData {
605        public InstallArgs args;
606        public PackageInstalledInfo res;
607
608        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
609            args = _a;
610            res = _r;
611        }
612    };
613    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
614    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
615
616    private final String mRequiredVerifierPackage;
617
618    private final PackageUsage mPackageUsage = new PackageUsage();
619
620    private class PackageUsage {
621        private static final int WRITE_INTERVAL
622            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
623
624        private final Object mFileLock = new Object();
625        private final AtomicLong mLastWritten = new AtomicLong(0);
626        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
627
628        private boolean mIsHistoricalPackageUsageAvailable = true;
629
630        boolean isHistoricalPackageUsageAvailable() {
631            return mIsHistoricalPackageUsageAvailable;
632        }
633
634        void write(boolean force) {
635            if (force) {
636                writeInternal();
637                return;
638            }
639            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
640                && !DEBUG_DEXOPT) {
641                return;
642            }
643            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
644                new Thread("PackageUsage_DiskWriter") {
645                    @Override
646                    public void run() {
647                        try {
648                            writeInternal();
649                        } finally {
650                            mBackgroundWriteRunning.set(false);
651                        }
652                    }
653                }.start();
654            }
655        }
656
657        private void writeInternal() {
658            synchronized (mPackages) {
659                synchronized (mFileLock) {
660                    AtomicFile file = getFile();
661                    FileOutputStream f = null;
662                    try {
663                        f = file.startWrite();
664                        BufferedOutputStream out = new BufferedOutputStream(f);
665                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
666                        StringBuilder sb = new StringBuilder();
667                        for (PackageParser.Package pkg : mPackages.values()) {
668                            if (pkg.mLastPackageUsageTimeInMills == 0) {
669                                continue;
670                            }
671                            sb.setLength(0);
672                            sb.append(pkg.packageName);
673                            sb.append(' ');
674                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
675                            sb.append('\n');
676                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
677                        }
678                        out.flush();
679                        file.finishWrite(f);
680                    } catch (IOException e) {
681                        if (f != null) {
682                            file.failWrite(f);
683                        }
684                        Log.e(TAG, "Failed to write package usage times", e);
685                    }
686                }
687            }
688            mLastWritten.set(SystemClock.elapsedRealtime());
689        }
690
691        void readLP() {
692            synchronized (mFileLock) {
693                AtomicFile file = getFile();
694                BufferedInputStream in = null;
695                try {
696                    in = new BufferedInputStream(file.openRead());
697                    StringBuffer sb = new StringBuffer();
698                    while (true) {
699                        String packageName = readToken(in, sb, ' ');
700                        if (packageName == null) {
701                            break;
702                        }
703                        String timeInMillisString = readToken(in, sb, '\n');
704                        if (timeInMillisString == null) {
705                            throw new IOException("Failed to find last usage time for package "
706                                                  + packageName);
707                        }
708                        PackageParser.Package pkg = mPackages.get(packageName);
709                        if (pkg == null) {
710                            continue;
711                        }
712                        long timeInMillis;
713                        try {
714                            timeInMillis = Long.parseLong(timeInMillisString.toString());
715                        } catch (NumberFormatException e) {
716                            throw new IOException("Failed to parse " + timeInMillisString
717                                                  + " as a long.", e);
718                        }
719                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
720                    }
721                } catch (FileNotFoundException expected) {
722                    mIsHistoricalPackageUsageAvailable = false;
723                } catch (IOException e) {
724                    Log.w(TAG, "Failed to read package usage times", e);
725                } finally {
726                    IoUtils.closeQuietly(in);
727                }
728            }
729            mLastWritten.set(SystemClock.elapsedRealtime());
730        }
731
732        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
733                throws IOException {
734            sb.setLength(0);
735            while (true) {
736                int ch = in.read();
737                if (ch == -1) {
738                    if (sb.length() == 0) {
739                        return null;
740                    }
741                    throw new IOException("Unexpected EOF");
742                }
743                if (ch == endOfToken) {
744                    return sb.toString();
745                }
746                sb.append((char)ch);
747            }
748        }
749
750        private AtomicFile getFile() {
751            File dataDir = Environment.getDataDirectory();
752            File systemDir = new File(dataDir, "system");
753            File fname = new File(systemDir, "package-usage.list");
754            return new AtomicFile(fname);
755        }
756    }
757
758    class PackageHandler extends Handler {
759        private boolean mBound = false;
760        final ArrayList<HandlerParams> mPendingInstalls =
761            new ArrayList<HandlerParams>();
762
763        private boolean connectToService() {
764            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
765                    " DefaultContainerService");
766            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
767            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
768            if (mContext.bindServiceAsUser(service, mDefContainerConn,
769                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
770                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
771                mBound = true;
772                return true;
773            }
774            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
775            return false;
776        }
777
778        private void disconnectService() {
779            mContainerService = null;
780            mBound = false;
781            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
782            mContext.unbindService(mDefContainerConn);
783            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
784        }
785
786        PackageHandler(Looper looper) {
787            super(looper);
788        }
789
790        public void handleMessage(Message msg) {
791            try {
792                doHandleMessage(msg);
793            } finally {
794                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
795            }
796        }
797
798        void doHandleMessage(Message msg) {
799            switch (msg.what) {
800                case INIT_COPY: {
801                    HandlerParams params = (HandlerParams) msg.obj;
802                    int idx = mPendingInstalls.size();
803                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
804                    // If a bind was already initiated we dont really
805                    // need to do anything. The pending install
806                    // will be processed later on.
807                    if (!mBound) {
808                        // If this is the only one pending we might
809                        // have to bind to the service again.
810                        if (!connectToService()) {
811                            Slog.e(TAG, "Failed to bind to media container service");
812                            params.serviceError();
813                            return;
814                        } else {
815                            // Once we bind to the service, the first
816                            // pending request will be processed.
817                            mPendingInstalls.add(idx, params);
818                        }
819                    } else {
820                        mPendingInstalls.add(idx, params);
821                        // Already bound to the service. Just make
822                        // sure we trigger off processing the first request.
823                        if (idx == 0) {
824                            mHandler.sendEmptyMessage(MCS_BOUND);
825                        }
826                    }
827                    break;
828                }
829                case MCS_BOUND: {
830                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
831                    if (msg.obj != null) {
832                        mContainerService = (IMediaContainerService) msg.obj;
833                    }
834                    if (mContainerService == null) {
835                        // Something seriously wrong. Bail out
836                        Slog.e(TAG, "Cannot bind to media container service");
837                        for (HandlerParams params : mPendingInstalls) {
838                            // Indicate service bind error
839                            params.serviceError();
840                        }
841                        mPendingInstalls.clear();
842                    } else if (mPendingInstalls.size() > 0) {
843                        HandlerParams params = mPendingInstalls.get(0);
844                        if (params != null) {
845                            if (params.startCopy()) {
846                                // We are done...  look for more work or to
847                                // go idle.
848                                if (DEBUG_SD_INSTALL) Log.i(TAG,
849                                        "Checking for more work or unbind...");
850                                // Delete pending install
851                                if (mPendingInstalls.size() > 0) {
852                                    mPendingInstalls.remove(0);
853                                }
854                                if (mPendingInstalls.size() == 0) {
855                                    if (mBound) {
856                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
857                                                "Posting delayed MCS_UNBIND");
858                                        removeMessages(MCS_UNBIND);
859                                        Message ubmsg = obtainMessage(MCS_UNBIND);
860                                        // Unbind after a little delay, to avoid
861                                        // continual thrashing.
862                                        sendMessageDelayed(ubmsg, 10000);
863                                    }
864                                } else {
865                                    // There are more pending requests in queue.
866                                    // Just post MCS_BOUND message to trigger processing
867                                    // of next pending install.
868                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
869                                            "Posting MCS_BOUND for next work");
870                                    mHandler.sendEmptyMessage(MCS_BOUND);
871                                }
872                            }
873                        }
874                    } else {
875                        // Should never happen ideally.
876                        Slog.w(TAG, "Empty queue");
877                    }
878                    break;
879                }
880                case MCS_RECONNECT: {
881                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
882                    if (mPendingInstalls.size() > 0) {
883                        if (mBound) {
884                            disconnectService();
885                        }
886                        if (!connectToService()) {
887                            Slog.e(TAG, "Failed to bind to media container service");
888                            for (HandlerParams params : mPendingInstalls) {
889                                // Indicate service bind error
890                                params.serviceError();
891                            }
892                            mPendingInstalls.clear();
893                        }
894                    }
895                    break;
896                }
897                case MCS_UNBIND: {
898                    // If there is no actual work left, then time to unbind.
899                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
900
901                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
902                        if (mBound) {
903                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
904
905                            disconnectService();
906                        }
907                    } else if (mPendingInstalls.size() > 0) {
908                        // There are more pending requests in queue.
909                        // Just post MCS_BOUND message to trigger processing
910                        // of next pending install.
911                        mHandler.sendEmptyMessage(MCS_BOUND);
912                    }
913
914                    break;
915                }
916                case MCS_GIVE_UP: {
917                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
918                    mPendingInstalls.remove(0);
919                    break;
920                }
921                case SEND_PENDING_BROADCAST: {
922                    String packages[];
923                    ArrayList<String> components[];
924                    int size = 0;
925                    int uids[];
926                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
927                    synchronized (mPackages) {
928                        if (mPendingBroadcasts == null) {
929                            return;
930                        }
931                        size = mPendingBroadcasts.size();
932                        if (size <= 0) {
933                            // Nothing to be done. Just return
934                            return;
935                        }
936                        packages = new String[size];
937                        components = new ArrayList[size];
938                        uids = new int[size];
939                        int i = 0;  // filling out the above arrays
940
941                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
942                            int packageUserId = mPendingBroadcasts.userIdAt(n);
943                            Iterator<Map.Entry<String, ArrayList<String>>> it
944                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
945                                            .entrySet().iterator();
946                            while (it.hasNext() && i < size) {
947                                Map.Entry<String, ArrayList<String>> ent = it.next();
948                                packages[i] = ent.getKey();
949                                components[i] = ent.getValue();
950                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
951                                uids[i] = (ps != null)
952                                        ? UserHandle.getUid(packageUserId, ps.appId)
953                                        : -1;
954                                i++;
955                            }
956                        }
957                        size = i;
958                        mPendingBroadcasts.clear();
959                    }
960                    // Send broadcasts
961                    for (int i = 0; i < size; i++) {
962                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
963                    }
964                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
965                    break;
966                }
967                case START_CLEANING_PACKAGE: {
968                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
969                    final String packageName = (String)msg.obj;
970                    final int userId = msg.arg1;
971                    final boolean andCode = msg.arg2 != 0;
972                    synchronized (mPackages) {
973                        if (userId == UserHandle.USER_ALL) {
974                            int[] users = sUserManager.getUserIds();
975                            for (int user : users) {
976                                mSettings.addPackageToCleanLPw(
977                                        new PackageCleanItem(user, packageName, andCode));
978                            }
979                        } else {
980                            mSettings.addPackageToCleanLPw(
981                                    new PackageCleanItem(userId, packageName, andCode));
982                        }
983                    }
984                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
985                    startCleaningPackages();
986                } break;
987                case POST_INSTALL: {
988                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
989                    PostInstallData data = mRunningInstalls.get(msg.arg1);
990                    mRunningInstalls.delete(msg.arg1);
991                    boolean deleteOld = false;
992
993                    if (data != null) {
994                        InstallArgs args = data.args;
995                        PackageInstalledInfo res = data.res;
996
997                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
998                            res.removedInfo.sendBroadcast(false, true, false);
999                            Bundle extras = new Bundle(1);
1000                            extras.putInt(Intent.EXTRA_UID, res.uid);
1001                            // Determine the set of users who are adding this
1002                            // package for the first time vs. those who are seeing
1003                            // an update.
1004                            int[] firstUsers;
1005                            int[] updateUsers = new int[0];
1006                            if (res.origUsers == null || res.origUsers.length == 0) {
1007                                firstUsers = res.newUsers;
1008                            } else {
1009                                firstUsers = new int[0];
1010                                for (int i=0; i<res.newUsers.length; i++) {
1011                                    int user = res.newUsers[i];
1012                                    boolean isNew = true;
1013                                    for (int j=0; j<res.origUsers.length; j++) {
1014                                        if (res.origUsers[j] == user) {
1015                                            isNew = false;
1016                                            break;
1017                                        }
1018                                    }
1019                                    if (isNew) {
1020                                        int[] newFirst = new int[firstUsers.length+1];
1021                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1022                                                firstUsers.length);
1023                                        newFirst[firstUsers.length] = user;
1024                                        firstUsers = newFirst;
1025                                    } else {
1026                                        int[] newUpdate = new int[updateUsers.length+1];
1027                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1028                                                updateUsers.length);
1029                                        newUpdate[updateUsers.length] = user;
1030                                        updateUsers = newUpdate;
1031                                    }
1032                                }
1033                            }
1034                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1035                                    res.pkg.applicationInfo.packageName,
1036                                    extras, null, null, firstUsers);
1037                            final boolean update = res.removedInfo.removedPackage != null;
1038                            if (update) {
1039                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1040                            }
1041                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1042                                    res.pkg.applicationInfo.packageName,
1043                                    extras, null, null, updateUsers);
1044                            if (update) {
1045                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1046                                        res.pkg.applicationInfo.packageName,
1047                                        extras, null, null, updateUsers);
1048                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1049                                        null, null,
1050                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1051
1052                                // treat asec-hosted packages like removable media on upgrade
1053                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1054                                    if (DEBUG_INSTALL) {
1055                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1056                                                + " is ASEC-hosted -> AVAILABLE");
1057                                    }
1058                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1059                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1060                                    pkgList.add(res.pkg.applicationInfo.packageName);
1061                                    sendResourcesChangedBroadcast(true, true,
1062                                            pkgList,uidArray, null);
1063                                }
1064                            }
1065                            if (res.removedInfo.args != null) {
1066                                // Remove the replaced package's older resources safely now
1067                                deleteOld = true;
1068                            }
1069
1070                            // Log current value of "unknown sources" setting
1071                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1072                                getUnknownSourcesSettings());
1073                        }
1074                        // Force a gc to clear up things
1075                        Runtime.getRuntime().gc();
1076                        // We delete after a gc for applications  on sdcard.
1077                        if (deleteOld) {
1078                            synchronized (mInstallLock) {
1079                                res.removedInfo.args.doPostDeleteLI(true);
1080                            }
1081                        }
1082                        if (args.observer != null) {
1083                            try {
1084                                Bundle extras = extrasForInstallResult(res);
1085                                args.observer.onPackageInstalled(res.name, res.returnCode,
1086                                        res.returnMsg, extras);
1087                            } catch (RemoteException e) {
1088                                Slog.i(TAG, "Observer no longer exists.");
1089                            }
1090                        }
1091                    } else {
1092                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1093                    }
1094                } break;
1095                case UPDATED_MEDIA_STATUS: {
1096                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1097                    boolean reportStatus = msg.arg1 == 1;
1098                    boolean doGc = msg.arg2 == 1;
1099                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1100                    if (doGc) {
1101                        // Force a gc to clear up stale containers.
1102                        Runtime.getRuntime().gc();
1103                    }
1104                    if (msg.obj != null) {
1105                        @SuppressWarnings("unchecked")
1106                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1107                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1108                        // Unload containers
1109                        unloadAllContainers(args);
1110                    }
1111                    if (reportStatus) {
1112                        try {
1113                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1114                            PackageHelper.getMountService().finishMediaUpdate();
1115                        } catch (RemoteException e) {
1116                            Log.e(TAG, "MountService not running?");
1117                        }
1118                    }
1119                } break;
1120                case WRITE_SETTINGS: {
1121                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1122                    synchronized (mPackages) {
1123                        removeMessages(WRITE_SETTINGS);
1124                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1125                        mSettings.writeLPr();
1126                        mDirtyUsers.clear();
1127                    }
1128                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1129                } break;
1130                case WRITE_PACKAGE_RESTRICTIONS: {
1131                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1132                    synchronized (mPackages) {
1133                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1134                        for (int userId : mDirtyUsers) {
1135                            mSettings.writePackageRestrictionsLPr(userId);
1136                        }
1137                        mDirtyUsers.clear();
1138                    }
1139                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1140                } break;
1141                case CHECK_PENDING_VERIFICATION: {
1142                    final int verificationId = msg.arg1;
1143                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1144
1145                    if ((state != null) && !state.timeoutExtended()) {
1146                        final InstallArgs args = state.getInstallArgs();
1147                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1148
1149                        Slog.i(TAG, "Verification timed out for " + originUri);
1150                        mPendingVerification.remove(verificationId);
1151
1152                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1153
1154                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1155                            Slog.i(TAG, "Continuing with installation of " + originUri);
1156                            state.setVerifierResponse(Binder.getCallingUid(),
1157                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1158                            broadcastPackageVerified(verificationId, originUri,
1159                                    PackageManager.VERIFICATION_ALLOW,
1160                                    state.getInstallArgs().getUser());
1161                            try {
1162                                ret = args.copyApk(mContainerService, true);
1163                            } catch (RemoteException e) {
1164                                Slog.e(TAG, "Could not contact the ContainerService");
1165                            }
1166                        } else {
1167                            broadcastPackageVerified(verificationId, originUri,
1168                                    PackageManager.VERIFICATION_REJECT,
1169                                    state.getInstallArgs().getUser());
1170                        }
1171
1172                        processPendingInstall(args, ret);
1173                        mHandler.sendEmptyMessage(MCS_UNBIND);
1174                    }
1175                    break;
1176                }
1177                case PACKAGE_VERIFIED: {
1178                    final int verificationId = msg.arg1;
1179
1180                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1181                    if (state == null) {
1182                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1183                        break;
1184                    }
1185
1186                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1187
1188                    state.setVerifierResponse(response.callerUid, response.code);
1189
1190                    if (state.isVerificationComplete()) {
1191                        mPendingVerification.remove(verificationId);
1192
1193                        final InstallArgs args = state.getInstallArgs();
1194                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1195
1196                        int ret;
1197                        if (state.isInstallAllowed()) {
1198                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1199                            broadcastPackageVerified(verificationId, originUri,
1200                                    response.code, state.getInstallArgs().getUser());
1201                            try {
1202                                ret = args.copyApk(mContainerService, true);
1203                            } catch (RemoteException e) {
1204                                Slog.e(TAG, "Could not contact the ContainerService");
1205                            }
1206                        } else {
1207                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1208                        }
1209
1210                        processPendingInstall(args, ret);
1211
1212                        mHandler.sendEmptyMessage(MCS_UNBIND);
1213                    }
1214
1215                    break;
1216                }
1217            }
1218        }
1219    }
1220
1221    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1222        Bundle extras = null;
1223        switch (res.returnCode) {
1224            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1225                extras = new Bundle();
1226                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1227                        res.origPermission);
1228                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1229                        res.origPackage);
1230                break;
1231            }
1232        }
1233        return extras;
1234    }
1235
1236    void scheduleWriteSettingsLocked() {
1237        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1238            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1239        }
1240    }
1241
1242    void scheduleWritePackageRestrictionsLocked(int userId) {
1243        if (!sUserManager.exists(userId)) return;
1244        mDirtyUsers.add(userId);
1245        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1246            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1247        }
1248    }
1249
1250    public static final PackageManagerService main(Context context, Installer installer,
1251            boolean factoryTest, boolean onlyCore) {
1252        PackageManagerService m = new PackageManagerService(context, installer,
1253                factoryTest, onlyCore);
1254        ServiceManager.addService("package", m);
1255        return m;
1256    }
1257
1258    static String[] splitString(String str, char sep) {
1259        int count = 1;
1260        int i = 0;
1261        while ((i=str.indexOf(sep, i)) >= 0) {
1262            count++;
1263            i++;
1264        }
1265
1266        String[] res = new String[count];
1267        i=0;
1268        count = 0;
1269        int lastI=0;
1270        while ((i=str.indexOf(sep, i)) >= 0) {
1271            res[count] = str.substring(lastI, i);
1272            count++;
1273            i++;
1274            lastI = i;
1275        }
1276        res[count] = str.substring(lastI, str.length());
1277        return res;
1278    }
1279
1280    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1281        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1282                Context.DISPLAY_SERVICE);
1283        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1284    }
1285
1286    public PackageManagerService(Context context, Installer installer,
1287            boolean factoryTest, boolean onlyCore) {
1288        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1289                SystemClock.uptimeMillis());
1290
1291        if (mSdkVersion <= 0) {
1292            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1293        }
1294
1295        mContext = context;
1296        mFactoryTest = factoryTest;
1297        mOnlyCore = onlyCore;
1298        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1299        mMetrics = new DisplayMetrics();
1300        mSettings = new Settings(context);
1301        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1302                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1303        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1304                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1305        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1306                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1307        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1308                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1309        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1310                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1311        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1312                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1313
1314        // TODO: add a property to control this?
1315        long dexOptLRUThresholdInMinutes;
1316        if (mLazyDexOpt) {
1317            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1318        } else {
1319            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1320        }
1321        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1322
1323        String separateProcesses = SystemProperties.get("debug.separate_processes");
1324        if (separateProcesses != null && separateProcesses.length() > 0) {
1325            if ("*".equals(separateProcesses)) {
1326                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1327                mSeparateProcesses = null;
1328                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1329            } else {
1330                mDefParseFlags = 0;
1331                mSeparateProcesses = separateProcesses.split(",");
1332                Slog.w(TAG, "Running with debug.separate_processes: "
1333                        + separateProcesses);
1334            }
1335        } else {
1336            mDefParseFlags = 0;
1337            mSeparateProcesses = null;
1338        }
1339
1340        mInstaller = installer;
1341
1342        getDefaultDisplayMetrics(context, mMetrics);
1343
1344        SystemConfig systemConfig = SystemConfig.getInstance();
1345        mGlobalGids = systemConfig.getGlobalGids();
1346        mSystemPermissions = systemConfig.getSystemPermissions();
1347        mAvailableFeatures = systemConfig.getAvailableFeatures();
1348
1349        synchronized (mInstallLock) {
1350        // writer
1351        synchronized (mPackages) {
1352            mHandlerThread = new ServiceThread(TAG,
1353                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1354            mHandlerThread.start();
1355            mHandler = new PackageHandler(mHandlerThread.getLooper());
1356            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1357
1358            File dataDir = Environment.getDataDirectory();
1359            mAppDataDir = new File(dataDir, "data");
1360            mAppInstallDir = new File(dataDir, "app");
1361            mAppLib32InstallDir = new File(dataDir, "app-lib");
1362            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1363            mUserAppDataDir = new File(dataDir, "user");
1364            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1365
1366            sUserManager = new UserManagerService(context, this,
1367                    mInstallLock, mPackages);
1368
1369            // Propagate permission configuration in to package manager.
1370            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1371                    = systemConfig.getPermissions();
1372            for (int i=0; i<permConfig.size(); i++) {
1373                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1374                BasePermission bp = mSettings.mPermissions.get(perm.name);
1375                if (bp == null) {
1376                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1377                    mSettings.mPermissions.put(perm.name, bp);
1378                }
1379                if (perm.gids != null) {
1380                    bp.gids = appendInts(bp.gids, perm.gids);
1381                }
1382            }
1383
1384            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1385            for (int i=0; i<libConfig.size(); i++) {
1386                mSharedLibraries.put(libConfig.keyAt(i),
1387                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1388            }
1389
1390            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1391
1392            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1393                    mSdkVersion, mOnlyCore);
1394
1395            String customResolverActivity = Resources.getSystem().getString(
1396                    R.string.config_customResolverActivity);
1397            if (TextUtils.isEmpty(customResolverActivity)) {
1398                customResolverActivity = null;
1399            } else {
1400                mCustomResolverComponentName = ComponentName.unflattenFromString(
1401                        customResolverActivity);
1402            }
1403
1404            long startTime = SystemClock.uptimeMillis();
1405
1406            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1407                    startTime);
1408
1409            // Set flag to monitor and not change apk file paths when
1410            // scanning install directories.
1411            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1412
1413            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1414
1415            /**
1416             * Add everything in the in the boot class path to the
1417             * list of process files because dexopt will have been run
1418             * if necessary during zygote startup.
1419             */
1420            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1421            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1422
1423            if (bootClassPath != null) {
1424                String[] bootClassPathElements = splitString(bootClassPath, ':');
1425                for (String element : bootClassPathElements) {
1426                    alreadyDexOpted.add(element);
1427                }
1428            } else {
1429                Slog.w(TAG, "No BOOTCLASSPATH found!");
1430            }
1431
1432            if (systemServerClassPath != null) {
1433                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1434                for (String element : systemServerClassPathElements) {
1435                    alreadyDexOpted.add(element);
1436                }
1437            } else {
1438                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1439            }
1440
1441            final List<String> allInstructionSets = getAllInstructionSets();
1442            final String[] dexCodeInstructionSets =
1443                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1444
1445            /**
1446             * Ensure all external libraries have had dexopt run on them.
1447             */
1448            if (mSharedLibraries.size() > 0) {
1449                // NOTE: For now, we're compiling these system "shared libraries"
1450                // (and framework jars) into all available architectures. It's possible
1451                // to compile them only when we come across an app that uses them (there's
1452                // already logic for that in scanPackageLI) but that adds some complexity.
1453                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1454                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1455                        final String lib = libEntry.path;
1456                        if (lib == null) {
1457                            continue;
1458                        }
1459
1460                        try {
1461                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1462                                                                                 dexCodeInstructionSet,
1463                                                                                 false);
1464                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1465                                alreadyDexOpted.add(lib);
1466
1467                                // The list of "shared libraries" we have at this point is
1468                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1469                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1470                                } else {
1471                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1472                                }
1473                            }
1474                        } catch (FileNotFoundException e) {
1475                            Slog.w(TAG, "Library not found: " + lib);
1476                        } catch (IOException e) {
1477                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1478                                    + e.getMessage());
1479                        }
1480                    }
1481                }
1482            }
1483
1484            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1485
1486            // Gross hack for now: we know this file doesn't contain any
1487            // code, so don't dexopt it to avoid the resulting log spew.
1488            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1489
1490            // Gross hack for now: we know this file is only part of
1491            // the boot class path for art, so don't dexopt it to
1492            // avoid the resulting log spew.
1493            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1494
1495            /**
1496             * And there are a number of commands implemented in Java, which
1497             * we currently need to do the dexopt on so that they can be
1498             * run from a non-root shell.
1499             */
1500            String[] frameworkFiles = frameworkDir.list();
1501            if (frameworkFiles != null) {
1502                // TODO: We could compile these only for the most preferred ABI. We should
1503                // first double check that the dex files for these commands are not referenced
1504                // by other system apps.
1505                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1506                    for (int i=0; i<frameworkFiles.length; i++) {
1507                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1508                        String path = libPath.getPath();
1509                        // Skip the file if we already did it.
1510                        if (alreadyDexOpted.contains(path)) {
1511                            continue;
1512                        }
1513                        // Skip the file if it is not a type we want to dexopt.
1514                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1515                            continue;
1516                        }
1517                        try {
1518                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1519                                                                                 dexCodeInstructionSet,
1520                                                                                 false);
1521                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1522                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1523                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1524                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1525                            }
1526                        } catch (FileNotFoundException e) {
1527                            Slog.w(TAG, "Jar not found: " + path);
1528                        } catch (IOException e) {
1529                            Slog.w(TAG, "Exception reading jar: " + path, e);
1530                        }
1531                    }
1532                }
1533            }
1534
1535            // Collect vendor overlay packages.
1536            // (Do this before scanning any apps.)
1537            // For security and version matching reason, only consider
1538            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1539            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1540            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1541                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1542
1543            // Find base frameworks (resource packages without code).
1544            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1545                    | PackageParser.PARSE_IS_SYSTEM_DIR
1546                    | PackageParser.PARSE_IS_PRIVILEGED,
1547                    scanFlags | SCAN_NO_DEX, 0);
1548
1549            // Collected privileged system packages.
1550            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1551            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1552                    | PackageParser.PARSE_IS_SYSTEM_DIR
1553                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1554
1555            // Collect ordinary system packages.
1556            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1557            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1558                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1559
1560            // Collect all vendor packages.
1561            File vendorAppDir = new File("/vendor/app");
1562            try {
1563                vendorAppDir = vendorAppDir.getCanonicalFile();
1564            } catch (IOException e) {
1565                // failed to look up canonical path, continue with original one
1566            }
1567            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1568                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1569
1570            // Collect all OEM packages.
1571            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1572            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1573                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1574
1575            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1576            mInstaller.moveFiles();
1577
1578            // Prune any system packages that no longer exist.
1579            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1580            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1581            if (!mOnlyCore) {
1582                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1583                while (psit.hasNext()) {
1584                    PackageSetting ps = psit.next();
1585
1586                    /*
1587                     * If this is not a system app, it can't be a
1588                     * disable system app.
1589                     */
1590                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1591                        continue;
1592                    }
1593
1594                    /*
1595                     * If the package is scanned, it's not erased.
1596                     */
1597                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1598                    if (scannedPkg != null) {
1599                        /*
1600                         * If the system app is both scanned and in the
1601                         * disabled packages list, then it must have been
1602                         * added via OTA. Remove it from the currently
1603                         * scanned package so the previously user-installed
1604                         * application can be scanned.
1605                         */
1606                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1607                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1608                                    + ps.name + "; removing system app.  Last known codePath="
1609                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1610                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1611                                    + scannedPkg.mVersionCode);
1612                            removePackageLI(ps, true);
1613                            expectingBetter.put(ps.name, ps.codePath);
1614                        }
1615
1616                        continue;
1617                    }
1618
1619                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1620                        psit.remove();
1621                        logCriticalInfo(Log.WARN, "System package " + ps.name
1622                                + " no longer exists; wiping its data");
1623                        removeDataDirsLI(ps.name);
1624                    } else {
1625                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1626                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1627                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1628                        }
1629                    }
1630                }
1631            }
1632
1633            //look for any incomplete package installations
1634            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1635            //clean up list
1636            for(int i = 0; i < deletePkgsList.size(); i++) {
1637                //clean up here
1638                cleanupInstallFailedPackage(deletePkgsList.get(i));
1639            }
1640            //delete tmp files
1641            deleteTempPackageFiles();
1642
1643            // Remove any shared userIDs that have no associated packages
1644            mSettings.pruneSharedUsersLPw();
1645
1646            if (!mOnlyCore) {
1647                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1648                        SystemClock.uptimeMillis());
1649                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1650
1651                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1652                        scanFlags, 0);
1653
1654                /**
1655                 * Remove disable package settings for any updated system
1656                 * apps that were removed via an OTA. If they're not a
1657                 * previously-updated app, remove them completely.
1658                 * Otherwise, just revoke their system-level permissions.
1659                 */
1660                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1661                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1662                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1663
1664                    String msg;
1665                    if (deletedPkg == null) {
1666                        msg = "Updated system package " + deletedAppName
1667                                + " no longer exists; wiping its data";
1668                        removeDataDirsLI(deletedAppName);
1669                    } else {
1670                        msg = "Updated system app + " + deletedAppName
1671                                + " no longer present; removing system privileges for "
1672                                + deletedAppName;
1673
1674                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1675
1676                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1677                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1678                    }
1679                    logCriticalInfo(Log.WARN, msg);
1680                }
1681
1682                /**
1683                 * Make sure all system apps that we expected to appear on
1684                 * the userdata partition actually showed up. If they never
1685                 * appeared, crawl back and revive the system version.
1686                 */
1687                for (int i = 0; i < expectingBetter.size(); i++) {
1688                    final String packageName = expectingBetter.keyAt(i);
1689                    if (!mPackages.containsKey(packageName)) {
1690                        final File scanFile = expectingBetter.valueAt(i);
1691
1692                        logCriticalInfo(Log.WARN, "Expected better " + packageName
1693                                + " but never showed up; reverting to system");
1694
1695                        final int reparseFlags;
1696                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
1697                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1698                                    | PackageParser.PARSE_IS_SYSTEM_DIR
1699                                    | PackageParser.PARSE_IS_PRIVILEGED;
1700                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
1701                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1702                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1703                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
1704                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1705                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1706                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
1707                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1708                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1709                        } else {
1710                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
1711                            continue;
1712                        }
1713
1714                        mSettings.enableSystemPackageLPw(packageName);
1715
1716                        try {
1717                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
1718                        } catch (PackageManagerException e) {
1719                            Slog.e(TAG, "Failed to parse original system package: "
1720                                    + e.getMessage());
1721                        }
1722                    }
1723                }
1724            }
1725
1726            // Now that we know all of the shared libraries, update all clients to have
1727            // the correct library paths.
1728            updateAllSharedLibrariesLPw();
1729
1730            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1731                // NOTE: We ignore potential failures here during a system scan (like
1732                // the rest of the commands above) because there's precious little we
1733                // can do about it. A settings error is reported, though.
1734                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1735                        false /* force dexopt */, false /* defer dexopt */);
1736            }
1737
1738            // Now that we know all the packages we are keeping,
1739            // read and update their last usage times.
1740            mPackageUsage.readLP();
1741
1742            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1743                    SystemClock.uptimeMillis());
1744            Slog.i(TAG, "Time to scan packages: "
1745                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1746                    + " seconds");
1747
1748            // If the platform SDK has changed since the last time we booted,
1749            // we need to re-grant app permission to catch any new ones that
1750            // appear.  This is really a hack, and means that apps can in some
1751            // cases get permissions that the user didn't initially explicitly
1752            // allow...  it would be nice to have some better way to handle
1753            // this situation.
1754            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1755                    != mSdkVersion;
1756            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1757                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1758                    + "; regranting permissions for internal storage");
1759            mSettings.mInternalSdkPlatform = mSdkVersion;
1760
1761            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1762                    | (regrantPermissions
1763                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1764                            : 0));
1765
1766            // If this is the first boot, and it is a normal boot, then
1767            // we need to initialize the default preferred apps.
1768            if (!mRestoredSettings && !onlyCore) {
1769                mSettings.readDefaultPreferredAppsLPw(this, 0);
1770            }
1771
1772            // If this is first boot after an OTA, and a normal boot, then
1773            // we need to clear code cache directories.
1774            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
1775            if (mIsUpgrade && !onlyCore) {
1776                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1777                for (String pkgName : mSettings.mPackages.keySet()) {
1778                    deleteCodeCacheDirsLI(pkgName);
1779                }
1780                mSettings.mFingerprint = Build.FINGERPRINT;
1781            }
1782
1783            // All the changes are done during package scanning.
1784            mSettings.updateInternalDatabaseVersion();
1785
1786            // can downgrade to reader
1787            mSettings.writeLPr();
1788
1789            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1790                    SystemClock.uptimeMillis());
1791
1792
1793            mRequiredVerifierPackage = getRequiredVerifierLPr();
1794        } // synchronized (mPackages)
1795        } // synchronized (mInstallLock)
1796
1797        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1798
1799        // Now after opening every single application zip, make sure they
1800        // are all flushed.  Not really needed, but keeps things nice and
1801        // tidy.
1802        Runtime.getRuntime().gc();
1803    }
1804
1805    @Override
1806    public boolean isFirstBoot() {
1807        return !mRestoredSettings;
1808    }
1809
1810    @Override
1811    public boolean isOnlyCoreApps() {
1812        return mOnlyCore;
1813    }
1814
1815    @Override
1816    public boolean isUpgrade() {
1817        return mIsUpgrade;
1818    }
1819
1820    private String getRequiredVerifierLPr() {
1821        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1822        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1823                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1824
1825        String requiredVerifier = null;
1826
1827        final int N = receivers.size();
1828        for (int i = 0; i < N; i++) {
1829            final ResolveInfo info = receivers.get(i);
1830
1831            if (info.activityInfo == null) {
1832                continue;
1833            }
1834
1835            final String packageName = info.activityInfo.packageName;
1836
1837            final PackageSetting ps = mSettings.mPackages.get(packageName);
1838            if (ps == null) {
1839                continue;
1840            }
1841
1842            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1843            if (!gp.grantedPermissions
1844                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1845                continue;
1846            }
1847
1848            if (requiredVerifier != null) {
1849                throw new RuntimeException("There can be only one required verifier");
1850            }
1851
1852            requiredVerifier = packageName;
1853        }
1854
1855        return requiredVerifier;
1856    }
1857
1858    @Override
1859    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1860            throws RemoteException {
1861        try {
1862            return super.onTransact(code, data, reply, flags);
1863        } catch (RuntimeException e) {
1864            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1865                Slog.wtf(TAG, "Package Manager Crash", e);
1866            }
1867            throw e;
1868        }
1869    }
1870
1871    void cleanupInstallFailedPackage(PackageSetting ps) {
1872        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
1873
1874        removeDataDirsLI(ps.name);
1875        if (ps.codePath != null) {
1876            if (ps.codePath.isDirectory()) {
1877                FileUtils.deleteContents(ps.codePath);
1878            }
1879            ps.codePath.delete();
1880        }
1881        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1882            if (ps.resourcePath.isDirectory()) {
1883                FileUtils.deleteContents(ps.resourcePath);
1884            }
1885            ps.resourcePath.delete();
1886        }
1887        mSettings.removePackageLPw(ps.name);
1888    }
1889
1890    static int[] appendInts(int[] cur, int[] add) {
1891        if (add == null) return cur;
1892        if (cur == null) return add;
1893        final int N = add.length;
1894        for (int i=0; i<N; i++) {
1895            cur = appendInt(cur, add[i]);
1896        }
1897        return cur;
1898    }
1899
1900    static int[] removeInts(int[] cur, int[] rem) {
1901        if (rem == null) return cur;
1902        if (cur == null) return cur;
1903        final int N = rem.length;
1904        for (int i=0; i<N; i++) {
1905            cur = removeInt(cur, rem[i]);
1906        }
1907        return cur;
1908    }
1909
1910    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1911        if (!sUserManager.exists(userId)) return null;
1912        final PackageSetting ps = (PackageSetting) p.mExtras;
1913        if (ps == null) {
1914            return null;
1915        }
1916        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1917        final PackageUserState state = ps.readUserState(userId);
1918        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1919                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1920                state, userId);
1921    }
1922
1923    @Override
1924    public boolean isPackageAvailable(String packageName, int userId) {
1925        if (!sUserManager.exists(userId)) return false;
1926        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
1927        synchronized (mPackages) {
1928            PackageParser.Package p = mPackages.get(packageName);
1929            if (p != null) {
1930                final PackageSetting ps = (PackageSetting) p.mExtras;
1931                if (ps != null) {
1932                    final PackageUserState state = ps.readUserState(userId);
1933                    if (state != null) {
1934                        return PackageParser.isAvailable(state);
1935                    }
1936                }
1937            }
1938        }
1939        return false;
1940    }
1941
1942    @Override
1943    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1944        if (!sUserManager.exists(userId)) return null;
1945        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
1946        // reader
1947        synchronized (mPackages) {
1948            PackageParser.Package p = mPackages.get(packageName);
1949            if (DEBUG_PACKAGE_INFO)
1950                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1951            if (p != null) {
1952                return generatePackageInfo(p, flags, userId);
1953            }
1954            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1955                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1956            }
1957        }
1958        return null;
1959    }
1960
1961    @Override
1962    public String[] currentToCanonicalPackageNames(String[] names) {
1963        String[] out = new String[names.length];
1964        // reader
1965        synchronized (mPackages) {
1966            for (int i=names.length-1; i>=0; i--) {
1967                PackageSetting ps = mSettings.mPackages.get(names[i]);
1968                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1969            }
1970        }
1971        return out;
1972    }
1973
1974    @Override
1975    public String[] canonicalToCurrentPackageNames(String[] names) {
1976        String[] out = new String[names.length];
1977        // reader
1978        synchronized (mPackages) {
1979            for (int i=names.length-1; i>=0; i--) {
1980                String cur = mSettings.mRenamedPackages.get(names[i]);
1981                out[i] = cur != null ? cur : names[i];
1982            }
1983        }
1984        return out;
1985    }
1986
1987    @Override
1988    public int getPackageUid(String packageName, int userId) {
1989        if (!sUserManager.exists(userId)) return -1;
1990        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
1991        // reader
1992        synchronized (mPackages) {
1993            PackageParser.Package p = mPackages.get(packageName);
1994            if(p != null) {
1995                return UserHandle.getUid(userId, p.applicationInfo.uid);
1996            }
1997            PackageSetting ps = mSettings.mPackages.get(packageName);
1998            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1999                return -1;
2000            }
2001            p = ps.pkg;
2002            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2003        }
2004    }
2005
2006    @Override
2007    public int[] getPackageGids(String packageName) {
2008        // reader
2009        synchronized (mPackages) {
2010            PackageParser.Package p = mPackages.get(packageName);
2011            if (DEBUG_PACKAGE_INFO)
2012                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2013            if (p != null) {
2014                final PackageSetting ps = (PackageSetting)p.mExtras;
2015                return ps.getGids();
2016            }
2017        }
2018        // stupid thing to indicate an error.
2019        return new int[0];
2020    }
2021
2022    static final PermissionInfo generatePermissionInfo(
2023            BasePermission bp, int flags) {
2024        if (bp.perm != null) {
2025            return PackageParser.generatePermissionInfo(bp.perm, flags);
2026        }
2027        PermissionInfo pi = new PermissionInfo();
2028        pi.name = bp.name;
2029        pi.packageName = bp.sourcePackage;
2030        pi.nonLocalizedLabel = bp.name;
2031        pi.protectionLevel = bp.protectionLevel;
2032        return pi;
2033    }
2034
2035    @Override
2036    public PermissionInfo getPermissionInfo(String name, int flags) {
2037        // reader
2038        synchronized (mPackages) {
2039            final BasePermission p = mSettings.mPermissions.get(name);
2040            if (p != null) {
2041                return generatePermissionInfo(p, flags);
2042            }
2043            return null;
2044        }
2045    }
2046
2047    @Override
2048    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2049        // reader
2050        synchronized (mPackages) {
2051            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2052            for (BasePermission p : mSettings.mPermissions.values()) {
2053                if (group == null) {
2054                    if (p.perm == null || p.perm.info.group == null) {
2055                        out.add(generatePermissionInfo(p, flags));
2056                    }
2057                } else {
2058                    if (p.perm != null && group.equals(p.perm.info.group)) {
2059                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2060                    }
2061                }
2062            }
2063
2064            if (out.size() > 0) {
2065                return out;
2066            }
2067            return mPermissionGroups.containsKey(group) ? out : null;
2068        }
2069    }
2070
2071    @Override
2072    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2073        // reader
2074        synchronized (mPackages) {
2075            return PackageParser.generatePermissionGroupInfo(
2076                    mPermissionGroups.get(name), flags);
2077        }
2078    }
2079
2080    @Override
2081    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2082        // reader
2083        synchronized (mPackages) {
2084            final int N = mPermissionGroups.size();
2085            ArrayList<PermissionGroupInfo> out
2086                    = new ArrayList<PermissionGroupInfo>(N);
2087            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2088                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2089            }
2090            return out;
2091        }
2092    }
2093
2094    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2095            int userId) {
2096        if (!sUserManager.exists(userId)) return null;
2097        PackageSetting ps = mSettings.mPackages.get(packageName);
2098        if (ps != null) {
2099            if (ps.pkg == null) {
2100                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2101                        flags, userId);
2102                if (pInfo != null) {
2103                    return pInfo.applicationInfo;
2104                }
2105                return null;
2106            }
2107            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2108                    ps.readUserState(userId), userId);
2109        }
2110        return null;
2111    }
2112
2113    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2114            int userId) {
2115        if (!sUserManager.exists(userId)) return null;
2116        PackageSetting ps = mSettings.mPackages.get(packageName);
2117        if (ps != null) {
2118            PackageParser.Package pkg = ps.pkg;
2119            if (pkg == null) {
2120                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2121                    return null;
2122                }
2123                // Only data remains, so we aren't worried about code paths
2124                pkg = new PackageParser.Package(packageName);
2125                pkg.applicationInfo.packageName = packageName;
2126                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2127                pkg.applicationInfo.dataDir =
2128                        getDataPathForPackage(packageName, 0).getPath();
2129                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2130                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2131            }
2132            return generatePackageInfo(pkg, flags, userId);
2133        }
2134        return null;
2135    }
2136
2137    @Override
2138    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2139        if (!sUserManager.exists(userId)) return null;
2140        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2141        // writer
2142        synchronized (mPackages) {
2143            PackageParser.Package p = mPackages.get(packageName);
2144            if (DEBUG_PACKAGE_INFO) Log.v(
2145                    TAG, "getApplicationInfo " + packageName
2146                    + ": " + p);
2147            if (p != null) {
2148                PackageSetting ps = mSettings.mPackages.get(packageName);
2149                if (ps == null) return null;
2150                // Note: isEnabledLP() does not apply here - always return info
2151                return PackageParser.generateApplicationInfo(
2152                        p, flags, ps.readUserState(userId), userId);
2153            }
2154            if ("android".equals(packageName)||"system".equals(packageName)) {
2155                return mAndroidApplication;
2156            }
2157            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2158                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2159            }
2160        }
2161        return null;
2162    }
2163
2164
2165    @Override
2166    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2167        mContext.enforceCallingOrSelfPermission(
2168                android.Manifest.permission.CLEAR_APP_CACHE, null);
2169        // Queue up an async operation since clearing cache may take a little while.
2170        mHandler.post(new Runnable() {
2171            public void run() {
2172                mHandler.removeCallbacks(this);
2173                int retCode = -1;
2174                synchronized (mInstallLock) {
2175                    retCode = mInstaller.freeCache(freeStorageSize);
2176                    if (retCode < 0) {
2177                        Slog.w(TAG, "Couldn't clear application caches");
2178                    }
2179                }
2180                if (observer != null) {
2181                    try {
2182                        observer.onRemoveCompleted(null, (retCode >= 0));
2183                    } catch (RemoteException e) {
2184                        Slog.w(TAG, "RemoveException when invoking call back");
2185                    }
2186                }
2187            }
2188        });
2189    }
2190
2191    @Override
2192    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2193        mContext.enforceCallingOrSelfPermission(
2194                android.Manifest.permission.CLEAR_APP_CACHE, null);
2195        // Queue up an async operation since clearing cache may take a little while.
2196        mHandler.post(new Runnable() {
2197            public void run() {
2198                mHandler.removeCallbacks(this);
2199                int retCode = -1;
2200                synchronized (mInstallLock) {
2201                    retCode = mInstaller.freeCache(freeStorageSize);
2202                    if (retCode < 0) {
2203                        Slog.w(TAG, "Couldn't clear application caches");
2204                    }
2205                }
2206                if(pi != null) {
2207                    try {
2208                        // Callback via pending intent
2209                        int code = (retCode >= 0) ? 1 : 0;
2210                        pi.sendIntent(null, code, null,
2211                                null, null);
2212                    } catch (SendIntentException e1) {
2213                        Slog.i(TAG, "Failed to send pending intent");
2214                    }
2215                }
2216            }
2217        });
2218    }
2219
2220    void freeStorage(long freeStorageSize) throws IOException {
2221        synchronized (mInstallLock) {
2222            if (mInstaller.freeCache(freeStorageSize) < 0) {
2223                throw new IOException("Failed to free enough space");
2224            }
2225        }
2226    }
2227
2228    @Override
2229    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2230        if (!sUserManager.exists(userId)) return null;
2231        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2232        synchronized (mPackages) {
2233            PackageParser.Activity a = mActivities.mActivities.get(component);
2234
2235            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2236            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2237                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2238                if (ps == null) return null;
2239                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2240                        userId);
2241            }
2242            if (mResolveComponentName.equals(component)) {
2243                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2244                        new PackageUserState(), userId);
2245            }
2246        }
2247        return null;
2248    }
2249
2250    @Override
2251    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2252            String resolvedType) {
2253        synchronized (mPackages) {
2254            PackageParser.Activity a = mActivities.mActivities.get(component);
2255            if (a == null) {
2256                return false;
2257            }
2258            for (int i=0; i<a.intents.size(); i++) {
2259                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2260                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2261                    return true;
2262                }
2263            }
2264            return false;
2265        }
2266    }
2267
2268    @Override
2269    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2270        if (!sUserManager.exists(userId)) return null;
2271        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2272        synchronized (mPackages) {
2273            PackageParser.Activity a = mReceivers.mActivities.get(component);
2274            if (DEBUG_PACKAGE_INFO) Log.v(
2275                TAG, "getReceiverInfo " + component + ": " + a);
2276            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2277                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2278                if (ps == null) return null;
2279                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2280                        userId);
2281            }
2282        }
2283        return null;
2284    }
2285
2286    @Override
2287    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2288        if (!sUserManager.exists(userId)) return null;
2289        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2290        synchronized (mPackages) {
2291            PackageParser.Service s = mServices.mServices.get(component);
2292            if (DEBUG_PACKAGE_INFO) Log.v(
2293                TAG, "getServiceInfo " + component + ": " + s);
2294            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2295                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2296                if (ps == null) return null;
2297                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2298                        userId);
2299            }
2300        }
2301        return null;
2302    }
2303
2304    @Override
2305    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2306        if (!sUserManager.exists(userId)) return null;
2307        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2308        synchronized (mPackages) {
2309            PackageParser.Provider p = mProviders.mProviders.get(component);
2310            if (DEBUG_PACKAGE_INFO) Log.v(
2311                TAG, "getProviderInfo " + component + ": " + p);
2312            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2313                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2314                if (ps == null) return null;
2315                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2316                        userId);
2317            }
2318        }
2319        return null;
2320    }
2321
2322    @Override
2323    public String[] getSystemSharedLibraryNames() {
2324        Set<String> libSet;
2325        synchronized (mPackages) {
2326            libSet = mSharedLibraries.keySet();
2327            int size = libSet.size();
2328            if (size > 0) {
2329                String[] libs = new String[size];
2330                libSet.toArray(libs);
2331                return libs;
2332            }
2333        }
2334        return null;
2335    }
2336
2337    @Override
2338    public FeatureInfo[] getSystemAvailableFeatures() {
2339        Collection<FeatureInfo> featSet;
2340        synchronized (mPackages) {
2341            featSet = mAvailableFeatures.values();
2342            int size = featSet.size();
2343            if (size > 0) {
2344                FeatureInfo[] features = new FeatureInfo[size+1];
2345                featSet.toArray(features);
2346                FeatureInfo fi = new FeatureInfo();
2347                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2348                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2349                features[size] = fi;
2350                return features;
2351            }
2352        }
2353        return null;
2354    }
2355
2356    @Override
2357    public boolean hasSystemFeature(String name) {
2358        synchronized (mPackages) {
2359            return mAvailableFeatures.containsKey(name);
2360        }
2361    }
2362
2363    private void checkValidCaller(int uid, int userId) {
2364        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2365            return;
2366
2367        throw new SecurityException("Caller uid=" + uid
2368                + " is not privileged to communicate with user=" + userId);
2369    }
2370
2371    @Override
2372    public int checkPermission(String permName, String pkgName) {
2373        synchronized (mPackages) {
2374            PackageParser.Package p = mPackages.get(pkgName);
2375            if (p != null && p.mExtras != null) {
2376                PackageSetting ps = (PackageSetting)p.mExtras;
2377                if (ps.sharedUser != null) {
2378                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2379                        return PackageManager.PERMISSION_GRANTED;
2380                    }
2381                } else if (ps.grantedPermissions.contains(permName)) {
2382                    return PackageManager.PERMISSION_GRANTED;
2383                }
2384            }
2385        }
2386        return PackageManager.PERMISSION_DENIED;
2387    }
2388
2389    @Override
2390    public int checkUidPermission(String permName, int uid) {
2391        synchronized (mPackages) {
2392            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2393            if (obj != null) {
2394                GrantedPermissions gp = (GrantedPermissions)obj;
2395                if (gp.grantedPermissions.contains(permName)) {
2396                    return PackageManager.PERMISSION_GRANTED;
2397                }
2398            } else {
2399                ArraySet<String> perms = mSystemPermissions.get(uid);
2400                if (perms != null && perms.contains(permName)) {
2401                    return PackageManager.PERMISSION_GRANTED;
2402                }
2403            }
2404        }
2405        return PackageManager.PERMISSION_DENIED;
2406    }
2407
2408    /**
2409     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2410     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2411     * @param checkShell TODO(yamasani):
2412     * @param message the message to log on security exception
2413     */
2414    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2415            boolean checkShell, String message) {
2416        if (userId < 0) {
2417            throw new IllegalArgumentException("Invalid userId " + userId);
2418        }
2419        if (checkShell) {
2420            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2421        }
2422        if (userId == UserHandle.getUserId(callingUid)) return;
2423        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2424            if (requireFullPermission) {
2425                mContext.enforceCallingOrSelfPermission(
2426                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2427            } else {
2428                try {
2429                    mContext.enforceCallingOrSelfPermission(
2430                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2431                } catch (SecurityException se) {
2432                    mContext.enforceCallingOrSelfPermission(
2433                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2434                }
2435            }
2436        }
2437    }
2438
2439    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2440        if (callingUid == Process.SHELL_UID) {
2441            if (userHandle >= 0
2442                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2443                throw new SecurityException("Shell does not have permission to access user "
2444                        + userHandle);
2445            } else if (userHandle < 0) {
2446                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2447                        + Debug.getCallers(3));
2448            }
2449        }
2450    }
2451
2452    private BasePermission findPermissionTreeLP(String permName) {
2453        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2454            if (permName.startsWith(bp.name) &&
2455                    permName.length() > bp.name.length() &&
2456                    permName.charAt(bp.name.length()) == '.') {
2457                return bp;
2458            }
2459        }
2460        return null;
2461    }
2462
2463    private BasePermission checkPermissionTreeLP(String permName) {
2464        if (permName != null) {
2465            BasePermission bp = findPermissionTreeLP(permName);
2466            if (bp != null) {
2467                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2468                    return bp;
2469                }
2470                throw new SecurityException("Calling uid "
2471                        + Binder.getCallingUid()
2472                        + " is not allowed to add to permission tree "
2473                        + bp.name + " owned by uid " + bp.uid);
2474            }
2475        }
2476        throw new SecurityException("No permission tree found for " + permName);
2477    }
2478
2479    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2480        if (s1 == null) {
2481            return s2 == null;
2482        }
2483        if (s2 == null) {
2484            return false;
2485        }
2486        if (s1.getClass() != s2.getClass()) {
2487            return false;
2488        }
2489        return s1.equals(s2);
2490    }
2491
2492    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2493        if (pi1.icon != pi2.icon) return false;
2494        if (pi1.logo != pi2.logo) return false;
2495        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2496        if (!compareStrings(pi1.name, pi2.name)) return false;
2497        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2498        // We'll take care of setting this one.
2499        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2500        // These are not currently stored in settings.
2501        //if (!compareStrings(pi1.group, pi2.group)) return false;
2502        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2503        //if (pi1.labelRes != pi2.labelRes) return false;
2504        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2505        return true;
2506    }
2507
2508    int permissionInfoFootprint(PermissionInfo info) {
2509        int size = info.name.length();
2510        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2511        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2512        return size;
2513    }
2514
2515    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2516        int size = 0;
2517        for (BasePermission perm : mSettings.mPermissions.values()) {
2518            if (perm.uid == tree.uid) {
2519                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2520            }
2521        }
2522        return size;
2523    }
2524
2525    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2526        // We calculate the max size of permissions defined by this uid and throw
2527        // if that plus the size of 'info' would exceed our stated maximum.
2528        if (tree.uid != Process.SYSTEM_UID) {
2529            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2530            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2531                throw new SecurityException("Permission tree size cap exceeded");
2532            }
2533        }
2534    }
2535
2536    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2537        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2538            throw new SecurityException("Label must be specified in permission");
2539        }
2540        BasePermission tree = checkPermissionTreeLP(info.name);
2541        BasePermission bp = mSettings.mPermissions.get(info.name);
2542        boolean added = bp == null;
2543        boolean changed = true;
2544        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2545        if (added) {
2546            enforcePermissionCapLocked(info, tree);
2547            bp = new BasePermission(info.name, tree.sourcePackage,
2548                    BasePermission.TYPE_DYNAMIC);
2549        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2550            throw new SecurityException(
2551                    "Not allowed to modify non-dynamic permission "
2552                    + info.name);
2553        } else {
2554            if (bp.protectionLevel == fixedLevel
2555                    && bp.perm.owner.equals(tree.perm.owner)
2556                    && bp.uid == tree.uid
2557                    && comparePermissionInfos(bp.perm.info, info)) {
2558                changed = false;
2559            }
2560        }
2561        bp.protectionLevel = fixedLevel;
2562        info = new PermissionInfo(info);
2563        info.protectionLevel = fixedLevel;
2564        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2565        bp.perm.info.packageName = tree.perm.info.packageName;
2566        bp.uid = tree.uid;
2567        if (added) {
2568            mSettings.mPermissions.put(info.name, bp);
2569        }
2570        if (changed) {
2571            if (!async) {
2572                mSettings.writeLPr();
2573            } else {
2574                scheduleWriteSettingsLocked();
2575            }
2576        }
2577        return added;
2578    }
2579
2580    @Override
2581    public boolean addPermission(PermissionInfo info) {
2582        synchronized (mPackages) {
2583            return addPermissionLocked(info, false);
2584        }
2585    }
2586
2587    @Override
2588    public boolean addPermissionAsync(PermissionInfo info) {
2589        synchronized (mPackages) {
2590            return addPermissionLocked(info, true);
2591        }
2592    }
2593
2594    @Override
2595    public void removePermission(String name) {
2596        synchronized (mPackages) {
2597            checkPermissionTreeLP(name);
2598            BasePermission bp = mSettings.mPermissions.get(name);
2599            if (bp != null) {
2600                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2601                    throw new SecurityException(
2602                            "Not allowed to modify non-dynamic permission "
2603                            + name);
2604                }
2605                mSettings.mPermissions.remove(name);
2606                mSettings.writeLPr();
2607            }
2608        }
2609    }
2610
2611    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2612        int index = pkg.requestedPermissions.indexOf(bp.name);
2613        if (index == -1) {
2614            throw new SecurityException("Package " + pkg.packageName
2615                    + " has not requested permission " + bp.name);
2616        }
2617        boolean isNormal =
2618                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2619                        == PermissionInfo.PROTECTION_NORMAL);
2620        boolean isDangerous =
2621                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2622                        == PermissionInfo.PROTECTION_DANGEROUS);
2623        boolean isDevelopment =
2624                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2625
2626        if (!isNormal && !isDangerous && !isDevelopment) {
2627            throw new SecurityException("Permission " + bp.name
2628                    + " is not a changeable permission type");
2629        }
2630
2631        if (isNormal || isDangerous) {
2632            if (pkg.requestedPermissionsRequired.get(index)) {
2633                throw new SecurityException("Can't change " + bp.name
2634                        + ". It is required by the application");
2635            }
2636        }
2637    }
2638
2639    @Override
2640    public void grantPermission(String packageName, String permissionName) {
2641        mContext.enforceCallingOrSelfPermission(
2642                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2643        synchronized (mPackages) {
2644            final PackageParser.Package pkg = mPackages.get(packageName);
2645            if (pkg == null) {
2646                throw new IllegalArgumentException("Unknown package: " + packageName);
2647            }
2648            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2649            if (bp == null) {
2650                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2651            }
2652
2653            checkGrantRevokePermissions(pkg, bp);
2654
2655            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2656            if (ps == null) {
2657                return;
2658            }
2659            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2660            if (gp.grantedPermissions.add(permissionName)) {
2661                if (ps.haveGids) {
2662                    gp.gids = appendInts(gp.gids, bp.gids);
2663                }
2664                mSettings.writeLPr();
2665            }
2666        }
2667    }
2668
2669    @Override
2670    public void revokePermission(String packageName, String permissionName) {
2671        int changedAppId = -1;
2672
2673        synchronized (mPackages) {
2674            final PackageParser.Package pkg = mPackages.get(packageName);
2675            if (pkg == null) {
2676                throw new IllegalArgumentException("Unknown package: " + packageName);
2677            }
2678            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2679                mContext.enforceCallingOrSelfPermission(
2680                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2681            }
2682            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2683            if (bp == null) {
2684                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2685            }
2686
2687            checkGrantRevokePermissions(pkg, bp);
2688
2689            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2690            if (ps == null) {
2691                return;
2692            }
2693            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2694            if (gp.grantedPermissions.remove(permissionName)) {
2695                gp.grantedPermissions.remove(permissionName);
2696                if (ps.haveGids) {
2697                    gp.gids = removeInts(gp.gids, bp.gids);
2698                }
2699                mSettings.writeLPr();
2700                changedAppId = ps.appId;
2701            }
2702        }
2703
2704        if (changedAppId >= 0) {
2705            // We changed the perm on someone, kill its processes.
2706            IActivityManager am = ActivityManagerNative.getDefault();
2707            if (am != null) {
2708                final int callingUserId = UserHandle.getCallingUserId();
2709                final long ident = Binder.clearCallingIdentity();
2710                try {
2711                    //XXX we should only revoke for the calling user's app permissions,
2712                    // but for now we impact all users.
2713                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2714                    //        "revoke " + permissionName);
2715                    int[] users = sUserManager.getUserIds();
2716                    for (int user : users) {
2717                        am.killUid(UserHandle.getUid(user, changedAppId),
2718                                "revoke " + permissionName);
2719                    }
2720                } catch (RemoteException e) {
2721                } finally {
2722                    Binder.restoreCallingIdentity(ident);
2723                }
2724            }
2725        }
2726    }
2727
2728    @Override
2729    public boolean isProtectedBroadcast(String actionName) {
2730        synchronized (mPackages) {
2731            return mProtectedBroadcasts.contains(actionName);
2732        }
2733    }
2734
2735    @Override
2736    public int checkSignatures(String pkg1, String pkg2) {
2737        synchronized (mPackages) {
2738            final PackageParser.Package p1 = mPackages.get(pkg1);
2739            final PackageParser.Package p2 = mPackages.get(pkg2);
2740            if (p1 == null || p1.mExtras == null
2741                    || p2 == null || p2.mExtras == null) {
2742                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2743            }
2744            return compareSignatures(p1.mSignatures, p2.mSignatures);
2745        }
2746    }
2747
2748    @Override
2749    public int checkUidSignatures(int uid1, int uid2) {
2750        // Map to base uids.
2751        uid1 = UserHandle.getAppId(uid1);
2752        uid2 = UserHandle.getAppId(uid2);
2753        // reader
2754        synchronized (mPackages) {
2755            Signature[] s1;
2756            Signature[] s2;
2757            Object obj = mSettings.getUserIdLPr(uid1);
2758            if (obj != null) {
2759                if (obj instanceof SharedUserSetting) {
2760                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2761                } else if (obj instanceof PackageSetting) {
2762                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2763                } else {
2764                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2765                }
2766            } else {
2767                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2768            }
2769            obj = mSettings.getUserIdLPr(uid2);
2770            if (obj != null) {
2771                if (obj instanceof SharedUserSetting) {
2772                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2773                } else if (obj instanceof PackageSetting) {
2774                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2775                } else {
2776                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2777                }
2778            } else {
2779                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2780            }
2781            return compareSignatures(s1, s2);
2782        }
2783    }
2784
2785    /**
2786     * Compares two sets of signatures. Returns:
2787     * <br />
2788     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2789     * <br />
2790     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2791     * <br />
2792     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2793     * <br />
2794     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2795     * <br />
2796     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2797     */
2798    static int compareSignatures(Signature[] s1, Signature[] s2) {
2799        if (s1 == null) {
2800            return s2 == null
2801                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2802                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2803        }
2804
2805        if (s2 == null) {
2806            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2807        }
2808
2809        if (s1.length != s2.length) {
2810            return PackageManager.SIGNATURE_NO_MATCH;
2811        }
2812
2813        // Since both signature sets are of size 1, we can compare without HashSets.
2814        if (s1.length == 1) {
2815            return s1[0].equals(s2[0]) ?
2816                    PackageManager.SIGNATURE_MATCH :
2817                    PackageManager.SIGNATURE_NO_MATCH;
2818        }
2819
2820        ArraySet<Signature> set1 = new ArraySet<Signature>();
2821        for (Signature sig : s1) {
2822            set1.add(sig);
2823        }
2824        ArraySet<Signature> set2 = new ArraySet<Signature>();
2825        for (Signature sig : s2) {
2826            set2.add(sig);
2827        }
2828        // Make sure s2 contains all signatures in s1.
2829        if (set1.equals(set2)) {
2830            return PackageManager.SIGNATURE_MATCH;
2831        }
2832        return PackageManager.SIGNATURE_NO_MATCH;
2833    }
2834
2835    /**
2836     * If the database version for this type of package (internal storage or
2837     * external storage) is less than the version where package signatures
2838     * were updated, return true.
2839     */
2840    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2841        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2842                DatabaseVersion.SIGNATURE_END_ENTITY))
2843                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2844                        DatabaseVersion.SIGNATURE_END_ENTITY));
2845    }
2846
2847    /**
2848     * Used for backward compatibility to make sure any packages with
2849     * certificate chains get upgraded to the new style. {@code existingSigs}
2850     * will be in the old format (since they were stored on disk from before the
2851     * system upgrade) and {@code scannedSigs} will be in the newer format.
2852     */
2853    private int compareSignaturesCompat(PackageSignatures existingSigs,
2854            PackageParser.Package scannedPkg) {
2855        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2856            return PackageManager.SIGNATURE_NO_MATCH;
2857        }
2858
2859        ArraySet<Signature> existingSet = new ArraySet<Signature>();
2860        for (Signature sig : existingSigs.mSignatures) {
2861            existingSet.add(sig);
2862        }
2863        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
2864        for (Signature sig : scannedPkg.mSignatures) {
2865            try {
2866                Signature[] chainSignatures = sig.getChainSignatures();
2867                for (Signature chainSig : chainSignatures) {
2868                    scannedCompatSet.add(chainSig);
2869                }
2870            } catch (CertificateEncodingException e) {
2871                scannedCompatSet.add(sig);
2872            }
2873        }
2874        /*
2875         * Make sure the expanded scanned set contains all signatures in the
2876         * existing one.
2877         */
2878        if (scannedCompatSet.equals(existingSet)) {
2879            // Migrate the old signatures to the new scheme.
2880            existingSigs.assignSignatures(scannedPkg.mSignatures);
2881            // The new KeySets will be re-added later in the scanning process.
2882            synchronized (mPackages) {
2883                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2884            }
2885            return PackageManager.SIGNATURE_MATCH;
2886        }
2887        return PackageManager.SIGNATURE_NO_MATCH;
2888    }
2889
2890    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2891        if (isExternal(scannedPkg)) {
2892            return mSettings.isExternalDatabaseVersionOlderThan(
2893                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
2894        } else {
2895            return mSettings.isInternalDatabaseVersionOlderThan(
2896                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
2897        }
2898    }
2899
2900    private int compareSignaturesRecover(PackageSignatures existingSigs,
2901            PackageParser.Package scannedPkg) {
2902        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
2903            return PackageManager.SIGNATURE_NO_MATCH;
2904        }
2905
2906        String msg = null;
2907        try {
2908            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
2909                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
2910                        + scannedPkg.packageName);
2911                return PackageManager.SIGNATURE_MATCH;
2912            }
2913        } catch (CertificateException e) {
2914            msg = e.getMessage();
2915        }
2916
2917        logCriticalInfo(Log.INFO,
2918                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
2919        return PackageManager.SIGNATURE_NO_MATCH;
2920    }
2921
2922    @Override
2923    public String[] getPackagesForUid(int uid) {
2924        uid = UserHandle.getAppId(uid);
2925        // reader
2926        synchronized (mPackages) {
2927            Object obj = mSettings.getUserIdLPr(uid);
2928            if (obj instanceof SharedUserSetting) {
2929                final SharedUserSetting sus = (SharedUserSetting) obj;
2930                final int N = sus.packages.size();
2931                final String[] res = new String[N];
2932                final Iterator<PackageSetting> it = sus.packages.iterator();
2933                int i = 0;
2934                while (it.hasNext()) {
2935                    res[i++] = it.next().name;
2936                }
2937                return res;
2938            } else if (obj instanceof PackageSetting) {
2939                final PackageSetting ps = (PackageSetting) obj;
2940                return new String[] { ps.name };
2941            }
2942        }
2943        return null;
2944    }
2945
2946    @Override
2947    public String getNameForUid(int uid) {
2948        // reader
2949        synchronized (mPackages) {
2950            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2951            if (obj instanceof SharedUserSetting) {
2952                final SharedUserSetting sus = (SharedUserSetting) obj;
2953                return sus.name + ":" + sus.userId;
2954            } else if (obj instanceof PackageSetting) {
2955                final PackageSetting ps = (PackageSetting) obj;
2956                return ps.name;
2957            }
2958        }
2959        return null;
2960    }
2961
2962    @Override
2963    public int getUidForSharedUser(String sharedUserName) {
2964        if(sharedUserName == null) {
2965            return -1;
2966        }
2967        // reader
2968        synchronized (mPackages) {
2969            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2970            if (suid == null) {
2971                return -1;
2972            }
2973            return suid.userId;
2974        }
2975    }
2976
2977    @Override
2978    public int getFlagsForUid(int uid) {
2979        synchronized (mPackages) {
2980            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2981            if (obj instanceof SharedUserSetting) {
2982                final SharedUserSetting sus = (SharedUserSetting) obj;
2983                return sus.pkgFlags;
2984            } else if (obj instanceof PackageSetting) {
2985                final PackageSetting ps = (PackageSetting) obj;
2986                return ps.pkgFlags;
2987            }
2988        }
2989        return 0;
2990    }
2991
2992    @Override
2993    public boolean isUidPrivileged(int uid) {
2994        uid = UserHandle.getAppId(uid);
2995        // reader
2996        synchronized (mPackages) {
2997            Object obj = mSettings.getUserIdLPr(uid);
2998            if (obj instanceof SharedUserSetting) {
2999                final SharedUserSetting sus = (SharedUserSetting) obj;
3000                final Iterator<PackageSetting> it = sus.packages.iterator();
3001                while (it.hasNext()) {
3002                    if (it.next().isPrivileged()) {
3003                        return true;
3004                    }
3005                }
3006            } else if (obj instanceof PackageSetting) {
3007                final PackageSetting ps = (PackageSetting) obj;
3008                return ps.isPrivileged();
3009            }
3010        }
3011        return false;
3012    }
3013
3014    @Override
3015    public String[] getAppOpPermissionPackages(String permissionName) {
3016        synchronized (mPackages) {
3017            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3018            if (pkgs == null) {
3019                return null;
3020            }
3021            return pkgs.toArray(new String[pkgs.size()]);
3022        }
3023    }
3024
3025    @Override
3026    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3027            int flags, int userId) {
3028        if (!sUserManager.exists(userId)) return null;
3029        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3030        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3031        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3032    }
3033
3034    @Override
3035    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3036            IntentFilter filter, int match, ComponentName activity) {
3037        final int userId = UserHandle.getCallingUserId();
3038        if (DEBUG_PREFERRED) {
3039            Log.v(TAG, "setLastChosenActivity intent=" + intent
3040                + " resolvedType=" + resolvedType
3041                + " flags=" + flags
3042                + " filter=" + filter
3043                + " match=" + match
3044                + " activity=" + activity);
3045            filter.dump(new PrintStreamPrinter(System.out), "    ");
3046        }
3047        intent.setComponent(null);
3048        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3049        // Find any earlier preferred or last chosen entries and nuke them
3050        findPreferredActivity(intent, resolvedType,
3051                flags, query, 0, false, true, false, userId);
3052        // Add the new activity as the last chosen for this filter
3053        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3054                "Setting last chosen");
3055    }
3056
3057    @Override
3058    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3059        final int userId = UserHandle.getCallingUserId();
3060        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3061        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3062        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3063                false, false, false, userId);
3064    }
3065
3066    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3067            int flags, List<ResolveInfo> query, int userId) {
3068        if (query != null) {
3069            final int N = query.size();
3070            if (N == 1) {
3071                return query.get(0);
3072            } else if (N > 1) {
3073                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3074                // If there is more than one activity with the same priority,
3075                // then let the user decide between them.
3076                ResolveInfo r0 = query.get(0);
3077                ResolveInfo r1 = query.get(1);
3078                if (DEBUG_INTENT_MATCHING || debug) {
3079                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3080                            + r1.activityInfo.name + "=" + r1.priority);
3081                }
3082                // If the first activity has a higher priority, or a different
3083                // default, then it is always desireable to pick it.
3084                if (r0.priority != r1.priority
3085                        || r0.preferredOrder != r1.preferredOrder
3086                        || r0.isDefault != r1.isDefault) {
3087                    return query.get(0);
3088                }
3089                // If we have saved a preference for a preferred activity for
3090                // this Intent, use that.
3091                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3092                        flags, query, r0.priority, true, false, debug, userId);
3093                if (ri != null) {
3094                    return ri;
3095                }
3096                if (userId != 0) {
3097                    ri = new ResolveInfo(mResolveInfo);
3098                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3099                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3100                            ri.activityInfo.applicationInfo);
3101                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3102                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3103                    return ri;
3104                }
3105                return mResolveInfo;
3106            }
3107        }
3108        return null;
3109    }
3110
3111    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3112            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3113        final int N = query.size();
3114        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3115                .get(userId);
3116        // Get the list of persistent preferred activities that handle the intent
3117        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3118        List<PersistentPreferredActivity> pprefs = ppir != null
3119                ? ppir.queryIntent(intent, resolvedType,
3120                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3121                : null;
3122        if (pprefs != null && pprefs.size() > 0) {
3123            final int M = pprefs.size();
3124            for (int i=0; i<M; i++) {
3125                final PersistentPreferredActivity ppa = pprefs.get(i);
3126                if (DEBUG_PREFERRED || debug) {
3127                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3128                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3129                            + "\n  component=" + ppa.mComponent);
3130                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3131                }
3132                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3133                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3134                if (DEBUG_PREFERRED || debug) {
3135                    Slog.v(TAG, "Found persistent preferred activity:");
3136                    if (ai != null) {
3137                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3138                    } else {
3139                        Slog.v(TAG, "  null");
3140                    }
3141                }
3142                if (ai == null) {
3143                    // This previously registered persistent preferred activity
3144                    // component is no longer known. Ignore it and do NOT remove it.
3145                    continue;
3146                }
3147                for (int j=0; j<N; j++) {
3148                    final ResolveInfo ri = query.get(j);
3149                    if (!ri.activityInfo.applicationInfo.packageName
3150                            .equals(ai.applicationInfo.packageName)) {
3151                        continue;
3152                    }
3153                    if (!ri.activityInfo.name.equals(ai.name)) {
3154                        continue;
3155                    }
3156                    //  Found a persistent preference that can handle the intent.
3157                    if (DEBUG_PREFERRED || debug) {
3158                        Slog.v(TAG, "Returning persistent preferred activity: " +
3159                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3160                    }
3161                    return ri;
3162                }
3163            }
3164        }
3165        return null;
3166    }
3167
3168    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3169            List<ResolveInfo> query, int priority, boolean always,
3170            boolean removeMatches, boolean debug, int userId) {
3171        if (!sUserManager.exists(userId)) return null;
3172        // writer
3173        synchronized (mPackages) {
3174            if (intent.getSelector() != null) {
3175                intent = intent.getSelector();
3176            }
3177            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3178
3179            // Try to find a matching persistent preferred activity.
3180            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3181                    debug, userId);
3182
3183            // If a persistent preferred activity matched, use it.
3184            if (pri != null) {
3185                return pri;
3186            }
3187
3188            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3189            // Get the list of preferred activities that handle the intent
3190            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3191            List<PreferredActivity> prefs = pir != null
3192                    ? pir.queryIntent(intent, resolvedType,
3193                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3194                    : null;
3195            if (prefs != null && prefs.size() > 0) {
3196                boolean changed = false;
3197                try {
3198                    // First figure out how good the original match set is.
3199                    // We will only allow preferred activities that came
3200                    // from the same match quality.
3201                    int match = 0;
3202
3203                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3204
3205                    final int N = query.size();
3206                    for (int j=0; j<N; j++) {
3207                        final ResolveInfo ri = query.get(j);
3208                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3209                                + ": 0x" + Integer.toHexString(match));
3210                        if (ri.match > match) {
3211                            match = ri.match;
3212                        }
3213                    }
3214
3215                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3216                            + Integer.toHexString(match));
3217
3218                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3219                    final int M = prefs.size();
3220                    for (int i=0; i<M; i++) {
3221                        final PreferredActivity pa = prefs.get(i);
3222                        if (DEBUG_PREFERRED || debug) {
3223                            Slog.v(TAG, "Checking PreferredActivity ds="
3224                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3225                                    + "\n  component=" + pa.mPref.mComponent);
3226                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3227                        }
3228                        if (pa.mPref.mMatch != match) {
3229                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3230                                    + Integer.toHexString(pa.mPref.mMatch));
3231                            continue;
3232                        }
3233                        // If it's not an "always" type preferred activity and that's what we're
3234                        // looking for, skip it.
3235                        if (always && !pa.mPref.mAlways) {
3236                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3237                            continue;
3238                        }
3239                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3240                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3241                        if (DEBUG_PREFERRED || debug) {
3242                            Slog.v(TAG, "Found preferred activity:");
3243                            if (ai != null) {
3244                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3245                            } else {
3246                                Slog.v(TAG, "  null");
3247                            }
3248                        }
3249                        if (ai == null) {
3250                            // This previously registered preferred activity
3251                            // component is no longer known.  Most likely an update
3252                            // to the app was installed and in the new version this
3253                            // component no longer exists.  Clean it up by removing
3254                            // it from the preferred activities list, and skip it.
3255                            Slog.w(TAG, "Removing dangling preferred activity: "
3256                                    + pa.mPref.mComponent);
3257                            pir.removeFilter(pa);
3258                            changed = true;
3259                            continue;
3260                        }
3261                        for (int j=0; j<N; j++) {
3262                            final ResolveInfo ri = query.get(j);
3263                            if (!ri.activityInfo.applicationInfo.packageName
3264                                    .equals(ai.applicationInfo.packageName)) {
3265                                continue;
3266                            }
3267                            if (!ri.activityInfo.name.equals(ai.name)) {
3268                                continue;
3269                            }
3270
3271                            if (removeMatches) {
3272                                pir.removeFilter(pa);
3273                                changed = true;
3274                                if (DEBUG_PREFERRED) {
3275                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3276                                }
3277                                break;
3278                            }
3279
3280                            // Okay we found a previously set preferred or last chosen app.
3281                            // If the result set is different from when this
3282                            // was created, we need to clear it and re-ask the
3283                            // user their preference, if we're looking for an "always" type entry.
3284                            if (always && !pa.mPref.sameSet(query)) {
3285                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3286                                        + intent + " type " + resolvedType);
3287                                if (DEBUG_PREFERRED) {
3288                                    Slog.v(TAG, "Removing preferred activity since set changed "
3289                                            + pa.mPref.mComponent);
3290                                }
3291                                pir.removeFilter(pa);
3292                                // Re-add the filter as a "last chosen" entry (!always)
3293                                PreferredActivity lastChosen = new PreferredActivity(
3294                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3295                                pir.addFilter(lastChosen);
3296                                changed = true;
3297                                return null;
3298                            }
3299
3300                            // Yay! Either the set matched or we're looking for the last chosen
3301                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3302                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3303                            return ri;
3304                        }
3305                    }
3306                } finally {
3307                    if (changed) {
3308                        if (DEBUG_PREFERRED) {
3309                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3310                        }
3311                        scheduleWritePackageRestrictionsLocked(userId);
3312                    }
3313                }
3314            }
3315        }
3316        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3317        return null;
3318    }
3319
3320    /*
3321     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3322     */
3323    @Override
3324    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3325            int targetUserId) {
3326        mContext.enforceCallingOrSelfPermission(
3327                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3328        List<CrossProfileIntentFilter> matches =
3329                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3330        if (matches != null) {
3331            int size = matches.size();
3332            for (int i = 0; i < size; i++) {
3333                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3334            }
3335        }
3336        return false;
3337    }
3338
3339    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3340            String resolvedType, int userId) {
3341        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3342        if (resolver != null) {
3343            return resolver.queryIntent(intent, resolvedType, false, userId);
3344        }
3345        return null;
3346    }
3347
3348    @Override
3349    public List<ResolveInfo> queryIntentActivities(Intent intent,
3350            String resolvedType, int flags, int userId) {
3351        if (!sUserManager.exists(userId)) return Collections.emptyList();
3352        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3353        ComponentName comp = intent.getComponent();
3354        if (comp == null) {
3355            if (intent.getSelector() != null) {
3356                intent = intent.getSelector();
3357                comp = intent.getComponent();
3358            }
3359        }
3360
3361        if (comp != null) {
3362            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3363            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3364            if (ai != null) {
3365                final ResolveInfo ri = new ResolveInfo();
3366                ri.activityInfo = ai;
3367                list.add(ri);
3368            }
3369            return list;
3370        }
3371
3372        // reader
3373        synchronized (mPackages) {
3374            final String pkgName = intent.getPackage();
3375            if (pkgName == null) {
3376                List<CrossProfileIntentFilter> matchingFilters =
3377                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3378                // Check for results that need to skip the current profile.
3379                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3380                        resolvedType, flags, userId);
3381                if (resolveInfo != null) {
3382                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3383                    result.add(resolveInfo);
3384                    return result;
3385                }
3386                // Check for cross profile results.
3387                resolveInfo = queryCrossProfileIntents(
3388                        matchingFilters, intent, resolvedType, flags, userId);
3389
3390                // Check for results in the current profile.
3391                List<ResolveInfo> result = mActivities.queryIntent(
3392                        intent, resolvedType, flags, userId);
3393                if (resolveInfo != null) {
3394                    result.add(resolveInfo);
3395                    Collections.sort(result, mResolvePrioritySorter);
3396                }
3397                return result;
3398            }
3399            final PackageParser.Package pkg = mPackages.get(pkgName);
3400            if (pkg != null) {
3401                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3402                        pkg.activities, userId);
3403            }
3404            return new ArrayList<ResolveInfo>();
3405        }
3406    }
3407
3408    private ResolveInfo querySkipCurrentProfileIntents(
3409            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3410            int flags, int sourceUserId) {
3411        if (matchingFilters != null) {
3412            int size = matchingFilters.size();
3413            for (int i = 0; i < size; i ++) {
3414                CrossProfileIntentFilter filter = matchingFilters.get(i);
3415                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3416                    // Checking if there are activities in the target user that can handle the
3417                    // intent.
3418                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3419                            flags, sourceUserId);
3420                    if (resolveInfo != null) {
3421                        return resolveInfo;
3422                    }
3423                }
3424            }
3425        }
3426        return null;
3427    }
3428
3429    // Return matching ResolveInfo if any for skip current profile intent filters.
3430    private ResolveInfo queryCrossProfileIntents(
3431            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3432            int flags, int sourceUserId) {
3433        if (matchingFilters != null) {
3434            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3435            // match the same intent. For performance reasons, it is better not to
3436            // run queryIntent twice for the same userId
3437            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3438            int size = matchingFilters.size();
3439            for (int i = 0; i < size; i++) {
3440                CrossProfileIntentFilter filter = matchingFilters.get(i);
3441                int targetUserId = filter.getTargetUserId();
3442                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3443                        && !alreadyTriedUserIds.get(targetUserId)) {
3444                    // Checking if there are activities in the target user that can handle the
3445                    // intent.
3446                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3447                            flags, sourceUserId);
3448                    if (resolveInfo != null) return resolveInfo;
3449                    alreadyTriedUserIds.put(targetUserId, true);
3450                }
3451            }
3452        }
3453        return null;
3454    }
3455
3456    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3457            String resolvedType, int flags, int sourceUserId) {
3458        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3459                resolvedType, flags, filter.getTargetUserId());
3460        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3461            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3462        }
3463        return null;
3464    }
3465
3466    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3467            int sourceUserId, int targetUserId) {
3468        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3469        String className;
3470        if (targetUserId == UserHandle.USER_OWNER) {
3471            className = FORWARD_INTENT_TO_USER_OWNER;
3472        } else {
3473            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3474        }
3475        ComponentName forwardingActivityComponentName = new ComponentName(
3476                mAndroidApplication.packageName, className);
3477        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3478                sourceUserId);
3479        if (targetUserId == UserHandle.USER_OWNER) {
3480            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3481            forwardingResolveInfo.noResourceId = true;
3482        }
3483        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3484        forwardingResolveInfo.priority = 0;
3485        forwardingResolveInfo.preferredOrder = 0;
3486        forwardingResolveInfo.match = 0;
3487        forwardingResolveInfo.isDefault = true;
3488        forwardingResolveInfo.filter = filter;
3489        forwardingResolveInfo.targetUserId = targetUserId;
3490        return forwardingResolveInfo;
3491    }
3492
3493    @Override
3494    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3495            Intent[] specifics, String[] specificTypes, Intent intent,
3496            String resolvedType, int flags, int userId) {
3497        if (!sUserManager.exists(userId)) return Collections.emptyList();
3498        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3499                false, "query intent activity options");
3500        final String resultsAction = intent.getAction();
3501
3502        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3503                | PackageManager.GET_RESOLVED_FILTER, userId);
3504
3505        if (DEBUG_INTENT_MATCHING) {
3506            Log.v(TAG, "Query " + intent + ": " + results);
3507        }
3508
3509        int specificsPos = 0;
3510        int N;
3511
3512        // todo: note that the algorithm used here is O(N^2).  This
3513        // isn't a problem in our current environment, but if we start running
3514        // into situations where we have more than 5 or 10 matches then this
3515        // should probably be changed to something smarter...
3516
3517        // First we go through and resolve each of the specific items
3518        // that were supplied, taking care of removing any corresponding
3519        // duplicate items in the generic resolve list.
3520        if (specifics != null) {
3521            for (int i=0; i<specifics.length; i++) {
3522                final Intent sintent = specifics[i];
3523                if (sintent == null) {
3524                    continue;
3525                }
3526
3527                if (DEBUG_INTENT_MATCHING) {
3528                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3529                }
3530
3531                String action = sintent.getAction();
3532                if (resultsAction != null && resultsAction.equals(action)) {
3533                    // If this action was explicitly requested, then don't
3534                    // remove things that have it.
3535                    action = null;
3536                }
3537
3538                ResolveInfo ri = null;
3539                ActivityInfo ai = null;
3540
3541                ComponentName comp = sintent.getComponent();
3542                if (comp == null) {
3543                    ri = resolveIntent(
3544                        sintent,
3545                        specificTypes != null ? specificTypes[i] : null,
3546                            flags, userId);
3547                    if (ri == null) {
3548                        continue;
3549                    }
3550                    if (ri == mResolveInfo) {
3551                        // ACK!  Must do something better with this.
3552                    }
3553                    ai = ri.activityInfo;
3554                    comp = new ComponentName(ai.applicationInfo.packageName,
3555                            ai.name);
3556                } else {
3557                    ai = getActivityInfo(comp, flags, userId);
3558                    if (ai == null) {
3559                        continue;
3560                    }
3561                }
3562
3563                // Look for any generic query activities that are duplicates
3564                // of this specific one, and remove them from the results.
3565                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3566                N = results.size();
3567                int j;
3568                for (j=specificsPos; j<N; j++) {
3569                    ResolveInfo sri = results.get(j);
3570                    if ((sri.activityInfo.name.equals(comp.getClassName())
3571                            && sri.activityInfo.applicationInfo.packageName.equals(
3572                                    comp.getPackageName()))
3573                        || (action != null && sri.filter.matchAction(action))) {
3574                        results.remove(j);
3575                        if (DEBUG_INTENT_MATCHING) Log.v(
3576                            TAG, "Removing duplicate item from " + j
3577                            + " due to specific " + specificsPos);
3578                        if (ri == null) {
3579                            ri = sri;
3580                        }
3581                        j--;
3582                        N--;
3583                    }
3584                }
3585
3586                // Add this specific item to its proper place.
3587                if (ri == null) {
3588                    ri = new ResolveInfo();
3589                    ri.activityInfo = ai;
3590                }
3591                results.add(specificsPos, ri);
3592                ri.specificIndex = i;
3593                specificsPos++;
3594            }
3595        }
3596
3597        // Now we go through the remaining generic results and remove any
3598        // duplicate actions that are found here.
3599        N = results.size();
3600        for (int i=specificsPos; i<N-1; i++) {
3601            final ResolveInfo rii = results.get(i);
3602            if (rii.filter == null) {
3603                continue;
3604            }
3605
3606            // Iterate over all of the actions of this result's intent
3607            // filter...  typically this should be just one.
3608            final Iterator<String> it = rii.filter.actionsIterator();
3609            if (it == null) {
3610                continue;
3611            }
3612            while (it.hasNext()) {
3613                final String action = it.next();
3614                if (resultsAction != null && resultsAction.equals(action)) {
3615                    // If this action was explicitly requested, then don't
3616                    // remove things that have it.
3617                    continue;
3618                }
3619                for (int j=i+1; j<N; j++) {
3620                    final ResolveInfo rij = results.get(j);
3621                    if (rij.filter != null && rij.filter.hasAction(action)) {
3622                        results.remove(j);
3623                        if (DEBUG_INTENT_MATCHING) Log.v(
3624                            TAG, "Removing duplicate item from " + j
3625                            + " due to action " + action + " at " + i);
3626                        j--;
3627                        N--;
3628                    }
3629                }
3630            }
3631
3632            // If the caller didn't request filter information, drop it now
3633            // so we don't have to marshall/unmarshall it.
3634            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3635                rii.filter = null;
3636            }
3637        }
3638
3639        // Filter out the caller activity if so requested.
3640        if (caller != null) {
3641            N = results.size();
3642            for (int i=0; i<N; i++) {
3643                ActivityInfo ainfo = results.get(i).activityInfo;
3644                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3645                        && caller.getClassName().equals(ainfo.name)) {
3646                    results.remove(i);
3647                    break;
3648                }
3649            }
3650        }
3651
3652        // If the caller didn't request filter information,
3653        // drop them now so we don't have to
3654        // marshall/unmarshall it.
3655        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3656            N = results.size();
3657            for (int i=0; i<N; i++) {
3658                results.get(i).filter = null;
3659            }
3660        }
3661
3662        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3663        return results;
3664    }
3665
3666    @Override
3667    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3668            int userId) {
3669        if (!sUserManager.exists(userId)) return Collections.emptyList();
3670        ComponentName comp = intent.getComponent();
3671        if (comp == null) {
3672            if (intent.getSelector() != null) {
3673                intent = intent.getSelector();
3674                comp = intent.getComponent();
3675            }
3676        }
3677        if (comp != null) {
3678            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3679            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3680            if (ai != null) {
3681                ResolveInfo ri = new ResolveInfo();
3682                ri.activityInfo = ai;
3683                list.add(ri);
3684            }
3685            return list;
3686        }
3687
3688        // reader
3689        synchronized (mPackages) {
3690            String pkgName = intent.getPackage();
3691            if (pkgName == null) {
3692                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3693            }
3694            final PackageParser.Package pkg = mPackages.get(pkgName);
3695            if (pkg != null) {
3696                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3697                        userId);
3698            }
3699            return null;
3700        }
3701    }
3702
3703    @Override
3704    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3705        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3706        if (!sUserManager.exists(userId)) return null;
3707        if (query != null) {
3708            if (query.size() >= 1) {
3709                // If there is more than one service with the same priority,
3710                // just arbitrarily pick the first one.
3711                return query.get(0);
3712            }
3713        }
3714        return null;
3715    }
3716
3717    @Override
3718    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3719            int userId) {
3720        if (!sUserManager.exists(userId)) return Collections.emptyList();
3721        ComponentName comp = intent.getComponent();
3722        if (comp == null) {
3723            if (intent.getSelector() != null) {
3724                intent = intent.getSelector();
3725                comp = intent.getComponent();
3726            }
3727        }
3728        if (comp != null) {
3729            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3730            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3731            if (si != null) {
3732                final ResolveInfo ri = new ResolveInfo();
3733                ri.serviceInfo = si;
3734                list.add(ri);
3735            }
3736            return list;
3737        }
3738
3739        // reader
3740        synchronized (mPackages) {
3741            String pkgName = intent.getPackage();
3742            if (pkgName == null) {
3743                return mServices.queryIntent(intent, resolvedType, flags, userId);
3744            }
3745            final PackageParser.Package pkg = mPackages.get(pkgName);
3746            if (pkg != null) {
3747                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3748                        userId);
3749            }
3750            return null;
3751        }
3752    }
3753
3754    @Override
3755    public List<ResolveInfo> queryIntentContentProviders(
3756            Intent intent, String resolvedType, int flags, int userId) {
3757        if (!sUserManager.exists(userId)) return Collections.emptyList();
3758        ComponentName comp = intent.getComponent();
3759        if (comp == null) {
3760            if (intent.getSelector() != null) {
3761                intent = intent.getSelector();
3762                comp = intent.getComponent();
3763            }
3764        }
3765        if (comp != null) {
3766            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3767            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3768            if (pi != null) {
3769                final ResolveInfo ri = new ResolveInfo();
3770                ri.providerInfo = pi;
3771                list.add(ri);
3772            }
3773            return list;
3774        }
3775
3776        // reader
3777        synchronized (mPackages) {
3778            String pkgName = intent.getPackage();
3779            if (pkgName == null) {
3780                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3781            }
3782            final PackageParser.Package pkg = mPackages.get(pkgName);
3783            if (pkg != null) {
3784                return mProviders.queryIntentForPackage(
3785                        intent, resolvedType, flags, pkg.providers, userId);
3786            }
3787            return null;
3788        }
3789    }
3790
3791    @Override
3792    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3793        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3794
3795        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3796
3797        // writer
3798        synchronized (mPackages) {
3799            ArrayList<PackageInfo> list;
3800            if (listUninstalled) {
3801                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3802                for (PackageSetting ps : mSettings.mPackages.values()) {
3803                    PackageInfo pi;
3804                    if (ps.pkg != null) {
3805                        pi = generatePackageInfo(ps.pkg, flags, userId);
3806                    } else {
3807                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3808                    }
3809                    if (pi != null) {
3810                        list.add(pi);
3811                    }
3812                }
3813            } else {
3814                list = new ArrayList<PackageInfo>(mPackages.size());
3815                for (PackageParser.Package p : mPackages.values()) {
3816                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3817                    if (pi != null) {
3818                        list.add(pi);
3819                    }
3820                }
3821            }
3822
3823            return new ParceledListSlice<PackageInfo>(list);
3824        }
3825    }
3826
3827    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3828            String[] permissions, boolean[] tmp, int flags, int userId) {
3829        int numMatch = 0;
3830        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3831        for (int i=0; i<permissions.length; i++) {
3832            if (gp.grantedPermissions.contains(permissions[i])) {
3833                tmp[i] = true;
3834                numMatch++;
3835            } else {
3836                tmp[i] = false;
3837            }
3838        }
3839        if (numMatch == 0) {
3840            return;
3841        }
3842        PackageInfo pi;
3843        if (ps.pkg != null) {
3844            pi = generatePackageInfo(ps.pkg, flags, userId);
3845        } else {
3846            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3847        }
3848        // The above might return null in cases of uninstalled apps or install-state
3849        // skew across users/profiles.
3850        if (pi != null) {
3851            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3852                if (numMatch == permissions.length) {
3853                    pi.requestedPermissions = permissions;
3854                } else {
3855                    pi.requestedPermissions = new String[numMatch];
3856                    numMatch = 0;
3857                    for (int i=0; i<permissions.length; i++) {
3858                        if (tmp[i]) {
3859                            pi.requestedPermissions[numMatch] = permissions[i];
3860                            numMatch++;
3861                        }
3862                    }
3863                }
3864            }
3865            list.add(pi);
3866        }
3867    }
3868
3869    @Override
3870    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3871            String[] permissions, int flags, int userId) {
3872        if (!sUserManager.exists(userId)) return null;
3873        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3874
3875        // writer
3876        synchronized (mPackages) {
3877            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3878            boolean[] tmpBools = new boolean[permissions.length];
3879            if (listUninstalled) {
3880                for (PackageSetting ps : mSettings.mPackages.values()) {
3881                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3882                }
3883            } else {
3884                for (PackageParser.Package pkg : mPackages.values()) {
3885                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3886                    if (ps != null) {
3887                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3888                                userId);
3889                    }
3890                }
3891            }
3892
3893            return new ParceledListSlice<PackageInfo>(list);
3894        }
3895    }
3896
3897    @Override
3898    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3899        if (!sUserManager.exists(userId)) return null;
3900        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3901
3902        // writer
3903        synchronized (mPackages) {
3904            ArrayList<ApplicationInfo> list;
3905            if (listUninstalled) {
3906                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3907                for (PackageSetting ps : mSettings.mPackages.values()) {
3908                    ApplicationInfo ai;
3909                    if (ps.pkg != null) {
3910                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3911                                ps.readUserState(userId), userId);
3912                    } else {
3913                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3914                    }
3915                    if (ai != null) {
3916                        list.add(ai);
3917                    }
3918                }
3919            } else {
3920                list = new ArrayList<ApplicationInfo>(mPackages.size());
3921                for (PackageParser.Package p : mPackages.values()) {
3922                    if (p.mExtras != null) {
3923                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3924                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3925                        if (ai != null) {
3926                            list.add(ai);
3927                        }
3928                    }
3929                }
3930            }
3931
3932            return new ParceledListSlice<ApplicationInfo>(list);
3933        }
3934    }
3935
3936    public List<ApplicationInfo> getPersistentApplications(int flags) {
3937        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3938
3939        // reader
3940        synchronized (mPackages) {
3941            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3942            final int userId = UserHandle.getCallingUserId();
3943            while (i.hasNext()) {
3944                final PackageParser.Package p = i.next();
3945                if (p.applicationInfo != null
3946                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3947                        && (!mSafeMode || isSystemApp(p))) {
3948                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3949                    if (ps != null) {
3950                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3951                                ps.readUserState(userId), userId);
3952                        if (ai != null) {
3953                            finalList.add(ai);
3954                        }
3955                    }
3956                }
3957            }
3958        }
3959
3960        return finalList;
3961    }
3962
3963    @Override
3964    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3965        if (!sUserManager.exists(userId)) return null;
3966        // reader
3967        synchronized (mPackages) {
3968            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3969            PackageSetting ps = provider != null
3970                    ? mSettings.mPackages.get(provider.owner.packageName)
3971                    : null;
3972            return ps != null
3973                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3974                    && (!mSafeMode || (provider.info.applicationInfo.flags
3975                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3976                    ? PackageParser.generateProviderInfo(provider, flags,
3977                            ps.readUserState(userId), userId)
3978                    : null;
3979        }
3980    }
3981
3982    /**
3983     * @deprecated
3984     */
3985    @Deprecated
3986    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3987        // reader
3988        synchronized (mPackages) {
3989            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3990                    .entrySet().iterator();
3991            final int userId = UserHandle.getCallingUserId();
3992            while (i.hasNext()) {
3993                Map.Entry<String, PackageParser.Provider> entry = i.next();
3994                PackageParser.Provider p = entry.getValue();
3995                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3996
3997                if (ps != null && p.syncable
3998                        && (!mSafeMode || (p.info.applicationInfo.flags
3999                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4000                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4001                            ps.readUserState(userId), userId);
4002                    if (info != null) {
4003                        outNames.add(entry.getKey());
4004                        outInfo.add(info);
4005                    }
4006                }
4007            }
4008        }
4009    }
4010
4011    @Override
4012    public List<ProviderInfo> queryContentProviders(String processName,
4013            int uid, int flags) {
4014        ArrayList<ProviderInfo> finalList = null;
4015        // reader
4016        synchronized (mPackages) {
4017            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4018            final int userId = processName != null ?
4019                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4020            while (i.hasNext()) {
4021                final PackageParser.Provider p = i.next();
4022                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4023                if (ps != null && p.info.authority != null
4024                        && (processName == null
4025                                || (p.info.processName.equals(processName)
4026                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4027                        && mSettings.isEnabledLPr(p.info, flags, userId)
4028                        && (!mSafeMode
4029                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4030                    if (finalList == null) {
4031                        finalList = new ArrayList<ProviderInfo>(3);
4032                    }
4033                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4034                            ps.readUserState(userId), userId);
4035                    if (info != null) {
4036                        finalList.add(info);
4037                    }
4038                }
4039            }
4040        }
4041
4042        if (finalList != null) {
4043            Collections.sort(finalList, mProviderInitOrderSorter);
4044        }
4045
4046        return finalList;
4047    }
4048
4049    @Override
4050    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4051            int flags) {
4052        // reader
4053        synchronized (mPackages) {
4054            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4055            return PackageParser.generateInstrumentationInfo(i, flags);
4056        }
4057    }
4058
4059    @Override
4060    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4061            int flags) {
4062        ArrayList<InstrumentationInfo> finalList =
4063            new ArrayList<InstrumentationInfo>();
4064
4065        // reader
4066        synchronized (mPackages) {
4067            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4068            while (i.hasNext()) {
4069                final PackageParser.Instrumentation p = i.next();
4070                if (targetPackage == null
4071                        || targetPackage.equals(p.info.targetPackage)) {
4072                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4073                            flags);
4074                    if (ii != null) {
4075                        finalList.add(ii);
4076                    }
4077                }
4078            }
4079        }
4080
4081        return finalList;
4082    }
4083
4084    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4085        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4086        if (overlays == null) {
4087            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4088            return;
4089        }
4090        for (PackageParser.Package opkg : overlays.values()) {
4091            // Not much to do if idmap fails: we already logged the error
4092            // and we certainly don't want to abort installation of pkg simply
4093            // because an overlay didn't fit properly. For these reasons,
4094            // ignore the return value of createIdmapForPackagePairLI.
4095            createIdmapForPackagePairLI(pkg, opkg);
4096        }
4097    }
4098
4099    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4100            PackageParser.Package opkg) {
4101        if (!opkg.mTrustedOverlay) {
4102            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4103                    opkg.baseCodePath + ": overlay not trusted");
4104            return false;
4105        }
4106        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4107        if (overlaySet == null) {
4108            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4109                    opkg.baseCodePath + " but target package has no known overlays");
4110            return false;
4111        }
4112        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4113        // TODO: generate idmap for split APKs
4114        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4115            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4116                    + opkg.baseCodePath);
4117            return false;
4118        }
4119        PackageParser.Package[] overlayArray =
4120            overlaySet.values().toArray(new PackageParser.Package[0]);
4121        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4122            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4123                return p1.mOverlayPriority - p2.mOverlayPriority;
4124            }
4125        };
4126        Arrays.sort(overlayArray, cmp);
4127
4128        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4129        int i = 0;
4130        for (PackageParser.Package p : overlayArray) {
4131            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4132        }
4133        return true;
4134    }
4135
4136    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4137        final File[] files = dir.listFiles();
4138        if (ArrayUtils.isEmpty(files)) {
4139            Log.d(TAG, "No files in app dir " + dir);
4140            return;
4141        }
4142
4143        if (DEBUG_PACKAGE_SCANNING) {
4144            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4145                    + " flags=0x" + Integer.toHexString(parseFlags));
4146        }
4147
4148        for (File file : files) {
4149            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4150                    && !PackageInstallerService.isStageName(file.getName());
4151            if (!isPackage) {
4152                // Ignore entries which are not packages
4153                continue;
4154            }
4155            try {
4156                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4157                        scanFlags, currentTime, null);
4158            } catch (PackageManagerException e) {
4159                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4160
4161                // Delete invalid userdata apps
4162                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4163                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4164                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4165                    if (file.isDirectory()) {
4166                        FileUtils.deleteContents(file);
4167                    }
4168                    file.delete();
4169                }
4170            }
4171        }
4172    }
4173
4174    private static File getSettingsProblemFile() {
4175        File dataDir = Environment.getDataDirectory();
4176        File systemDir = new File(dataDir, "system");
4177        File fname = new File(systemDir, "uiderrors.txt");
4178        return fname;
4179    }
4180
4181    static void reportSettingsProblem(int priority, String msg) {
4182        logCriticalInfo(priority, msg);
4183    }
4184
4185    static void logCriticalInfo(int priority, String msg) {
4186        Slog.println(priority, TAG, msg);
4187        EventLogTags.writePmCriticalInfo(msg);
4188        try {
4189            File fname = getSettingsProblemFile();
4190            FileOutputStream out = new FileOutputStream(fname, true);
4191            PrintWriter pw = new FastPrintWriter(out);
4192            SimpleDateFormat formatter = new SimpleDateFormat();
4193            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4194            pw.println(dateString + ": " + msg);
4195            pw.close();
4196            FileUtils.setPermissions(
4197                    fname.toString(),
4198                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4199                    -1, -1);
4200        } catch (java.io.IOException e) {
4201        }
4202    }
4203
4204    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4205            PackageParser.Package pkg, File srcFile, int parseFlags)
4206            throws PackageManagerException {
4207        if (ps != null
4208                && ps.codePath.equals(srcFile)
4209                && ps.timeStamp == srcFile.lastModified()
4210                && !isCompatSignatureUpdateNeeded(pkg)
4211                && !isRecoverSignatureUpdateNeeded(pkg)) {
4212            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4213            if (ps.signatures.mSignatures != null
4214                    && ps.signatures.mSignatures.length != 0
4215                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4216                // Optimization: reuse the existing cached certificates
4217                // if the package appears to be unchanged.
4218                pkg.mSignatures = ps.signatures.mSignatures;
4219                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4220                synchronized (mPackages) {
4221                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4222                }
4223                return;
4224            }
4225
4226            Slog.w(TAG, "PackageSetting for " + ps.name
4227                    + " is missing signatures.  Collecting certs again to recover them.");
4228        } else {
4229            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4230        }
4231
4232        try {
4233            pp.collectCertificates(pkg, parseFlags);
4234            pp.collectManifestDigest(pkg);
4235        } catch (PackageParserException e) {
4236            throw PackageManagerException.from(e);
4237        }
4238    }
4239
4240    /*
4241     *  Scan a package and return the newly parsed package.
4242     *  Returns null in case of errors and the error code is stored in mLastScanError
4243     */
4244    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4245            long currentTime, UserHandle user) throws PackageManagerException {
4246        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4247        parseFlags |= mDefParseFlags;
4248        PackageParser pp = new PackageParser();
4249        pp.setSeparateProcesses(mSeparateProcesses);
4250        pp.setOnlyCoreApps(mOnlyCore);
4251        pp.setDisplayMetrics(mMetrics);
4252
4253        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4254            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4255        }
4256
4257        final PackageParser.Package pkg;
4258        try {
4259            pkg = pp.parsePackage(scanFile, parseFlags);
4260        } catch (PackageParserException e) {
4261            throw PackageManagerException.from(e);
4262        }
4263
4264        PackageSetting ps = null;
4265        PackageSetting updatedPkg;
4266        // reader
4267        synchronized (mPackages) {
4268            // Look to see if we already know about this package.
4269            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4270            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4271                // This package has been renamed to its original name.  Let's
4272                // use that.
4273                ps = mSettings.peekPackageLPr(oldName);
4274            }
4275            // If there was no original package, see one for the real package name.
4276            if (ps == null) {
4277                ps = mSettings.peekPackageLPr(pkg.packageName);
4278            }
4279            // Check to see if this package could be hiding/updating a system
4280            // package.  Must look for it either under the original or real
4281            // package name depending on our state.
4282            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4283            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4284        }
4285        boolean updatedPkgBetter = false;
4286        // First check if this is a system package that may involve an update
4287        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4288            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
4289            // it needs to drop FLAG_PRIVILEGED.
4290            if (locationIsPrivileged(scanFile)) {
4291                updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4292            } else {
4293                updatedPkg.pkgFlags &= ~ApplicationInfo.FLAG_PRIVILEGED;
4294            }
4295
4296            if (ps != null && !ps.codePath.equals(scanFile)) {
4297                // The path has changed from what was last scanned...  check the
4298                // version of the new path against what we have stored to determine
4299                // what to do.
4300                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4301                if (pkg.mVersionCode <= ps.versionCode) {
4302                    // The system package has been updated and the code path does not match
4303                    // Ignore entry. Skip it.
4304                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
4305                            + " ignored: updated version " + ps.versionCode
4306                            + " better than this " + pkg.mVersionCode);
4307                    if (!updatedPkg.codePath.equals(scanFile)) {
4308                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4309                                + ps.name + " changing from " + updatedPkg.codePathString
4310                                + " to " + scanFile);
4311                        updatedPkg.codePath = scanFile;
4312                        updatedPkg.codePathString = scanFile.toString();
4313                        updatedPkg.resourcePath = scanFile;
4314                        updatedPkg.resourcePathString = scanFile.toString();
4315                    }
4316                    updatedPkg.pkg = pkg;
4317                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4318                } else {
4319                    // The current app on the system partition is better than
4320                    // what we have updated to on the data partition; switch
4321                    // back to the system partition version.
4322                    // At this point, its safely assumed that package installation for
4323                    // apps in system partition will go through. If not there won't be a working
4324                    // version of the app
4325                    // writer
4326                    synchronized (mPackages) {
4327                        // Just remove the loaded entries from package lists.
4328                        mPackages.remove(ps.name);
4329                    }
4330
4331                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4332                            + " reverting from " + ps.codePathString
4333                            + ": new version " + pkg.mVersionCode
4334                            + " better than installed " + ps.versionCode);
4335
4336                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4337                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4338                            getAppDexInstructionSets(ps));
4339                    synchronized (mInstallLock) {
4340                        args.cleanUpResourcesLI();
4341                    }
4342                    synchronized (mPackages) {
4343                        mSettings.enableSystemPackageLPw(ps.name);
4344                    }
4345                    updatedPkgBetter = true;
4346                }
4347            }
4348        }
4349
4350        if (updatedPkg != null) {
4351            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4352            // initially
4353            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4354
4355            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4356            // flag set initially
4357            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4358                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4359            }
4360        }
4361
4362        // Verify certificates against what was last scanned
4363        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4364
4365        /*
4366         * A new system app appeared, but we already had a non-system one of the
4367         * same name installed earlier.
4368         */
4369        boolean shouldHideSystemApp = false;
4370        if (updatedPkg == null && ps != null
4371                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4372            /*
4373             * Check to make sure the signatures match first. If they don't,
4374             * wipe the installed application and its data.
4375             */
4376            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4377                    != PackageManager.SIGNATURE_MATCH) {
4378                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
4379                        + " signatures don't match existing userdata copy; removing");
4380                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4381                ps = null;
4382            } else {
4383                /*
4384                 * If the newly-added system app is an older version than the
4385                 * already installed version, hide it. It will be scanned later
4386                 * and re-added like an update.
4387                 */
4388                if (pkg.mVersionCode <= ps.versionCode) {
4389                    shouldHideSystemApp = true;
4390                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
4391                            + " but new version " + pkg.mVersionCode + " better than installed "
4392                            + ps.versionCode + "; hiding system");
4393                } else {
4394                    /*
4395                     * The newly found system app is a newer version that the
4396                     * one previously installed. Simply remove the
4397                     * already-installed application and replace it with our own
4398                     * while keeping the application data.
4399                     */
4400                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4401                            + " reverting from " + ps.codePathString + ": new version "
4402                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
4403                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4404                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4405                            getAppDexInstructionSets(ps));
4406                    synchronized (mInstallLock) {
4407                        args.cleanUpResourcesLI();
4408                    }
4409                }
4410            }
4411        }
4412
4413        // The apk is forward locked (not public) if its code and resources
4414        // are kept in different files. (except for app in either system or
4415        // vendor path).
4416        // TODO grab this value from PackageSettings
4417        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4418            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4419                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4420            }
4421        }
4422
4423        // TODO: extend to support forward-locked splits
4424        String resourcePath = null;
4425        String baseResourcePath = null;
4426        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4427            if (ps != null && ps.resourcePathString != null) {
4428                resourcePath = ps.resourcePathString;
4429                baseResourcePath = ps.resourcePathString;
4430            } else {
4431                // Should not happen at all. Just log an error.
4432                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4433            }
4434        } else {
4435            resourcePath = pkg.codePath;
4436            baseResourcePath = pkg.baseCodePath;
4437        }
4438
4439        // Set application objects path explicitly.
4440        pkg.applicationInfo.setCodePath(pkg.codePath);
4441        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4442        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4443        pkg.applicationInfo.setResourcePath(resourcePath);
4444        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4445        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4446
4447        // Note that we invoke the following method only if we are about to unpack an application
4448        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4449                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4450
4451        /*
4452         * If the system app should be overridden by a previously installed
4453         * data, hide the system app now and let the /data/app scan pick it up
4454         * again.
4455         */
4456        if (shouldHideSystemApp) {
4457            synchronized (mPackages) {
4458                /*
4459                 * We have to grant systems permissions before we hide, because
4460                 * grantPermissions will assume the package update is trying to
4461                 * expand its permissions.
4462                 */
4463                grantPermissionsLPw(pkg, true, pkg.packageName);
4464                mSettings.disableSystemPackageLPw(pkg.packageName);
4465            }
4466        }
4467
4468        return scannedPkg;
4469    }
4470
4471    private static String fixProcessName(String defProcessName,
4472            String processName, int uid) {
4473        if (processName == null) {
4474            return defProcessName;
4475        }
4476        return processName;
4477    }
4478
4479    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4480            throws PackageManagerException {
4481        if (pkgSetting.signatures.mSignatures != null) {
4482            // Already existing package. Make sure signatures match
4483            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4484                    == PackageManager.SIGNATURE_MATCH;
4485            if (!match) {
4486                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4487                        == PackageManager.SIGNATURE_MATCH;
4488            }
4489            if (!match) {
4490                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
4491                        == PackageManager.SIGNATURE_MATCH;
4492            }
4493            if (!match) {
4494                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4495                        + pkg.packageName + " signatures do not match the "
4496                        + "previously installed version; ignoring!");
4497            }
4498        }
4499
4500        // Check for shared user signatures
4501        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4502            // Already existing package. Make sure signatures match
4503            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4504                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4505            if (!match) {
4506                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4507                        == PackageManager.SIGNATURE_MATCH;
4508            }
4509            if (!match) {
4510                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
4511                        == PackageManager.SIGNATURE_MATCH;
4512            }
4513            if (!match) {
4514                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4515                        "Package " + pkg.packageName
4516                        + " has no signatures that match those in shared user "
4517                        + pkgSetting.sharedUser.name + "; ignoring!");
4518            }
4519        }
4520    }
4521
4522    /**
4523     * Enforces that only the system UID or root's UID can call a method exposed
4524     * via Binder.
4525     *
4526     * @param message used as message if SecurityException is thrown
4527     * @throws SecurityException if the caller is not system or root
4528     */
4529    private static final void enforceSystemOrRoot(String message) {
4530        final int uid = Binder.getCallingUid();
4531        if (uid != Process.SYSTEM_UID && uid != 0) {
4532            throw new SecurityException(message);
4533        }
4534    }
4535
4536    @Override
4537    public void performBootDexOpt() {
4538        enforceSystemOrRoot("Only the system can request dexopt be performed");
4539
4540        // Before everything else, see whether we need to fstrim.
4541        try {
4542            IMountService ms = PackageHelper.getMountService();
4543            if (ms != null) {
4544                final boolean isUpgrade = isUpgrade();
4545                boolean doTrim = isUpgrade;
4546                if (doTrim) {
4547                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
4548                } else {
4549                    final long interval = android.provider.Settings.Global.getLong(
4550                            mContext.getContentResolver(),
4551                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
4552                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
4553                    if (interval > 0) {
4554                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
4555                        if (timeSinceLast > interval) {
4556                            doTrim = true;
4557                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
4558                                    + "; running immediately");
4559                        }
4560                    }
4561                }
4562                if (doTrim) {
4563                    if (!isFirstBoot()) {
4564                        try {
4565                            ActivityManagerNative.getDefault().showBootMessage(
4566                                    mContext.getResources().getString(
4567                                            R.string.android_upgrading_fstrim), true);
4568                        } catch (RemoteException e) {
4569                        }
4570                    }
4571                    ms.runMaintenance();
4572                }
4573            } else {
4574                Slog.e(TAG, "Mount service unavailable!");
4575            }
4576        } catch (RemoteException e) {
4577            // Can't happen; MountService is local
4578        }
4579
4580        final ArraySet<PackageParser.Package> pkgs;
4581        synchronized (mPackages) {
4582            pkgs = mDeferredDexOpt;
4583            mDeferredDexOpt = null;
4584        }
4585
4586        if (pkgs != null) {
4587            // Sort apps by importance for dexopt ordering. Important apps are given more priority
4588            // in case the device runs out of space.
4589            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
4590            // Give priority to core apps.
4591            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4592                PackageParser.Package pkg = it.next();
4593                if (pkg.coreApp) {
4594                    if (DEBUG_DEXOPT) {
4595                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
4596                    }
4597                    sortedPkgs.add(pkg);
4598                    it.remove();
4599                }
4600            }
4601            // Give priority to system apps that listen for pre boot complete.
4602            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
4603            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
4604            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4605                PackageParser.Package pkg = it.next();
4606                if (pkgNames.contains(pkg.packageName)) {
4607                    if (DEBUG_DEXOPT) {
4608                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
4609                    }
4610                    sortedPkgs.add(pkg);
4611                    it.remove();
4612                }
4613            }
4614            // Give priority to system apps.
4615            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4616                PackageParser.Package pkg = it.next();
4617                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4618                    if (DEBUG_DEXOPT) {
4619                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
4620                    }
4621                    sortedPkgs.add(pkg);
4622                    it.remove();
4623                }
4624            }
4625            // Give priority to updated system apps.
4626            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4627                PackageParser.Package pkg = it.next();
4628                if (isUpdatedSystemApp(pkg)) {
4629                    if (DEBUG_DEXOPT) {
4630                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
4631                    }
4632                    sortedPkgs.add(pkg);
4633                    it.remove();
4634                }
4635            }
4636            // Give priority to apps that listen for boot complete.
4637            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
4638            pkgNames = getPackageNamesForIntent(intent);
4639            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4640                PackageParser.Package pkg = it.next();
4641                if (pkgNames.contains(pkg.packageName)) {
4642                    if (DEBUG_DEXOPT) {
4643                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
4644                    }
4645                    sortedPkgs.add(pkg);
4646                    it.remove();
4647                }
4648            }
4649            // Filter out packages that aren't recently used.
4650            filterRecentlyUsedApps(pkgs);
4651            // Add all remaining apps.
4652            for (PackageParser.Package pkg : pkgs) {
4653                if (DEBUG_DEXOPT) {
4654                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
4655                }
4656                sortedPkgs.add(pkg);
4657            }
4658
4659            // If we want to be lazy, filter everything that wasn't recently used.
4660            if (mLazyDexOpt) {
4661                filterRecentlyUsedApps(sortedPkgs);
4662            }
4663
4664            int i = 0;
4665            int total = sortedPkgs.size();
4666            File dataDir = Environment.getDataDirectory();
4667            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
4668            if (lowThreshold == 0) {
4669                throw new IllegalStateException("Invalid low memory threshold");
4670            }
4671            for (PackageParser.Package pkg : sortedPkgs) {
4672                long usableSpace = dataDir.getUsableSpace();
4673                if (usableSpace < lowThreshold) {
4674                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
4675                    break;
4676                }
4677                performBootDexOpt(pkg, ++i, total);
4678            }
4679        }
4680    }
4681
4682    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
4683        // Filter out packages that aren't recently used.
4684        //
4685        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4686        // should do a full dexopt.
4687        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4688            int total = pkgs.size();
4689            int skipped = 0;
4690            long now = System.currentTimeMillis();
4691            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4692                PackageParser.Package pkg = i.next();
4693                long then = pkg.mLastPackageUsageTimeInMills;
4694                if (then + mDexOptLRUThresholdInMills < now) {
4695                    if (DEBUG_DEXOPT) {
4696                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4697                              ((then == 0) ? "never" : new Date(then)));
4698                    }
4699                    i.remove();
4700                    skipped++;
4701                }
4702            }
4703            if (DEBUG_DEXOPT) {
4704                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4705            }
4706        }
4707    }
4708
4709    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
4710        List<ResolveInfo> ris = null;
4711        try {
4712            ris = AppGlobals.getPackageManager().queryIntentReceivers(
4713                    intent, null, 0, UserHandle.USER_OWNER);
4714        } catch (RemoteException e) {
4715        }
4716        ArraySet<String> pkgNames = new ArraySet<String>();
4717        if (ris != null) {
4718            for (ResolveInfo ri : ris) {
4719                pkgNames.add(ri.activityInfo.packageName);
4720            }
4721        }
4722        return pkgNames;
4723    }
4724
4725    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
4726        if (DEBUG_DEXOPT) {
4727            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
4728        }
4729        if (!isFirstBoot()) {
4730            try {
4731                ActivityManagerNative.getDefault().showBootMessage(
4732                        mContext.getResources().getString(R.string.android_upgrading_apk,
4733                                curr, total), true);
4734            } catch (RemoteException e) {
4735            }
4736        }
4737        PackageParser.Package p = pkg;
4738        synchronized (mInstallLock) {
4739            performDexOptLI(p, null /* instruction sets */, false /* force dex */,
4740                            false /* defer */, true /* include dependencies */);
4741        }
4742    }
4743
4744    @Override
4745    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4746        return performDexOpt(packageName, instructionSet, false);
4747    }
4748
4749    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4750        if (info.primaryCpuAbi == null) {
4751            return getPreferredInstructionSet();
4752        }
4753
4754        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4755    }
4756
4757    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4758        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4759        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4760        if (!dexopt && !updateUsage) {
4761            // We aren't going to dexopt or update usage, so bail early.
4762            return false;
4763        }
4764        PackageParser.Package p;
4765        final String targetInstructionSet;
4766        synchronized (mPackages) {
4767            p = mPackages.get(packageName);
4768            if (p == null) {
4769                return false;
4770            }
4771            if (updateUsage) {
4772                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4773            }
4774            mPackageUsage.write(false);
4775            if (!dexopt) {
4776                // We aren't going to dexopt, so bail early.
4777                return false;
4778            }
4779
4780            targetInstructionSet = instructionSet != null ? instructionSet :
4781                    getPrimaryInstructionSet(p.applicationInfo);
4782            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4783                return false;
4784            }
4785        }
4786
4787        synchronized (mInstallLock) {
4788            final String[] instructionSets = new String[] { targetInstructionSet };
4789            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4790                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4791        }
4792    }
4793
4794    public ArraySet<String> getPackagesThatNeedDexOpt() {
4795        ArraySet<String> pkgs = null;
4796        synchronized (mPackages) {
4797            for (PackageParser.Package p : mPackages.values()) {
4798                if (DEBUG_DEXOPT) {
4799                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4800                }
4801                if (!p.mDexOptPerformed.isEmpty()) {
4802                    continue;
4803                }
4804                if (pkgs == null) {
4805                    pkgs = new ArraySet<String>();
4806                }
4807                pkgs.add(p.packageName);
4808            }
4809        }
4810        return pkgs;
4811    }
4812
4813    public void shutdown() {
4814        mPackageUsage.write(true);
4815    }
4816
4817    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4818             boolean forceDex, boolean defer, ArraySet<String> done) {
4819        for (int i=0; i<libs.size(); i++) {
4820            PackageParser.Package libPkg;
4821            String libName;
4822            synchronized (mPackages) {
4823                libName = libs.get(i);
4824                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4825                if (lib != null && lib.apk != null) {
4826                    libPkg = mPackages.get(lib.apk);
4827                } else {
4828                    libPkg = null;
4829                }
4830            }
4831            if (libPkg != null && !done.contains(libName)) {
4832                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4833            }
4834        }
4835    }
4836
4837    static final int DEX_OPT_SKIPPED = 0;
4838    static final int DEX_OPT_PERFORMED = 1;
4839    static final int DEX_OPT_DEFERRED = 2;
4840    static final int DEX_OPT_FAILED = -1;
4841
4842    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4843            boolean forceDex, boolean defer, ArraySet<String> done) {
4844        final String[] instructionSets = targetInstructionSets != null ?
4845                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4846
4847        if (done != null) {
4848            done.add(pkg.packageName);
4849            if (pkg.usesLibraries != null) {
4850                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4851            }
4852            if (pkg.usesOptionalLibraries != null) {
4853                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4854            }
4855        }
4856
4857        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4858            return DEX_OPT_SKIPPED;
4859        }
4860
4861        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4862
4863        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4864        boolean performedDexOpt = false;
4865        // There are three basic cases here:
4866        // 1.) we need to dexopt, either because we are forced or it is needed
4867        // 2.) we are defering a needed dexopt
4868        // 3.) we are skipping an unneeded dexopt
4869        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4870        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4871            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4872                continue;
4873            }
4874
4875            for (String path : paths) {
4876                try {
4877                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4878                    // patckage or the one we find does not match the image checksum (i.e. it was
4879                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4880                    // odex file and it matches the checksum of the image but not its base address,
4881                    // meaning we need to move it.
4882                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4883                            pkg.packageName, dexCodeInstructionSet, defer);
4884                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4885                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4886                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4887                                + " vmSafeMode=" + vmSafeMode);
4888                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4889                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4890                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4891
4892                        if (ret < 0) {
4893                            // Don't bother running dexopt again if we failed, it will probably
4894                            // just result in an error again. Also, don't bother dexopting for other
4895                            // paths & ISAs.
4896                            return DEX_OPT_FAILED;
4897                        }
4898
4899                        performedDexOpt = true;
4900                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4901                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4902                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4903                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4904                                pkg.packageName, dexCodeInstructionSet);
4905
4906                        if (ret < 0) {
4907                            // Don't bother running patchoat again if we failed, it will probably
4908                            // just result in an error again. Also, don't bother dexopting for other
4909                            // paths & ISAs.
4910                            return DEX_OPT_FAILED;
4911                        }
4912
4913                        performedDexOpt = true;
4914                    }
4915
4916                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4917                    // paths and instruction sets. We'll deal with them all together when we process
4918                    // our list of deferred dexopts.
4919                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4920                        if (mDeferredDexOpt == null) {
4921                            mDeferredDexOpt = new ArraySet<PackageParser.Package>();
4922                        }
4923                        mDeferredDexOpt.add(pkg);
4924                        return DEX_OPT_DEFERRED;
4925                    }
4926                } catch (FileNotFoundException e) {
4927                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4928                    return DEX_OPT_FAILED;
4929                } catch (IOException e) {
4930                    Slog.w(TAG, "IOException reading apk: " + path, e);
4931                    return DEX_OPT_FAILED;
4932                } catch (StaleDexCacheError e) {
4933                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4934                    return DEX_OPT_FAILED;
4935                } catch (Exception e) {
4936                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4937                    return DEX_OPT_FAILED;
4938                }
4939            }
4940
4941            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4942            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4943            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4944            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4945            // it.
4946            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4947        }
4948
4949        // If we've gotten here, we're sure that no error occurred and that we haven't
4950        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4951        // we've skipped all of them because they are up to date. In both cases this
4952        // package doesn't need dexopt any longer.
4953        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4954    }
4955
4956    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4957        if (info.primaryCpuAbi != null) {
4958            if (info.secondaryCpuAbi != null) {
4959                return new String[] {
4960                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4961                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4962            } else {
4963                return new String[] {
4964                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4965            }
4966        }
4967
4968        return new String[] { getPreferredInstructionSet() };
4969    }
4970
4971    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4972        if (ps.primaryCpuAbiString != null) {
4973            if (ps.secondaryCpuAbiString != null) {
4974                return new String[] {
4975                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4976                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4977            } else {
4978                return new String[] {
4979                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4980            }
4981        }
4982
4983        return new String[] { getPreferredInstructionSet() };
4984    }
4985
4986    private static String getPreferredInstructionSet() {
4987        if (sPreferredInstructionSet == null) {
4988            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4989        }
4990
4991        return sPreferredInstructionSet;
4992    }
4993
4994    private static List<String> getAllInstructionSets() {
4995        final String[] allAbis = Build.SUPPORTED_ABIS;
4996        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4997
4998        for (String abi : allAbis) {
4999            final String instructionSet = VMRuntime.getInstructionSet(abi);
5000            if (!allInstructionSets.contains(instructionSet)) {
5001                allInstructionSets.add(instructionSet);
5002            }
5003        }
5004
5005        return allInstructionSets;
5006    }
5007
5008    /**
5009     * Returns the instruction set that should be used to compile dex code. In the presence of
5010     * a native bridge this might be different than the one shared libraries use.
5011     */
5012    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
5013        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
5014        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
5015    }
5016
5017    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
5018        ArraySet<String> dexCodeInstructionSets = new ArraySet<String>(instructionSets.length);
5019        for (String instructionSet : instructionSets) {
5020            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
5021        }
5022        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
5023    }
5024
5025    /**
5026     * Returns deduplicated list of supported instructions for dex code.
5027     */
5028    public static String[] getAllDexCodeInstructionSets() {
5029        String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length];
5030        for (int i = 0; i < supportedInstructionSets.length; i++) {
5031            String abi = Build.SUPPORTED_ABIS[i];
5032            supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi);
5033        }
5034        return getDexCodeInstructionSets(supportedInstructionSets);
5035    }
5036
5037    @Override
5038    public void forceDexOpt(String packageName) {
5039        enforceSystemOrRoot("forceDexOpt");
5040
5041        PackageParser.Package pkg;
5042        synchronized (mPackages) {
5043            pkg = mPackages.get(packageName);
5044            if (pkg == null) {
5045                throw new IllegalArgumentException("Missing package: " + packageName);
5046            }
5047        }
5048
5049        synchronized (mInstallLock) {
5050            final String[] instructionSets = new String[] {
5051                    getPrimaryInstructionSet(pkg.applicationInfo) };
5052            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
5053            if (res != DEX_OPT_PERFORMED) {
5054                throw new IllegalStateException("Failed to dexopt: " + res);
5055            }
5056        }
5057    }
5058
5059    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
5060                                boolean forceDex, boolean defer, boolean inclDependencies) {
5061        ArraySet<String> done;
5062        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
5063            done = new ArraySet<String>();
5064            done.add(pkg.packageName);
5065        } else {
5066            done = null;
5067        }
5068        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
5069    }
5070
5071    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5072        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5073            Slog.w(TAG, "Unable to update from " + oldPkg.name
5074                    + " to " + newPkg.packageName
5075                    + ": old package not in system partition");
5076            return false;
5077        } else if (mPackages.get(oldPkg.name) != null) {
5078            Slog.w(TAG, "Unable to update from " + oldPkg.name
5079                    + " to " + newPkg.packageName
5080                    + ": old package still exists");
5081            return false;
5082        }
5083        return true;
5084    }
5085
5086    File getDataPathForUser(int userId) {
5087        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
5088    }
5089
5090    private File getDataPathForPackage(String packageName, int userId) {
5091        /*
5092         * Until we fully support multiple users, return the directory we
5093         * previously would have. The PackageManagerTests will need to be
5094         * revised when this is changed back..
5095         */
5096        if (userId == 0) {
5097            return new File(mAppDataDir, packageName);
5098        } else {
5099            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
5100                + File.separator + packageName);
5101        }
5102    }
5103
5104    private int createDataDirsLI(String packageName, int uid, String seinfo) {
5105        int[] users = sUserManager.getUserIds();
5106        int res = mInstaller.install(packageName, uid, uid, seinfo);
5107        if (res < 0) {
5108            return res;
5109        }
5110        for (int user : users) {
5111            if (user != 0) {
5112                res = mInstaller.createUserData(packageName,
5113                        UserHandle.getUid(user, uid), user, seinfo);
5114                if (res < 0) {
5115                    return res;
5116                }
5117            }
5118        }
5119        return res;
5120    }
5121
5122    private int removeDataDirsLI(String packageName) {
5123        int[] users = sUserManager.getUserIds();
5124        int res = 0;
5125        for (int user : users) {
5126            int resInner = mInstaller.remove(packageName, user);
5127            if (resInner < 0) {
5128                res = resInner;
5129            }
5130        }
5131
5132        return res;
5133    }
5134
5135    private int deleteCodeCacheDirsLI(String packageName) {
5136        int[] users = sUserManager.getUserIds();
5137        int res = 0;
5138        for (int user : users) {
5139            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
5140            if (resInner < 0) {
5141                res = resInner;
5142            }
5143        }
5144        return res;
5145    }
5146
5147    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5148            PackageParser.Package changingLib) {
5149        if (file.path != null) {
5150            usesLibraryFiles.add(file.path);
5151            return;
5152        }
5153        PackageParser.Package p = mPackages.get(file.apk);
5154        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5155            // If we are doing this while in the middle of updating a library apk,
5156            // then we need to make sure to use that new apk for determining the
5157            // dependencies here.  (We haven't yet finished committing the new apk
5158            // to the package manager state.)
5159            if (p == null || p.packageName.equals(changingLib.packageName)) {
5160                p = changingLib;
5161            }
5162        }
5163        if (p != null) {
5164            usesLibraryFiles.addAll(p.getAllCodePaths());
5165        }
5166    }
5167
5168    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5169            PackageParser.Package changingLib) throws PackageManagerException {
5170        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5171            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5172            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5173            for (int i=0; i<N; i++) {
5174                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5175                if (file == null) {
5176                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5177                            "Package " + pkg.packageName + " requires unavailable shared library "
5178                            + pkg.usesLibraries.get(i) + "; failing!");
5179                }
5180                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5181            }
5182            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5183            for (int i=0; i<N; i++) {
5184                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5185                if (file == null) {
5186                    Slog.w(TAG, "Package " + pkg.packageName
5187                            + " desires unavailable shared library "
5188                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5189                } else {
5190                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5191                }
5192            }
5193            N = usesLibraryFiles.size();
5194            if (N > 0) {
5195                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5196            } else {
5197                pkg.usesLibraryFiles = null;
5198            }
5199        }
5200    }
5201
5202    private static boolean hasString(List<String> list, List<String> which) {
5203        if (list == null) {
5204            return false;
5205        }
5206        for (int i=list.size()-1; i>=0; i--) {
5207            for (int j=which.size()-1; j>=0; j--) {
5208                if (which.get(j).equals(list.get(i))) {
5209                    return true;
5210                }
5211            }
5212        }
5213        return false;
5214    }
5215
5216    private void updateAllSharedLibrariesLPw() {
5217        for (PackageParser.Package pkg : mPackages.values()) {
5218            try {
5219                updateSharedLibrariesLPw(pkg, null);
5220            } catch (PackageManagerException e) {
5221                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5222            }
5223        }
5224    }
5225
5226    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5227            PackageParser.Package changingPkg) {
5228        ArrayList<PackageParser.Package> res = null;
5229        for (PackageParser.Package pkg : mPackages.values()) {
5230            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5231                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5232                if (res == null) {
5233                    res = new ArrayList<PackageParser.Package>();
5234                }
5235                res.add(pkg);
5236                try {
5237                    updateSharedLibrariesLPw(pkg, changingPkg);
5238                } catch (PackageManagerException e) {
5239                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5240                }
5241            }
5242        }
5243        return res;
5244    }
5245
5246    /**
5247     * Derive the value of the {@code cpuAbiOverride} based on the provided
5248     * value and an optional stored value from the package settings.
5249     */
5250    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5251        String cpuAbiOverride = null;
5252
5253        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5254            cpuAbiOverride = null;
5255        } else if (abiOverride != null) {
5256            cpuAbiOverride = abiOverride;
5257        } else if (settings != null) {
5258            cpuAbiOverride = settings.cpuAbiOverrideString;
5259        }
5260
5261        return cpuAbiOverride;
5262    }
5263
5264    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5265            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5266        boolean success = false;
5267        try {
5268            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5269                    currentTime, user);
5270            success = true;
5271            return res;
5272        } finally {
5273            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5274                removeDataDirsLI(pkg.packageName);
5275            }
5276        }
5277    }
5278
5279    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5280            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5281        final File scanFile = new File(pkg.codePath);
5282        if (pkg.applicationInfo.getCodePath() == null ||
5283                pkg.applicationInfo.getResourcePath() == null) {
5284            // Bail out. The resource and code paths haven't been set.
5285            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5286                    "Code and resource paths haven't been set correctly");
5287        }
5288
5289        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5290            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5291        } else {
5292            // Only allow system apps to be flagged as core apps.
5293            pkg.coreApp = false;
5294        }
5295
5296        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5297            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5298        }
5299
5300        if (mCustomResolverComponentName != null &&
5301                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5302            setUpCustomResolverActivity(pkg);
5303        }
5304
5305        if (pkg.packageName.equals("android")) {
5306            synchronized (mPackages) {
5307                if (mAndroidApplication != null) {
5308                    Slog.w(TAG, "*************************************************");
5309                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5310                    Slog.w(TAG, " file=" + scanFile);
5311                    Slog.w(TAG, "*************************************************");
5312                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5313                            "Core android package being redefined.  Skipping.");
5314                }
5315
5316                // Set up information for our fall-back user intent resolution activity.
5317                mPlatformPackage = pkg;
5318                pkg.mVersionCode = mSdkVersion;
5319                mAndroidApplication = pkg.applicationInfo;
5320
5321                if (!mResolverReplaced) {
5322                    mResolveActivity.applicationInfo = mAndroidApplication;
5323                    mResolveActivity.name = ResolverActivity.class.getName();
5324                    mResolveActivity.packageName = mAndroidApplication.packageName;
5325                    mResolveActivity.processName = "system:ui";
5326                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5327                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5328                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5329                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5330                    mResolveActivity.exported = true;
5331                    mResolveActivity.enabled = true;
5332                    mResolveInfo.activityInfo = mResolveActivity;
5333                    mResolveInfo.priority = 0;
5334                    mResolveInfo.preferredOrder = 0;
5335                    mResolveInfo.match = 0;
5336                    mResolveComponentName = new ComponentName(
5337                            mAndroidApplication.packageName, mResolveActivity.name);
5338                }
5339            }
5340        }
5341
5342        if (DEBUG_PACKAGE_SCANNING) {
5343            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5344                Log.d(TAG, "Scanning package " + pkg.packageName);
5345        }
5346
5347        if (mPackages.containsKey(pkg.packageName)
5348                || mSharedLibraries.containsKey(pkg.packageName)) {
5349            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5350                    "Application package " + pkg.packageName
5351                    + " already installed.  Skipping duplicate.");
5352        }
5353
5354        // Initialize package source and resource directories
5355        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5356        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5357
5358        SharedUserSetting suid = null;
5359        PackageSetting pkgSetting = null;
5360
5361        if (!isSystemApp(pkg)) {
5362            // Only system apps can use these features.
5363            pkg.mOriginalPackages = null;
5364            pkg.mRealPackage = null;
5365            pkg.mAdoptPermissions = null;
5366        }
5367
5368        // writer
5369        synchronized (mPackages) {
5370            if (pkg.mSharedUserId != null) {
5371                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5372                if (suid == null) {
5373                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5374                            "Creating application package " + pkg.packageName
5375                            + " for shared user failed");
5376                }
5377                if (DEBUG_PACKAGE_SCANNING) {
5378                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5379                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5380                                + "): packages=" + suid.packages);
5381                }
5382            }
5383
5384            // Check if we are renaming from an original package name.
5385            PackageSetting origPackage = null;
5386            String realName = null;
5387            if (pkg.mOriginalPackages != null) {
5388                // This package may need to be renamed to a previously
5389                // installed name.  Let's check on that...
5390                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5391                if (pkg.mOriginalPackages.contains(renamed)) {
5392                    // This package had originally been installed as the
5393                    // original name, and we have already taken care of
5394                    // transitioning to the new one.  Just update the new
5395                    // one to continue using the old name.
5396                    realName = pkg.mRealPackage;
5397                    if (!pkg.packageName.equals(renamed)) {
5398                        // Callers into this function may have already taken
5399                        // care of renaming the package; only do it here if
5400                        // it is not already done.
5401                        pkg.setPackageName(renamed);
5402                    }
5403
5404                } else {
5405                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5406                        if ((origPackage = mSettings.peekPackageLPr(
5407                                pkg.mOriginalPackages.get(i))) != null) {
5408                            // We do have the package already installed under its
5409                            // original name...  should we use it?
5410                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5411                                // New package is not compatible with original.
5412                                origPackage = null;
5413                                continue;
5414                            } else if (origPackage.sharedUser != null) {
5415                                // Make sure uid is compatible between packages.
5416                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5417                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5418                                            + " to " + pkg.packageName + ": old uid "
5419                                            + origPackage.sharedUser.name
5420                                            + " differs from " + pkg.mSharedUserId);
5421                                    origPackage = null;
5422                                    continue;
5423                                }
5424                            } else {
5425                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5426                                        + pkg.packageName + " to old name " + origPackage.name);
5427                            }
5428                            break;
5429                        }
5430                    }
5431                }
5432            }
5433
5434            if (mTransferedPackages.contains(pkg.packageName)) {
5435                Slog.w(TAG, "Package " + pkg.packageName
5436                        + " was transferred to another, but its .apk remains");
5437            }
5438
5439            // Just create the setting, don't add it yet. For already existing packages
5440            // the PkgSetting exists already and doesn't have to be created.
5441            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5442                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5443                    pkg.applicationInfo.primaryCpuAbi,
5444                    pkg.applicationInfo.secondaryCpuAbi,
5445                    pkg.applicationInfo.flags, user, false);
5446            if (pkgSetting == null) {
5447                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5448                        "Creating application package " + pkg.packageName + " failed");
5449            }
5450
5451            if (pkgSetting.origPackage != null) {
5452                // If we are first transitioning from an original package,
5453                // fix up the new package's name now.  We need to do this after
5454                // looking up the package under its new name, so getPackageLP
5455                // can take care of fiddling things correctly.
5456                pkg.setPackageName(origPackage.name);
5457
5458                // File a report about this.
5459                String msg = "New package " + pkgSetting.realName
5460                        + " renamed to replace old package " + pkgSetting.name;
5461                reportSettingsProblem(Log.WARN, msg);
5462
5463                // Make a note of it.
5464                mTransferedPackages.add(origPackage.name);
5465
5466                // No longer need to retain this.
5467                pkgSetting.origPackage = null;
5468            }
5469
5470            if (realName != null) {
5471                // Make a note of it.
5472                mTransferedPackages.add(pkg.packageName);
5473            }
5474
5475            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5476                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5477            }
5478
5479            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5480                // Check all shared libraries and map to their actual file path.
5481                // We only do this here for apps not on a system dir, because those
5482                // are the only ones that can fail an install due to this.  We
5483                // will take care of the system apps by updating all of their
5484                // library paths after the scan is done.
5485                updateSharedLibrariesLPw(pkg, null);
5486            }
5487
5488            if (mFoundPolicyFile) {
5489                SELinuxMMAC.assignSeinfoValue(pkg);
5490            }
5491
5492            pkg.applicationInfo.uid = pkgSetting.appId;
5493            pkg.mExtras = pkgSetting;
5494            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5495                try {
5496                    verifySignaturesLP(pkgSetting, pkg);
5497                    // We just determined the app is signed correctly, so bring
5498                    // over the latest parsed certs.
5499                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5500                } catch (PackageManagerException e) {
5501                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5502                        throw e;
5503                    }
5504                    // The signature has changed, but this package is in the system
5505                    // image...  let's recover!
5506                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5507                    // However...  if this package is part of a shared user, but it
5508                    // doesn't match the signature of the shared user, let's fail.
5509                    // What this means is that you can't change the signatures
5510                    // associated with an overall shared user, which doesn't seem all
5511                    // that unreasonable.
5512                    if (pkgSetting.sharedUser != null) {
5513                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5514                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5515                            throw new PackageManagerException(
5516                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5517                                            "Signature mismatch for shared user : "
5518                                            + pkgSetting.sharedUser);
5519                        }
5520                    }
5521                    // File a report about this.
5522                    String msg = "System package " + pkg.packageName
5523                        + " signature changed; retaining data.";
5524                    reportSettingsProblem(Log.WARN, msg);
5525                }
5526            } else {
5527                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5528                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5529                            + pkg.packageName + " upgrade keys do not match the "
5530                            + "previously installed version");
5531                } else {
5532                    // We just determined the app is signed correctly, so bring
5533                    // over the latest parsed certs.
5534                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5535                }
5536            }
5537            // Verify that this new package doesn't have any content providers
5538            // that conflict with existing packages.  Only do this if the
5539            // package isn't already installed, since we don't want to break
5540            // things that are installed.
5541            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5542                final int N = pkg.providers.size();
5543                int i;
5544                for (i=0; i<N; i++) {
5545                    PackageParser.Provider p = pkg.providers.get(i);
5546                    if (p.info.authority != null) {
5547                        String names[] = p.info.authority.split(";");
5548                        for (int j = 0; j < names.length; j++) {
5549                            if (mProvidersByAuthority.containsKey(names[j])) {
5550                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5551                                final String otherPackageName =
5552                                        ((other != null && other.getComponentName() != null) ?
5553                                                other.getComponentName().getPackageName() : "?");
5554                                throw new PackageManagerException(
5555                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5556                                                "Can't install because provider name " + names[j]
5557                                                + " (in package " + pkg.applicationInfo.packageName
5558                                                + ") is already used by " + otherPackageName);
5559                            }
5560                        }
5561                    }
5562                }
5563            }
5564
5565            if (pkg.mAdoptPermissions != null) {
5566                // This package wants to adopt ownership of permissions from
5567                // another package.
5568                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5569                    final String origName = pkg.mAdoptPermissions.get(i);
5570                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5571                    if (orig != null) {
5572                        if (verifyPackageUpdateLPr(orig, pkg)) {
5573                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5574                                    + pkg.packageName);
5575                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5576                        }
5577                    }
5578                }
5579            }
5580        }
5581
5582        final String pkgName = pkg.packageName;
5583
5584        final long scanFileTime = scanFile.lastModified();
5585        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5586        pkg.applicationInfo.processName = fixProcessName(
5587                pkg.applicationInfo.packageName,
5588                pkg.applicationInfo.processName,
5589                pkg.applicationInfo.uid);
5590
5591        File dataPath;
5592        if (mPlatformPackage == pkg) {
5593            // The system package is special.
5594            dataPath = new File(Environment.getDataDirectory(), "system");
5595
5596            pkg.applicationInfo.dataDir = dataPath.getPath();
5597
5598        } else {
5599            // This is a normal package, need to make its data directory.
5600            dataPath = getDataPathForPackage(pkg.packageName, 0);
5601
5602            boolean uidError = false;
5603            if (dataPath.exists()) {
5604                int currentUid = 0;
5605                try {
5606                    StructStat stat = Os.stat(dataPath.getPath());
5607                    currentUid = stat.st_uid;
5608                } catch (ErrnoException e) {
5609                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5610                }
5611
5612                // If we have mismatched owners for the data path, we have a problem.
5613                if (currentUid != pkg.applicationInfo.uid) {
5614                    boolean recovered = false;
5615                    if (currentUid == 0) {
5616                        // The directory somehow became owned by root.  Wow.
5617                        // This is probably because the system was stopped while
5618                        // installd was in the middle of messing with its libs
5619                        // directory.  Ask installd to fix that.
5620                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5621                                pkg.applicationInfo.uid);
5622                        if (ret >= 0) {
5623                            recovered = true;
5624                            String msg = "Package " + pkg.packageName
5625                                    + " unexpectedly changed to uid 0; recovered to " +
5626                                    + pkg.applicationInfo.uid;
5627                            reportSettingsProblem(Log.WARN, msg);
5628                        }
5629                    }
5630                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5631                            || (scanFlags&SCAN_BOOTING) != 0)) {
5632                        // If this is a system app, we can at least delete its
5633                        // current data so the application will still work.
5634                        int ret = removeDataDirsLI(pkgName);
5635                        if (ret >= 0) {
5636                            // TODO: Kill the processes first
5637                            // Old data gone!
5638                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5639                                    ? "System package " : "Third party package ";
5640                            String msg = prefix + pkg.packageName
5641                                    + " has changed from uid: "
5642                                    + currentUid + " to "
5643                                    + pkg.applicationInfo.uid + "; old data erased";
5644                            reportSettingsProblem(Log.WARN, msg);
5645                            recovered = true;
5646
5647                            // And now re-install the app.
5648                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5649                                                   pkg.applicationInfo.seinfo);
5650                            if (ret == -1) {
5651                                // Ack should not happen!
5652                                msg = prefix + pkg.packageName
5653                                        + " could not have data directory re-created after delete.";
5654                                reportSettingsProblem(Log.WARN, msg);
5655                                throw new PackageManagerException(
5656                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5657                            }
5658                        }
5659                        if (!recovered) {
5660                            mHasSystemUidErrors = true;
5661                        }
5662                    } else if (!recovered) {
5663                        // If we allow this install to proceed, we will be broken.
5664                        // Abort, abort!
5665                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5666                                "scanPackageLI");
5667                    }
5668                    if (!recovered) {
5669                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5670                            + pkg.applicationInfo.uid + "/fs_"
5671                            + currentUid;
5672                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5673                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5674                        String msg = "Package " + pkg.packageName
5675                                + " has mismatched uid: "
5676                                + currentUid + " on disk, "
5677                                + pkg.applicationInfo.uid + " in settings";
5678                        // writer
5679                        synchronized (mPackages) {
5680                            mSettings.mReadMessages.append(msg);
5681                            mSettings.mReadMessages.append('\n');
5682                            uidError = true;
5683                            if (!pkgSetting.uidError) {
5684                                reportSettingsProblem(Log.ERROR, msg);
5685                            }
5686                        }
5687                    }
5688                }
5689                pkg.applicationInfo.dataDir = dataPath.getPath();
5690                if (mShouldRestoreconData) {
5691                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5692                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5693                                pkg.applicationInfo.uid);
5694                }
5695            } else {
5696                if (DEBUG_PACKAGE_SCANNING) {
5697                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5698                        Log.v(TAG, "Want this data dir: " + dataPath);
5699                }
5700                //invoke installer to do the actual installation
5701                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5702                                           pkg.applicationInfo.seinfo);
5703                if (ret < 0) {
5704                    // Error from installer
5705                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5706                            "Unable to create data dirs [errorCode=" + ret + "]");
5707                }
5708
5709                if (dataPath.exists()) {
5710                    pkg.applicationInfo.dataDir = dataPath.getPath();
5711                } else {
5712                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5713                    pkg.applicationInfo.dataDir = null;
5714                }
5715            }
5716
5717            pkgSetting.uidError = uidError;
5718        }
5719
5720        final String path = scanFile.getPath();
5721        final String codePath = pkg.applicationInfo.getCodePath();
5722        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5723        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5724            setBundledAppAbisAndRoots(pkg, pkgSetting);
5725
5726            // If we haven't found any native libraries for the app, check if it has
5727            // renderscript code. We'll need to force the app to 32 bit if it has
5728            // renderscript bitcode.
5729            if (pkg.applicationInfo.primaryCpuAbi == null
5730                    && pkg.applicationInfo.secondaryCpuAbi == null
5731                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5732                NativeLibraryHelper.Handle handle = null;
5733                try {
5734                    handle = NativeLibraryHelper.Handle.create(scanFile);
5735                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5736                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5737                    }
5738                } catch (IOException ioe) {
5739                    Slog.w(TAG, "Error scanning system app : " + ioe);
5740                } finally {
5741                    IoUtils.closeQuietly(handle);
5742                }
5743            }
5744
5745            setNativeLibraryPaths(pkg);
5746        } else {
5747            // TODO: We can probably be smarter about this stuff. For installed apps,
5748            // we can calculate this information at install time once and for all. For
5749            // system apps, we can probably assume that this information doesn't change
5750            // after the first boot scan. As things stand, we do lots of unnecessary work.
5751
5752            // Give ourselves some initial paths; we'll come back for another
5753            // pass once we've determined ABI below.
5754            setNativeLibraryPaths(pkg);
5755
5756            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5757            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5758            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5759
5760            NativeLibraryHelper.Handle handle = null;
5761            try {
5762                handle = NativeLibraryHelper.Handle.create(scanFile);
5763                // TODO(multiArch): This can be null for apps that didn't go through the
5764                // usual installation process. We can calculate it again, like we
5765                // do during install time.
5766                //
5767                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5768                // unnecessary.
5769                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5770
5771                // Null out the abis so that they can be recalculated.
5772                pkg.applicationInfo.primaryCpuAbi = null;
5773                pkg.applicationInfo.secondaryCpuAbi = null;
5774                if (isMultiArch(pkg.applicationInfo)) {
5775                    // Warn if we've set an abiOverride for multi-lib packages..
5776                    // By definition, we need to copy both 32 and 64 bit libraries for
5777                    // such packages.
5778                    if (pkg.cpuAbiOverride != null
5779                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5780                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5781                    }
5782
5783                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5784                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5785                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5786                        if (isAsec) {
5787                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5788                        } else {
5789                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5790                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5791                                    useIsaSpecificSubdirs);
5792                        }
5793                    }
5794
5795                    maybeThrowExceptionForMultiArchCopy(
5796                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5797
5798                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5799                        if (isAsec) {
5800                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5801                        } else {
5802                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5803                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5804                                    useIsaSpecificSubdirs);
5805                        }
5806                    }
5807
5808                    maybeThrowExceptionForMultiArchCopy(
5809                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5810
5811                    if (abi64 >= 0) {
5812                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5813                    }
5814
5815                    if (abi32 >= 0) {
5816                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5817                        if (abi64 >= 0) {
5818                            pkg.applicationInfo.secondaryCpuAbi = abi;
5819                        } else {
5820                            pkg.applicationInfo.primaryCpuAbi = abi;
5821                        }
5822                    }
5823                } else {
5824                    String[] abiList = (cpuAbiOverride != null) ?
5825                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5826
5827                    // Enable gross and lame hacks for apps that are built with old
5828                    // SDK tools. We must scan their APKs for renderscript bitcode and
5829                    // not launch them if it's present. Don't bother checking on devices
5830                    // that don't have 64 bit support.
5831                    boolean needsRenderScriptOverride = false;
5832                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5833                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5834                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5835                        needsRenderScriptOverride = true;
5836                    }
5837
5838                    final int copyRet;
5839                    if (isAsec) {
5840                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5841                    } else {
5842                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5843                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5844                    }
5845
5846                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5847                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5848                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5849                    }
5850
5851                    if (copyRet >= 0) {
5852                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5853                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5854                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5855                    } else if (needsRenderScriptOverride) {
5856                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5857                    }
5858                }
5859            } catch (IOException ioe) {
5860                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5861            } finally {
5862                IoUtils.closeQuietly(handle);
5863            }
5864
5865            // Now that we've calculated the ABIs and determined if it's an internal app,
5866            // we will go ahead and populate the nativeLibraryPath.
5867            setNativeLibraryPaths(pkg);
5868
5869            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5870            final int[] userIds = sUserManager.getUserIds();
5871            synchronized (mInstallLock) {
5872                // Create a native library symlink only if we have native libraries
5873                // and if the native libraries are 32 bit libraries. We do not provide
5874                // this symlink for 64 bit libraries.
5875                if (pkg.applicationInfo.primaryCpuAbi != null &&
5876                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5877                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5878                    for (int userId : userIds) {
5879                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5880                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5881                                    "Failed linking native library dir (user=" + userId + ")");
5882                        }
5883                    }
5884                }
5885            }
5886        }
5887
5888        // This is a special case for the "system" package, where the ABI is
5889        // dictated by the zygote configuration (and init.rc). We should keep track
5890        // of this ABI so that we can deal with "normal" applications that run under
5891        // the same UID correctly.
5892        if (mPlatformPackage == pkg) {
5893            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5894                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5895        }
5896
5897        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5898        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5899        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5900        // Copy the derived override back to the parsed package, so that we can
5901        // update the package settings accordingly.
5902        pkg.cpuAbiOverride = cpuAbiOverride;
5903
5904        if (DEBUG_ABI_SELECTION) {
5905            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5906                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5907                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5908        }
5909
5910        // Push the derived path down into PackageSettings so we know what to
5911        // clean up at uninstall time.
5912        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5913
5914        if (DEBUG_ABI_SELECTION) {
5915            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5916                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5917                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5918        }
5919
5920        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5921            // We don't do this here during boot because we can do it all
5922            // at once after scanning all existing packages.
5923            //
5924            // We also do this *before* we perform dexopt on this package, so that
5925            // we can avoid redundant dexopts, and also to make sure we've got the
5926            // code and package path correct.
5927            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5928                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5929        }
5930
5931        if ((scanFlags & SCAN_NO_DEX) == 0) {
5932            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5933                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5934                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5935            }
5936        }
5937
5938        if (mFactoryTest && pkg.requestedPermissions.contains(
5939                android.Manifest.permission.FACTORY_TEST)) {
5940            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5941        }
5942
5943        ArrayList<PackageParser.Package> clientLibPkgs = null;
5944
5945        // writer
5946        synchronized (mPackages) {
5947            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5948                // Only system apps can add new shared libraries.
5949                if (pkg.libraryNames != null) {
5950                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5951                        String name = pkg.libraryNames.get(i);
5952                        boolean allowed = false;
5953                        if (isUpdatedSystemApp(pkg)) {
5954                            // New library entries can only be added through the
5955                            // system image.  This is important to get rid of a lot
5956                            // of nasty edge cases: for example if we allowed a non-
5957                            // system update of the app to add a library, then uninstalling
5958                            // the update would make the library go away, and assumptions
5959                            // we made such as through app install filtering would now
5960                            // have allowed apps on the device which aren't compatible
5961                            // with it.  Better to just have the restriction here, be
5962                            // conservative, and create many fewer cases that can negatively
5963                            // impact the user experience.
5964                            final PackageSetting sysPs = mSettings
5965                                    .getDisabledSystemPkgLPr(pkg.packageName);
5966                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5967                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5968                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5969                                        allowed = true;
5970                                        allowed = true;
5971                                        break;
5972                                    }
5973                                }
5974                            }
5975                        } else {
5976                            allowed = true;
5977                        }
5978                        if (allowed) {
5979                            if (!mSharedLibraries.containsKey(name)) {
5980                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5981                            } else if (!name.equals(pkg.packageName)) {
5982                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5983                                        + name + " already exists; skipping");
5984                            }
5985                        } else {
5986                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5987                                    + name + " that is not declared on system image; skipping");
5988                        }
5989                    }
5990                    if ((scanFlags&SCAN_BOOTING) == 0) {
5991                        // If we are not booting, we need to update any applications
5992                        // that are clients of our shared library.  If we are booting,
5993                        // this will all be done once the scan is complete.
5994                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5995                    }
5996                }
5997            }
5998        }
5999
6000        // We also need to dexopt any apps that are dependent on this library.  Note that
6001        // if these fail, we should abort the install since installing the library will
6002        // result in some apps being broken.
6003        if (clientLibPkgs != null) {
6004            if ((scanFlags & SCAN_NO_DEX) == 0) {
6005                for (int i = 0; i < clientLibPkgs.size(); i++) {
6006                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6007                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
6008                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
6009                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6010                                "scanPackageLI failed to dexopt clientLibPkgs");
6011                    }
6012                }
6013            }
6014        }
6015
6016        // Request the ActivityManager to kill the process(only for existing packages)
6017        // so that we do not end up in a confused state while the user is still using the older
6018        // version of the application while the new one gets installed.
6019        if ((scanFlags & SCAN_REPLACING) != 0) {
6020            killApplication(pkg.applicationInfo.packageName,
6021                        pkg.applicationInfo.uid, "update pkg");
6022        }
6023
6024        // Also need to kill any apps that are dependent on the library.
6025        if (clientLibPkgs != null) {
6026            for (int i=0; i<clientLibPkgs.size(); i++) {
6027                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6028                killApplication(clientPkg.applicationInfo.packageName,
6029                        clientPkg.applicationInfo.uid, "update lib");
6030            }
6031        }
6032
6033        // writer
6034        synchronized (mPackages) {
6035            // We don't expect installation to fail beyond this point
6036
6037            // Add the new setting to mSettings
6038            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6039            // Add the new setting to mPackages
6040            mPackages.put(pkg.applicationInfo.packageName, pkg);
6041            // Make sure we don't accidentally delete its data.
6042            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6043            while (iter.hasNext()) {
6044                PackageCleanItem item = iter.next();
6045                if (pkgName.equals(item.packageName)) {
6046                    iter.remove();
6047                }
6048            }
6049
6050            // Take care of first install / last update times.
6051            if (currentTime != 0) {
6052                if (pkgSetting.firstInstallTime == 0) {
6053                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6054                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6055                    pkgSetting.lastUpdateTime = currentTime;
6056                }
6057            } else if (pkgSetting.firstInstallTime == 0) {
6058                // We need *something*.  Take time time stamp of the file.
6059                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6060            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6061                if (scanFileTime != pkgSetting.timeStamp) {
6062                    // A package on the system image has changed; consider this
6063                    // to be an update.
6064                    pkgSetting.lastUpdateTime = scanFileTime;
6065                }
6066            }
6067
6068            // Add the package's KeySets to the global KeySetManagerService
6069            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6070            try {
6071                // Old KeySetData no longer valid.
6072                ksms.removeAppKeySetDataLPw(pkg.packageName);
6073                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6074                if (pkg.mKeySetMapping != null) {
6075                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
6076                            pkg.mKeySetMapping.entrySet()) {
6077                        if (entry.getValue() != null) {
6078                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
6079                                                          entry.getValue(), entry.getKey());
6080                        }
6081                    }
6082                    if (pkg.mUpgradeKeySets != null) {
6083                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
6084                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
6085                        }
6086                    }
6087                }
6088            } catch (NullPointerException e) {
6089                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6090            } catch (IllegalArgumentException e) {
6091                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6092            }
6093
6094            int N = pkg.providers.size();
6095            StringBuilder r = null;
6096            int i;
6097            for (i=0; i<N; i++) {
6098                PackageParser.Provider p = pkg.providers.get(i);
6099                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6100                        p.info.processName, pkg.applicationInfo.uid);
6101                mProviders.addProvider(p);
6102                p.syncable = p.info.isSyncable;
6103                if (p.info.authority != null) {
6104                    String names[] = p.info.authority.split(";");
6105                    p.info.authority = null;
6106                    for (int j = 0; j < names.length; j++) {
6107                        if (j == 1 && p.syncable) {
6108                            // We only want the first authority for a provider to possibly be
6109                            // syncable, so if we already added this provider using a different
6110                            // authority clear the syncable flag. We copy the provider before
6111                            // changing it because the mProviders object contains a reference
6112                            // to a provider that we don't want to change.
6113                            // Only do this for the second authority since the resulting provider
6114                            // object can be the same for all future authorities for this provider.
6115                            p = new PackageParser.Provider(p);
6116                            p.syncable = false;
6117                        }
6118                        if (!mProvidersByAuthority.containsKey(names[j])) {
6119                            mProvidersByAuthority.put(names[j], p);
6120                            if (p.info.authority == null) {
6121                                p.info.authority = names[j];
6122                            } else {
6123                                p.info.authority = p.info.authority + ";" + names[j];
6124                            }
6125                            if (DEBUG_PACKAGE_SCANNING) {
6126                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6127                                    Log.d(TAG, "Registered content provider: " + names[j]
6128                                            + ", className = " + p.info.name + ", isSyncable = "
6129                                            + p.info.isSyncable);
6130                            }
6131                        } else {
6132                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6133                            Slog.w(TAG, "Skipping provider name " + names[j] +
6134                                    " (in package " + pkg.applicationInfo.packageName +
6135                                    "): name already used by "
6136                                    + ((other != null && other.getComponentName() != null)
6137                                            ? other.getComponentName().getPackageName() : "?"));
6138                        }
6139                    }
6140                }
6141                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6142                    if (r == null) {
6143                        r = new StringBuilder(256);
6144                    } else {
6145                        r.append(' ');
6146                    }
6147                    r.append(p.info.name);
6148                }
6149            }
6150            if (r != null) {
6151                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6152            }
6153
6154            N = pkg.services.size();
6155            r = null;
6156            for (i=0; i<N; i++) {
6157                PackageParser.Service s = pkg.services.get(i);
6158                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6159                        s.info.processName, pkg.applicationInfo.uid);
6160                mServices.addService(s);
6161                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6162                    if (r == null) {
6163                        r = new StringBuilder(256);
6164                    } else {
6165                        r.append(' ');
6166                    }
6167                    r.append(s.info.name);
6168                }
6169            }
6170            if (r != null) {
6171                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6172            }
6173
6174            N = pkg.receivers.size();
6175            r = null;
6176            for (i=0; i<N; i++) {
6177                PackageParser.Activity a = pkg.receivers.get(i);
6178                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6179                        a.info.processName, pkg.applicationInfo.uid);
6180                mReceivers.addActivity(a, "receiver");
6181                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6182                    if (r == null) {
6183                        r = new StringBuilder(256);
6184                    } else {
6185                        r.append(' ');
6186                    }
6187                    r.append(a.info.name);
6188                }
6189            }
6190            if (r != null) {
6191                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6192            }
6193
6194            N = pkg.activities.size();
6195            r = null;
6196            for (i=0; i<N; i++) {
6197                PackageParser.Activity a = pkg.activities.get(i);
6198                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6199                        a.info.processName, pkg.applicationInfo.uid);
6200                mActivities.addActivity(a, "activity");
6201                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6202                    if (r == null) {
6203                        r = new StringBuilder(256);
6204                    } else {
6205                        r.append(' ');
6206                    }
6207                    r.append(a.info.name);
6208                }
6209            }
6210            if (r != null) {
6211                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6212            }
6213
6214            N = pkg.permissionGroups.size();
6215            r = null;
6216            for (i=0; i<N; i++) {
6217                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6218                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6219                if (cur == null) {
6220                    mPermissionGroups.put(pg.info.name, pg);
6221                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6222                        if (r == null) {
6223                            r = new StringBuilder(256);
6224                        } else {
6225                            r.append(' ');
6226                        }
6227                        r.append(pg.info.name);
6228                    }
6229                } else {
6230                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6231                            + pg.info.packageName + " ignored: original from "
6232                            + cur.info.packageName);
6233                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6234                        if (r == null) {
6235                            r = new StringBuilder(256);
6236                        } else {
6237                            r.append(' ');
6238                        }
6239                        r.append("DUP:");
6240                        r.append(pg.info.name);
6241                    }
6242                }
6243            }
6244            if (r != null) {
6245                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6246            }
6247
6248            N = pkg.permissions.size();
6249            r = null;
6250            for (i=0; i<N; i++) {
6251                PackageParser.Permission p = pkg.permissions.get(i);
6252                ArrayMap<String, BasePermission> permissionMap =
6253                        p.tree ? mSettings.mPermissionTrees
6254                        : mSettings.mPermissions;
6255                p.group = mPermissionGroups.get(p.info.group);
6256                if (p.info.group == null || p.group != null) {
6257                    BasePermission bp = permissionMap.get(p.info.name);
6258
6259                    // Allow system apps to redefine non-system permissions
6260                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6261                        final boolean currentOwnerIsSystem = (bp.perm != null
6262                                && isSystemApp(bp.perm.owner));
6263                        if (isSystemApp(p.owner)) {
6264                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6265                                // It's a built-in permission and no owner, take ownership now
6266                                bp.packageSetting = pkgSetting;
6267                                bp.perm = p;
6268                                bp.uid = pkg.applicationInfo.uid;
6269                                bp.sourcePackage = p.info.packageName;
6270                            } else if (!currentOwnerIsSystem) {
6271                                String msg = "New decl " + p.owner + " of permission  "
6272                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6273                                reportSettingsProblem(Log.WARN, msg);
6274                                bp = null;
6275                            }
6276                        }
6277                    }
6278
6279                    if (bp == null) {
6280                        bp = new BasePermission(p.info.name, p.info.packageName,
6281                                BasePermission.TYPE_NORMAL);
6282                        permissionMap.put(p.info.name, bp);
6283                    }
6284
6285                    if (bp.perm == null) {
6286                        if (bp.sourcePackage == null
6287                                || bp.sourcePackage.equals(p.info.packageName)) {
6288                            BasePermission tree = findPermissionTreeLP(p.info.name);
6289                            if (tree == null
6290                                    || tree.sourcePackage.equals(p.info.packageName)) {
6291                                bp.packageSetting = pkgSetting;
6292                                bp.perm = p;
6293                                bp.uid = pkg.applicationInfo.uid;
6294                                bp.sourcePackage = p.info.packageName;
6295                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6296                                    if (r == null) {
6297                                        r = new StringBuilder(256);
6298                                    } else {
6299                                        r.append(' ');
6300                                    }
6301                                    r.append(p.info.name);
6302                                }
6303                            } else {
6304                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6305                                        + p.info.packageName + " ignored: base tree "
6306                                        + tree.name + " is from package "
6307                                        + tree.sourcePackage);
6308                            }
6309                        } else {
6310                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6311                                    + p.info.packageName + " ignored: original from "
6312                                    + bp.sourcePackage);
6313                        }
6314                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6315                        if (r == null) {
6316                            r = new StringBuilder(256);
6317                        } else {
6318                            r.append(' ');
6319                        }
6320                        r.append("DUP:");
6321                        r.append(p.info.name);
6322                    }
6323                    if (bp.perm == p) {
6324                        bp.protectionLevel = p.info.protectionLevel;
6325                    }
6326                } else {
6327                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6328                            + p.info.packageName + " ignored: no group "
6329                            + p.group);
6330                }
6331            }
6332            if (r != null) {
6333                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6334            }
6335
6336            N = pkg.instrumentation.size();
6337            r = null;
6338            for (i=0; i<N; i++) {
6339                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6340                a.info.packageName = pkg.applicationInfo.packageName;
6341                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6342                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6343                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6344                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6345                a.info.dataDir = pkg.applicationInfo.dataDir;
6346
6347                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6348                // need other information about the application, like the ABI and what not ?
6349                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6350                mInstrumentation.put(a.getComponentName(), a);
6351                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6352                    if (r == null) {
6353                        r = new StringBuilder(256);
6354                    } else {
6355                        r.append(' ');
6356                    }
6357                    r.append(a.info.name);
6358                }
6359            }
6360            if (r != null) {
6361                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6362            }
6363
6364            if (pkg.protectedBroadcasts != null) {
6365                N = pkg.protectedBroadcasts.size();
6366                for (i=0; i<N; i++) {
6367                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6368                }
6369            }
6370
6371            pkgSetting.setTimeStamp(scanFileTime);
6372
6373            // Create idmap files for pairs of (packages, overlay packages).
6374            // Note: "android", ie framework-res.apk, is handled by native layers.
6375            if (pkg.mOverlayTarget != null) {
6376                // This is an overlay package.
6377                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6378                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6379                        mOverlays.put(pkg.mOverlayTarget,
6380                                new ArrayMap<String, PackageParser.Package>());
6381                    }
6382                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6383                    map.put(pkg.packageName, pkg);
6384                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6385                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6386                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6387                                "scanPackageLI failed to createIdmap");
6388                    }
6389                }
6390            } else if (mOverlays.containsKey(pkg.packageName) &&
6391                    !pkg.packageName.equals("android")) {
6392                // This is a regular package, with one or more known overlay packages.
6393                createIdmapsForPackageLI(pkg);
6394            }
6395        }
6396
6397        return pkg;
6398    }
6399
6400    /**
6401     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6402     * i.e, so that all packages can be run inside a single process if required.
6403     *
6404     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6405     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6406     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6407     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6408     * updating a package that belongs to a shared user.
6409     *
6410     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6411     * adds unnecessary complexity.
6412     */
6413    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6414            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6415        String requiredInstructionSet = null;
6416        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6417            requiredInstructionSet = VMRuntime.getInstructionSet(
6418                     scannedPackage.applicationInfo.primaryCpuAbi);
6419        }
6420
6421        PackageSetting requirer = null;
6422        for (PackageSetting ps : packagesForUser) {
6423            // If packagesForUser contains scannedPackage, we skip it. This will happen
6424            // when scannedPackage is an update of an existing package. Without this check,
6425            // we will never be able to change the ABI of any package belonging to a shared
6426            // user, even if it's compatible with other packages.
6427            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6428                if (ps.primaryCpuAbiString == null) {
6429                    continue;
6430                }
6431
6432                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6433                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6434                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6435                    // this but there's not much we can do.
6436                    String errorMessage = "Instruction set mismatch, "
6437                            + ((requirer == null) ? "[caller]" : requirer)
6438                            + " requires " + requiredInstructionSet + " whereas " + ps
6439                            + " requires " + instructionSet;
6440                    Slog.w(TAG, errorMessage);
6441                }
6442
6443                if (requiredInstructionSet == null) {
6444                    requiredInstructionSet = instructionSet;
6445                    requirer = ps;
6446                }
6447            }
6448        }
6449
6450        if (requiredInstructionSet != null) {
6451            String adjustedAbi;
6452            if (requirer != null) {
6453                // requirer != null implies that either scannedPackage was null or that scannedPackage
6454                // did not require an ABI, in which case we have to adjust scannedPackage to match
6455                // the ABI of the set (which is the same as requirer's ABI)
6456                adjustedAbi = requirer.primaryCpuAbiString;
6457                if (scannedPackage != null) {
6458                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6459                }
6460            } else {
6461                // requirer == null implies that we're updating all ABIs in the set to
6462                // match scannedPackage.
6463                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6464            }
6465
6466            for (PackageSetting ps : packagesForUser) {
6467                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6468                    if (ps.primaryCpuAbiString != null) {
6469                        continue;
6470                    }
6471
6472                    ps.primaryCpuAbiString = adjustedAbi;
6473                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6474                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6475                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6476
6477                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6478                                deferDexOpt, true) == DEX_OPT_FAILED) {
6479                            ps.primaryCpuAbiString = null;
6480                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6481                            return;
6482                        } else {
6483                            mInstaller.rmdex(ps.codePathString,
6484                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6485                        }
6486                    }
6487                }
6488            }
6489        }
6490    }
6491
6492    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6493        synchronized (mPackages) {
6494            mResolverReplaced = true;
6495            // Set up information for custom user intent resolution activity.
6496            mResolveActivity.applicationInfo = pkg.applicationInfo;
6497            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6498            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6499            mResolveActivity.processName = pkg.applicationInfo.packageName;
6500            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6501            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6502                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6503            mResolveActivity.theme = 0;
6504            mResolveActivity.exported = true;
6505            mResolveActivity.enabled = true;
6506            mResolveInfo.activityInfo = mResolveActivity;
6507            mResolveInfo.priority = 0;
6508            mResolveInfo.preferredOrder = 0;
6509            mResolveInfo.match = 0;
6510            mResolveComponentName = mCustomResolverComponentName;
6511            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6512                    mResolveComponentName);
6513        }
6514    }
6515
6516    private static String calculateBundledApkRoot(final String codePathString) {
6517        final File codePath = new File(codePathString);
6518        final File codeRoot;
6519        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6520            codeRoot = Environment.getRootDirectory();
6521        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6522            codeRoot = Environment.getOemDirectory();
6523        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6524            codeRoot = Environment.getVendorDirectory();
6525        } else {
6526            // Unrecognized code path; take its top real segment as the apk root:
6527            // e.g. /something/app/blah.apk => /something
6528            try {
6529                File f = codePath.getCanonicalFile();
6530                File parent = f.getParentFile();    // non-null because codePath is a file
6531                File tmp;
6532                while ((tmp = parent.getParentFile()) != null) {
6533                    f = parent;
6534                    parent = tmp;
6535                }
6536                codeRoot = f;
6537                Slog.w(TAG, "Unrecognized code path "
6538                        + codePath + " - using " + codeRoot);
6539            } catch (IOException e) {
6540                // Can't canonicalize the code path -- shenanigans?
6541                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6542                return Environment.getRootDirectory().getPath();
6543            }
6544        }
6545        return codeRoot.getPath();
6546    }
6547
6548    /**
6549     * Derive and set the location of native libraries for the given package,
6550     * which varies depending on where and how the package was installed.
6551     */
6552    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6553        final ApplicationInfo info = pkg.applicationInfo;
6554        final String codePath = pkg.codePath;
6555        final File codeFile = new File(codePath);
6556        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6557        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6558
6559        info.nativeLibraryRootDir = null;
6560        info.nativeLibraryRootRequiresIsa = false;
6561        info.nativeLibraryDir = null;
6562        info.secondaryNativeLibraryDir = null;
6563
6564        if (isApkFile(codeFile)) {
6565            // Monolithic install
6566            if (bundledApp) {
6567                // If "/system/lib64/apkname" exists, assume that is the per-package
6568                // native library directory to use; otherwise use "/system/lib/apkname".
6569                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6570                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6571                        getPrimaryInstructionSet(info));
6572
6573                // This is a bundled system app so choose the path based on the ABI.
6574                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6575                // is just the default path.
6576                final String apkName = deriveCodePathName(codePath);
6577                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6578                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6579                        apkName).getAbsolutePath();
6580
6581                if (info.secondaryCpuAbi != null) {
6582                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6583                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6584                            secondaryLibDir, apkName).getAbsolutePath();
6585                }
6586            } else if (asecApp) {
6587                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6588                        .getAbsolutePath();
6589            } else {
6590                final String apkName = deriveCodePathName(codePath);
6591                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6592                        .getAbsolutePath();
6593            }
6594
6595            info.nativeLibraryRootRequiresIsa = false;
6596            info.nativeLibraryDir = info.nativeLibraryRootDir;
6597        } else {
6598            // Cluster install
6599            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6600            info.nativeLibraryRootRequiresIsa = true;
6601
6602            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6603                    getPrimaryInstructionSet(info)).getAbsolutePath();
6604
6605            if (info.secondaryCpuAbi != null) {
6606                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6607                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6608            }
6609        }
6610    }
6611
6612    /**
6613     * Calculate the abis and roots for a bundled app. These can uniquely
6614     * be determined from the contents of the system partition, i.e whether
6615     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6616     * of this information, and instead assume that the system was built
6617     * sensibly.
6618     */
6619    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6620                                           PackageSetting pkgSetting) {
6621        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6622
6623        // If "/system/lib64/apkname" exists, assume that is the per-package
6624        // native library directory to use; otherwise use "/system/lib/apkname".
6625        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6626        setBundledAppAbi(pkg, apkRoot, apkName);
6627        // pkgSetting might be null during rescan following uninstall of updates
6628        // to a bundled app, so accommodate that possibility.  The settings in
6629        // that case will be established later from the parsed package.
6630        //
6631        // If the settings aren't null, sync them up with what we've just derived.
6632        // note that apkRoot isn't stored in the package settings.
6633        if (pkgSetting != null) {
6634            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6635            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6636        }
6637    }
6638
6639    /**
6640     * Deduces the ABI of a bundled app and sets the relevant fields on the
6641     * parsed pkg object.
6642     *
6643     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6644     *        under which system libraries are installed.
6645     * @param apkName the name of the installed package.
6646     */
6647    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6648        final File codeFile = new File(pkg.codePath);
6649
6650        final boolean has64BitLibs;
6651        final boolean has32BitLibs;
6652        if (isApkFile(codeFile)) {
6653            // Monolithic install
6654            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6655            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6656        } else {
6657            // Cluster install
6658            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6659            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6660                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6661                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6662                has64BitLibs = (new File(rootDir, isa)).exists();
6663            } else {
6664                has64BitLibs = false;
6665            }
6666            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6667                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6668                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6669                has32BitLibs = (new File(rootDir, isa)).exists();
6670            } else {
6671                has32BitLibs = false;
6672            }
6673        }
6674
6675        if (has64BitLibs && !has32BitLibs) {
6676            // The package has 64 bit libs, but not 32 bit libs. Its primary
6677            // ABI should be 64 bit. We can safely assume here that the bundled
6678            // native libraries correspond to the most preferred ABI in the list.
6679
6680            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6681            pkg.applicationInfo.secondaryCpuAbi = null;
6682        } else if (has32BitLibs && !has64BitLibs) {
6683            // The package has 32 bit libs but not 64 bit libs. Its primary
6684            // ABI should be 32 bit.
6685
6686            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6687            pkg.applicationInfo.secondaryCpuAbi = null;
6688        } else if (has32BitLibs && has64BitLibs) {
6689            // The application has both 64 and 32 bit bundled libraries. We check
6690            // here that the app declares multiArch support, and warn if it doesn't.
6691            //
6692            // We will be lenient here and record both ABIs. The primary will be the
6693            // ABI that's higher on the list, i.e, a device that's configured to prefer
6694            // 64 bit apps will see a 64 bit primary ABI,
6695
6696            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6697                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6698            }
6699
6700            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6701                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6702                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6703            } else {
6704                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6705                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6706            }
6707        } else {
6708            pkg.applicationInfo.primaryCpuAbi = null;
6709            pkg.applicationInfo.secondaryCpuAbi = null;
6710        }
6711    }
6712
6713    private void killApplication(String pkgName, int appId, String reason) {
6714        // Request the ActivityManager to kill the process(only for existing packages)
6715        // so that we do not end up in a confused state while the user is still using the older
6716        // version of the application while the new one gets installed.
6717        IActivityManager am = ActivityManagerNative.getDefault();
6718        if (am != null) {
6719            try {
6720                am.killApplicationWithAppId(pkgName, appId, reason);
6721            } catch (RemoteException e) {
6722            }
6723        }
6724    }
6725
6726    void removePackageLI(PackageSetting ps, boolean chatty) {
6727        if (DEBUG_INSTALL) {
6728            if (chatty)
6729                Log.d(TAG, "Removing package " + ps.name);
6730        }
6731
6732        // writer
6733        synchronized (mPackages) {
6734            mPackages.remove(ps.name);
6735            final PackageParser.Package pkg = ps.pkg;
6736            if (pkg != null) {
6737                cleanPackageDataStructuresLILPw(pkg, chatty);
6738            }
6739        }
6740    }
6741
6742    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6743        if (DEBUG_INSTALL) {
6744            if (chatty)
6745                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6746        }
6747
6748        // writer
6749        synchronized (mPackages) {
6750            mPackages.remove(pkg.applicationInfo.packageName);
6751            cleanPackageDataStructuresLILPw(pkg, chatty);
6752        }
6753    }
6754
6755    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6756        int N = pkg.providers.size();
6757        StringBuilder r = null;
6758        int i;
6759        for (i=0; i<N; i++) {
6760            PackageParser.Provider p = pkg.providers.get(i);
6761            mProviders.removeProvider(p);
6762            if (p.info.authority == null) {
6763
6764                /* There was another ContentProvider with this authority when
6765                 * this app was installed so this authority is null,
6766                 * Ignore it as we don't have to unregister the provider.
6767                 */
6768                continue;
6769            }
6770            String names[] = p.info.authority.split(";");
6771            for (int j = 0; j < names.length; j++) {
6772                if (mProvidersByAuthority.get(names[j]) == p) {
6773                    mProvidersByAuthority.remove(names[j]);
6774                    if (DEBUG_REMOVE) {
6775                        if (chatty)
6776                            Log.d(TAG, "Unregistered content provider: " + names[j]
6777                                    + ", className = " + p.info.name + ", isSyncable = "
6778                                    + p.info.isSyncable);
6779                    }
6780                }
6781            }
6782            if (DEBUG_REMOVE && chatty) {
6783                if (r == null) {
6784                    r = new StringBuilder(256);
6785                } else {
6786                    r.append(' ');
6787                }
6788                r.append(p.info.name);
6789            }
6790        }
6791        if (r != null) {
6792            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6793        }
6794
6795        N = pkg.services.size();
6796        r = null;
6797        for (i=0; i<N; i++) {
6798            PackageParser.Service s = pkg.services.get(i);
6799            mServices.removeService(s);
6800            if (chatty) {
6801                if (r == null) {
6802                    r = new StringBuilder(256);
6803                } else {
6804                    r.append(' ');
6805                }
6806                r.append(s.info.name);
6807            }
6808        }
6809        if (r != null) {
6810            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6811        }
6812
6813        N = pkg.receivers.size();
6814        r = null;
6815        for (i=0; i<N; i++) {
6816            PackageParser.Activity a = pkg.receivers.get(i);
6817            mReceivers.removeActivity(a, "receiver");
6818            if (DEBUG_REMOVE && chatty) {
6819                if (r == null) {
6820                    r = new StringBuilder(256);
6821                } else {
6822                    r.append(' ');
6823                }
6824                r.append(a.info.name);
6825            }
6826        }
6827        if (r != null) {
6828            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6829        }
6830
6831        N = pkg.activities.size();
6832        r = null;
6833        for (i=0; i<N; i++) {
6834            PackageParser.Activity a = pkg.activities.get(i);
6835            mActivities.removeActivity(a, "activity");
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, "  Activities: " + r);
6847        }
6848
6849        N = pkg.permissions.size();
6850        r = null;
6851        for (i=0; i<N; i++) {
6852            PackageParser.Permission p = pkg.permissions.get(i);
6853            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6854            if (bp == null) {
6855                bp = mSettings.mPermissionTrees.get(p.info.name);
6856            }
6857            if (bp != null && bp.perm == p) {
6858                bp.perm = null;
6859                if (DEBUG_REMOVE && chatty) {
6860                    if (r == null) {
6861                        r = new StringBuilder(256);
6862                    } else {
6863                        r.append(' ');
6864                    }
6865                    r.append(p.info.name);
6866                }
6867            }
6868            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6869                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6870                if (appOpPerms != null) {
6871                    appOpPerms.remove(pkg.packageName);
6872                }
6873            }
6874        }
6875        if (r != null) {
6876            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6877        }
6878
6879        N = pkg.requestedPermissions.size();
6880        r = null;
6881        for (i=0; i<N; i++) {
6882            String perm = pkg.requestedPermissions.get(i);
6883            BasePermission bp = mSettings.mPermissions.get(perm);
6884            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6885                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6886                if (appOpPerms != null) {
6887                    appOpPerms.remove(pkg.packageName);
6888                    if (appOpPerms.isEmpty()) {
6889                        mAppOpPermissionPackages.remove(perm);
6890                    }
6891                }
6892            }
6893        }
6894        if (r != null) {
6895            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6896        }
6897
6898        N = pkg.instrumentation.size();
6899        r = null;
6900        for (i=0; i<N; i++) {
6901            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6902            mInstrumentation.remove(a.getComponentName());
6903            if (DEBUG_REMOVE && chatty) {
6904                if (r == null) {
6905                    r = new StringBuilder(256);
6906                } else {
6907                    r.append(' ');
6908                }
6909                r.append(a.info.name);
6910            }
6911        }
6912        if (r != null) {
6913            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6914        }
6915
6916        r = null;
6917        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6918            // Only system apps can hold shared libraries.
6919            if (pkg.libraryNames != null) {
6920                for (i=0; i<pkg.libraryNames.size(); i++) {
6921                    String name = pkg.libraryNames.get(i);
6922                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6923                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6924                        mSharedLibraries.remove(name);
6925                        if (DEBUG_REMOVE && chatty) {
6926                            if (r == null) {
6927                                r = new StringBuilder(256);
6928                            } else {
6929                                r.append(' ');
6930                            }
6931                            r.append(name);
6932                        }
6933                    }
6934                }
6935            }
6936        }
6937        if (r != null) {
6938            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6939        }
6940    }
6941
6942    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6943        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6944            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6945                return true;
6946            }
6947        }
6948        return false;
6949    }
6950
6951    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6952    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6953    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6954
6955    private void updatePermissionsLPw(String changingPkg,
6956            PackageParser.Package pkgInfo, int flags) {
6957        // Make sure there are no dangling permission trees.
6958        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6959        while (it.hasNext()) {
6960            final BasePermission bp = it.next();
6961            if (bp.packageSetting == null) {
6962                // We may not yet have parsed the package, so just see if
6963                // we still know about its settings.
6964                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6965            }
6966            if (bp.packageSetting == null) {
6967                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6968                        + " from package " + bp.sourcePackage);
6969                it.remove();
6970            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6971                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6972                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6973                            + " from package " + bp.sourcePackage);
6974                    flags |= UPDATE_PERMISSIONS_ALL;
6975                    it.remove();
6976                }
6977            }
6978        }
6979
6980        // Make sure all dynamic permissions have been assigned to a package,
6981        // and make sure there are no dangling permissions.
6982        it = mSettings.mPermissions.values().iterator();
6983        while (it.hasNext()) {
6984            final BasePermission bp = it.next();
6985            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6986                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6987                        + bp.name + " pkg=" + bp.sourcePackage
6988                        + " info=" + bp.pendingInfo);
6989                if (bp.packageSetting == null && bp.pendingInfo != null) {
6990                    final BasePermission tree = findPermissionTreeLP(bp.name);
6991                    if (tree != null && tree.perm != null) {
6992                        bp.packageSetting = tree.packageSetting;
6993                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6994                                new PermissionInfo(bp.pendingInfo));
6995                        bp.perm.info.packageName = tree.perm.info.packageName;
6996                        bp.perm.info.name = bp.name;
6997                        bp.uid = tree.uid;
6998                    }
6999                }
7000            }
7001            if (bp.packageSetting == null) {
7002                // We may not yet have parsed the package, so just see if
7003                // we still know about its settings.
7004                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7005            }
7006            if (bp.packageSetting == null) {
7007                Slog.w(TAG, "Removing dangling permission: " + bp.name
7008                        + " from package " + bp.sourcePackage);
7009                it.remove();
7010            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7011                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7012                    Slog.i(TAG, "Removing old permission: " + bp.name
7013                            + " from package " + bp.sourcePackage);
7014                    flags |= UPDATE_PERMISSIONS_ALL;
7015                    it.remove();
7016                }
7017            }
7018        }
7019
7020        // Now update the permissions for all packages, in particular
7021        // replace the granted permissions of the system packages.
7022        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7023            for (PackageParser.Package pkg : mPackages.values()) {
7024                if (pkg != pkgInfo) {
7025                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7026                            changingPkg);
7027                }
7028            }
7029        }
7030
7031        if (pkgInfo != null) {
7032            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7033        }
7034    }
7035
7036    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7037            String packageOfInterest) {
7038        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7039        if (ps == null) {
7040            return;
7041        }
7042        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
7043        ArraySet<String> origPermissions = gp.grantedPermissions;
7044        boolean changedPermission = false;
7045
7046        if (replace) {
7047            ps.permissionsFixed = false;
7048            if (gp == ps) {
7049                origPermissions = new ArraySet<String>(gp.grantedPermissions);
7050                gp.grantedPermissions.clear();
7051                gp.gids = mGlobalGids;
7052            }
7053        }
7054
7055        if (gp.gids == null) {
7056            gp.gids = mGlobalGids;
7057        }
7058
7059        final int N = pkg.requestedPermissions.size();
7060        for (int i=0; i<N; i++) {
7061            final String name = pkg.requestedPermissions.get(i);
7062            final boolean required = pkg.requestedPermissionsRequired.get(i);
7063            final BasePermission bp = mSettings.mPermissions.get(name);
7064            if (DEBUG_INSTALL) {
7065                if (gp != ps) {
7066                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7067                }
7068            }
7069
7070            if (bp == null || bp.packageSetting == null) {
7071                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7072                    Slog.w(TAG, "Unknown permission " + name
7073                            + " in package " + pkg.packageName);
7074                }
7075                continue;
7076            }
7077
7078            final String perm = bp.name;
7079            boolean allowed;
7080            boolean allowedSig = false;
7081            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7082                // Keep track of app op permissions.
7083                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7084                if (pkgs == null) {
7085                    pkgs = new ArraySet<>();
7086                    mAppOpPermissionPackages.put(bp.name, pkgs);
7087                }
7088                pkgs.add(pkg.packageName);
7089            }
7090            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7091            if (level == PermissionInfo.PROTECTION_NORMAL
7092                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
7093                // We grant a normal or dangerous permission if any of the following
7094                // are true:
7095                // 1) The permission is required
7096                // 2) The permission is optional, but was granted in the past
7097                // 3) The permission is optional, but was requested by an
7098                //    app in /system (not /data)
7099                //
7100                // Otherwise, reject the permission.
7101                allowed = (required || origPermissions.contains(perm)
7102                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
7103            } else if (bp.packageSetting == null) {
7104                // This permission is invalid; skip it.
7105                allowed = false;
7106            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
7107                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
7108                if (allowed) {
7109                    allowedSig = true;
7110                }
7111            } else {
7112                allowed = false;
7113            }
7114            if (DEBUG_INSTALL) {
7115                if (gp != ps) {
7116                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7117                }
7118            }
7119            if (allowed) {
7120                if (!isSystemApp(ps) && ps.permissionsFixed) {
7121                    // If this is an existing, non-system package, then
7122                    // we can't add any new permissions to it.
7123                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
7124                        // Except...  if this is a permission that was added
7125                        // to the platform (note: need to only do this when
7126                        // updating the platform).
7127                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
7128                    }
7129                }
7130                if (allowed) {
7131                    if (!gp.grantedPermissions.contains(perm)) {
7132                        changedPermission = true;
7133                        gp.grantedPermissions.add(perm);
7134                        gp.gids = appendInts(gp.gids, bp.gids);
7135                    } else if (!ps.haveGids) {
7136                        gp.gids = appendInts(gp.gids, bp.gids);
7137                    }
7138                } else {
7139                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7140                        Slog.w(TAG, "Not granting permission " + perm
7141                                + " to package " + pkg.packageName
7142                                + " because it was previously installed without");
7143                    }
7144                }
7145            } else {
7146                if (gp.grantedPermissions.remove(perm)) {
7147                    changedPermission = true;
7148                    gp.gids = removeInts(gp.gids, bp.gids);
7149                    Slog.i(TAG, "Un-granting permission " + perm
7150                            + " from package " + pkg.packageName
7151                            + " (protectionLevel=" + bp.protectionLevel
7152                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7153                            + ")");
7154                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7155                    // Don't print warning for app op permissions, since it is fine for them
7156                    // not to be granted, there is a UI for the user to decide.
7157                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7158                        Slog.w(TAG, "Not granting permission " + perm
7159                                + " to package " + pkg.packageName
7160                                + " (protectionLevel=" + bp.protectionLevel
7161                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7162                                + ")");
7163                    }
7164                }
7165            }
7166        }
7167
7168        if ((changedPermission || replace) && !ps.permissionsFixed &&
7169                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7170            // This is the first that we have heard about this package, so the
7171            // permissions we have now selected are fixed until explicitly
7172            // changed.
7173            ps.permissionsFixed = true;
7174        }
7175        ps.haveGids = true;
7176    }
7177
7178    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7179        boolean allowed = false;
7180        final int NP = PackageParser.NEW_PERMISSIONS.length;
7181        for (int ip=0; ip<NP; ip++) {
7182            final PackageParser.NewPermissionInfo npi
7183                    = PackageParser.NEW_PERMISSIONS[ip];
7184            if (npi.name.equals(perm)
7185                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7186                allowed = true;
7187                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7188                        + pkg.packageName);
7189                break;
7190            }
7191        }
7192        return allowed;
7193    }
7194
7195    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7196                                          BasePermission bp, ArraySet<String> origPermissions) {
7197        boolean allowed;
7198        allowed = (compareSignatures(
7199                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7200                        == PackageManager.SIGNATURE_MATCH)
7201                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7202                        == PackageManager.SIGNATURE_MATCH);
7203        if (!allowed && (bp.protectionLevel
7204                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7205            if (isSystemApp(pkg)) {
7206                // For updated system applications, a system permission
7207                // is granted only if it had been defined by the original application.
7208                if (isUpdatedSystemApp(pkg)) {
7209                    final PackageSetting sysPs = mSettings
7210                            .getDisabledSystemPkgLPr(pkg.packageName);
7211                    final GrantedPermissions origGp = sysPs.sharedUser != null
7212                            ? sysPs.sharedUser : sysPs;
7213
7214                    if (origGp.grantedPermissions.contains(perm)) {
7215                        // If the original was granted this permission, we take
7216                        // that grant decision as read and propagate it to the
7217                        // update.
7218                        if (sysPs.isPrivileged()) {
7219                            allowed = true;
7220                        }
7221                    } else {
7222                        // The system apk may have been updated with an older
7223                        // version of the one on the data partition, but which
7224                        // granted a new system permission that it didn't have
7225                        // before.  In this case we do want to allow the app to
7226                        // now get the new permission if the ancestral apk is
7227                        // privileged to get it.
7228                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7229                            for (int j=0;
7230                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7231                                if (perm.equals(
7232                                        sysPs.pkg.requestedPermissions.get(j))) {
7233                                    allowed = true;
7234                                    break;
7235                                }
7236                            }
7237                        }
7238                    }
7239                } else {
7240                    allowed = isPrivilegedApp(pkg);
7241                }
7242            }
7243        }
7244        if (!allowed && (bp.protectionLevel
7245                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7246            // For development permissions, a development permission
7247            // is granted only if it was already granted.
7248            allowed = origPermissions.contains(perm);
7249        }
7250        return allowed;
7251    }
7252
7253    final class ActivityIntentResolver
7254            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7255        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7256                boolean defaultOnly, int userId) {
7257            if (!sUserManager.exists(userId)) return null;
7258            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7259            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7260        }
7261
7262        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7263                int userId) {
7264            if (!sUserManager.exists(userId)) return null;
7265            mFlags = flags;
7266            return super.queryIntent(intent, resolvedType,
7267                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7268        }
7269
7270        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7271                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7272            if (!sUserManager.exists(userId)) return null;
7273            if (packageActivities == null) {
7274                return null;
7275            }
7276            mFlags = flags;
7277            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7278            final int N = packageActivities.size();
7279            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7280                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7281
7282            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7283            for (int i = 0; i < N; ++i) {
7284                intentFilters = packageActivities.get(i).intents;
7285                if (intentFilters != null && intentFilters.size() > 0) {
7286                    PackageParser.ActivityIntentInfo[] array =
7287                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7288                    intentFilters.toArray(array);
7289                    listCut.add(array);
7290                }
7291            }
7292            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7293        }
7294
7295        public final void addActivity(PackageParser.Activity a, String type) {
7296            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7297            mActivities.put(a.getComponentName(), a);
7298            if (DEBUG_SHOW_INFO)
7299                Log.v(
7300                TAG, "  " + type + " " +
7301                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7302            if (DEBUG_SHOW_INFO)
7303                Log.v(TAG, "    Class=" + a.info.name);
7304            final int NI = a.intents.size();
7305            for (int j=0; j<NI; j++) {
7306                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7307                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7308                    intent.setPriority(0);
7309                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7310                            + a.className + " with priority > 0, forcing to 0");
7311                }
7312                if (DEBUG_SHOW_INFO) {
7313                    Log.v(TAG, "    IntentFilter:");
7314                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7315                }
7316                if (!intent.debugCheck()) {
7317                    Log.w(TAG, "==> For Activity " + a.info.name);
7318                }
7319                addFilter(intent);
7320            }
7321        }
7322
7323        public final void removeActivity(PackageParser.Activity a, String type) {
7324            mActivities.remove(a.getComponentName());
7325            if (DEBUG_SHOW_INFO) {
7326                Log.v(TAG, "  " + type + " "
7327                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7328                                : a.info.name) + ":");
7329                Log.v(TAG, "    Class=" + a.info.name);
7330            }
7331            final int NI = a.intents.size();
7332            for (int j=0; j<NI; j++) {
7333                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7334                if (DEBUG_SHOW_INFO) {
7335                    Log.v(TAG, "    IntentFilter:");
7336                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7337                }
7338                removeFilter(intent);
7339            }
7340        }
7341
7342        @Override
7343        protected boolean allowFilterResult(
7344                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7345            ActivityInfo filterAi = filter.activity.info;
7346            for (int i=dest.size()-1; i>=0; i--) {
7347                ActivityInfo destAi = dest.get(i).activityInfo;
7348                if (destAi.name == filterAi.name
7349                        && destAi.packageName == filterAi.packageName) {
7350                    return false;
7351                }
7352            }
7353            return true;
7354        }
7355
7356        @Override
7357        protected ActivityIntentInfo[] newArray(int size) {
7358            return new ActivityIntentInfo[size];
7359        }
7360
7361        @Override
7362        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7363            if (!sUserManager.exists(userId)) return true;
7364            PackageParser.Package p = filter.activity.owner;
7365            if (p != null) {
7366                PackageSetting ps = (PackageSetting)p.mExtras;
7367                if (ps != null) {
7368                    // System apps are never considered stopped for purposes of
7369                    // filtering, because there may be no way for the user to
7370                    // actually re-launch them.
7371                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7372                            && ps.getStopped(userId);
7373                }
7374            }
7375            return false;
7376        }
7377
7378        @Override
7379        protected boolean isPackageForFilter(String packageName,
7380                PackageParser.ActivityIntentInfo info) {
7381            return packageName.equals(info.activity.owner.packageName);
7382        }
7383
7384        @Override
7385        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7386                int match, int userId) {
7387            if (!sUserManager.exists(userId)) return null;
7388            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7389                return null;
7390            }
7391            final PackageParser.Activity activity = info.activity;
7392            if (mSafeMode && (activity.info.applicationInfo.flags
7393                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7394                return null;
7395            }
7396            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7397            if (ps == null) {
7398                return null;
7399            }
7400            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7401                    ps.readUserState(userId), userId);
7402            if (ai == null) {
7403                return null;
7404            }
7405            final ResolveInfo res = new ResolveInfo();
7406            res.activityInfo = ai;
7407            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7408                res.filter = info;
7409            }
7410            res.priority = info.getPriority();
7411            res.preferredOrder = activity.owner.mPreferredOrder;
7412            //System.out.println("Result: " + res.activityInfo.className +
7413            //                   " = " + res.priority);
7414            res.match = match;
7415            res.isDefault = info.hasDefault;
7416            res.labelRes = info.labelRes;
7417            res.nonLocalizedLabel = info.nonLocalizedLabel;
7418            if (userNeedsBadging(userId)) {
7419                res.noResourceId = true;
7420            } else {
7421                res.icon = info.icon;
7422            }
7423            res.system = isSystemApp(res.activityInfo.applicationInfo);
7424            return res;
7425        }
7426
7427        @Override
7428        protected void sortResults(List<ResolveInfo> results) {
7429            Collections.sort(results, mResolvePrioritySorter);
7430        }
7431
7432        @Override
7433        protected void dumpFilter(PrintWriter out, String prefix,
7434                PackageParser.ActivityIntentInfo filter) {
7435            out.print(prefix); out.print(
7436                    Integer.toHexString(System.identityHashCode(filter.activity)));
7437                    out.print(' ');
7438                    filter.activity.printComponentShortName(out);
7439                    out.print(" filter ");
7440                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7441        }
7442
7443        @Override
7444        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7445            return filter.activity;
7446        }
7447
7448        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7449            PackageParser.Activity activity = (PackageParser.Activity)label;
7450            out.print(prefix); out.print(
7451                    Integer.toHexString(System.identityHashCode(activity)));
7452                    out.print(' ');
7453                    activity.printComponentShortName(out);
7454            if (count > 1) {
7455                out.print(" ("); out.print(count); out.print(" filters)");
7456            }
7457            out.println();
7458        }
7459
7460//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7461//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7462//            final List<ResolveInfo> retList = Lists.newArrayList();
7463//            while (i.hasNext()) {
7464//                final ResolveInfo resolveInfo = i.next();
7465//                if (isEnabledLP(resolveInfo.activityInfo)) {
7466//                    retList.add(resolveInfo);
7467//                }
7468//            }
7469//            return retList;
7470//        }
7471
7472        // Keys are String (activity class name), values are Activity.
7473        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
7474                = new ArrayMap<ComponentName, PackageParser.Activity>();
7475        private int mFlags;
7476    }
7477
7478    private final class ServiceIntentResolver
7479            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7480        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7481                boolean defaultOnly, int userId) {
7482            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7483            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7484        }
7485
7486        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7487                int userId) {
7488            if (!sUserManager.exists(userId)) return null;
7489            mFlags = flags;
7490            return super.queryIntent(intent, resolvedType,
7491                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7492        }
7493
7494        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7495                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7496            if (!sUserManager.exists(userId)) return null;
7497            if (packageServices == null) {
7498                return null;
7499            }
7500            mFlags = flags;
7501            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7502            final int N = packageServices.size();
7503            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7504                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7505
7506            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7507            for (int i = 0; i < N; ++i) {
7508                intentFilters = packageServices.get(i).intents;
7509                if (intentFilters != null && intentFilters.size() > 0) {
7510                    PackageParser.ServiceIntentInfo[] array =
7511                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7512                    intentFilters.toArray(array);
7513                    listCut.add(array);
7514                }
7515            }
7516            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7517        }
7518
7519        public final void addService(PackageParser.Service s) {
7520            mServices.put(s.getComponentName(), s);
7521            if (DEBUG_SHOW_INFO) {
7522                Log.v(TAG, "  "
7523                        + (s.info.nonLocalizedLabel != null
7524                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7525                Log.v(TAG, "    Class=" + s.info.name);
7526            }
7527            final int NI = s.intents.size();
7528            int j;
7529            for (j=0; j<NI; j++) {
7530                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7531                if (DEBUG_SHOW_INFO) {
7532                    Log.v(TAG, "    IntentFilter:");
7533                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7534                }
7535                if (!intent.debugCheck()) {
7536                    Log.w(TAG, "==> For Service " + s.info.name);
7537                }
7538                addFilter(intent);
7539            }
7540        }
7541
7542        public final void removeService(PackageParser.Service s) {
7543            mServices.remove(s.getComponentName());
7544            if (DEBUG_SHOW_INFO) {
7545                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7546                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7547                Log.v(TAG, "    Class=" + s.info.name);
7548            }
7549            final int NI = s.intents.size();
7550            int j;
7551            for (j=0; j<NI; j++) {
7552                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7553                if (DEBUG_SHOW_INFO) {
7554                    Log.v(TAG, "    IntentFilter:");
7555                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7556                }
7557                removeFilter(intent);
7558            }
7559        }
7560
7561        @Override
7562        protected boolean allowFilterResult(
7563                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7564            ServiceInfo filterSi = filter.service.info;
7565            for (int i=dest.size()-1; i>=0; i--) {
7566                ServiceInfo destAi = dest.get(i).serviceInfo;
7567                if (destAi.name == filterSi.name
7568                        && destAi.packageName == filterSi.packageName) {
7569                    return false;
7570                }
7571            }
7572            return true;
7573        }
7574
7575        @Override
7576        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7577            return new PackageParser.ServiceIntentInfo[size];
7578        }
7579
7580        @Override
7581        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7582            if (!sUserManager.exists(userId)) return true;
7583            PackageParser.Package p = filter.service.owner;
7584            if (p != null) {
7585                PackageSetting ps = (PackageSetting)p.mExtras;
7586                if (ps != null) {
7587                    // System apps are never considered stopped for purposes of
7588                    // filtering, because there may be no way for the user to
7589                    // actually re-launch them.
7590                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7591                            && ps.getStopped(userId);
7592                }
7593            }
7594            return false;
7595        }
7596
7597        @Override
7598        protected boolean isPackageForFilter(String packageName,
7599                PackageParser.ServiceIntentInfo info) {
7600            return packageName.equals(info.service.owner.packageName);
7601        }
7602
7603        @Override
7604        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7605                int match, int userId) {
7606            if (!sUserManager.exists(userId)) return null;
7607            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7608            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7609                return null;
7610            }
7611            final PackageParser.Service service = info.service;
7612            if (mSafeMode && (service.info.applicationInfo.flags
7613                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7614                return null;
7615            }
7616            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7617            if (ps == null) {
7618                return null;
7619            }
7620            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7621                    ps.readUserState(userId), userId);
7622            if (si == null) {
7623                return null;
7624            }
7625            final ResolveInfo res = new ResolveInfo();
7626            res.serviceInfo = si;
7627            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7628                res.filter = filter;
7629            }
7630            res.priority = info.getPriority();
7631            res.preferredOrder = service.owner.mPreferredOrder;
7632            //System.out.println("Result: " + res.activityInfo.className +
7633            //                   " = " + res.priority);
7634            res.match = match;
7635            res.isDefault = info.hasDefault;
7636            res.labelRes = info.labelRes;
7637            res.nonLocalizedLabel = info.nonLocalizedLabel;
7638            res.icon = info.icon;
7639            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7640            return res;
7641        }
7642
7643        @Override
7644        protected void sortResults(List<ResolveInfo> results) {
7645            Collections.sort(results, mResolvePrioritySorter);
7646        }
7647
7648        @Override
7649        protected void dumpFilter(PrintWriter out, String prefix,
7650                PackageParser.ServiceIntentInfo filter) {
7651            out.print(prefix); out.print(
7652                    Integer.toHexString(System.identityHashCode(filter.service)));
7653                    out.print(' ');
7654                    filter.service.printComponentShortName(out);
7655                    out.print(" filter ");
7656                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7657        }
7658
7659        @Override
7660        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
7661            return filter.service;
7662        }
7663
7664        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7665            PackageParser.Service service = (PackageParser.Service)label;
7666            out.print(prefix); out.print(
7667                    Integer.toHexString(System.identityHashCode(service)));
7668                    out.print(' ');
7669                    service.printComponentShortName(out);
7670            if (count > 1) {
7671                out.print(" ("); out.print(count); out.print(" filters)");
7672            }
7673            out.println();
7674        }
7675
7676//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7677//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7678//            final List<ResolveInfo> retList = Lists.newArrayList();
7679//            while (i.hasNext()) {
7680//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7681//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7682//                    retList.add(resolveInfo);
7683//                }
7684//            }
7685//            return retList;
7686//        }
7687
7688        // Keys are String (activity class name), values are Activity.
7689        private final ArrayMap<ComponentName, PackageParser.Service> mServices
7690                = new ArrayMap<ComponentName, PackageParser.Service>();
7691        private int mFlags;
7692    };
7693
7694    private final class ProviderIntentResolver
7695            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7696        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7697                boolean defaultOnly, int userId) {
7698            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7699            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7700        }
7701
7702        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7703                int userId) {
7704            if (!sUserManager.exists(userId))
7705                return null;
7706            mFlags = flags;
7707            return super.queryIntent(intent, resolvedType,
7708                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7709        }
7710
7711        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7712                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7713            if (!sUserManager.exists(userId))
7714                return null;
7715            if (packageProviders == null) {
7716                return null;
7717            }
7718            mFlags = flags;
7719            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7720            final int N = packageProviders.size();
7721            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7722                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7723
7724            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7725            for (int i = 0; i < N; ++i) {
7726                intentFilters = packageProviders.get(i).intents;
7727                if (intentFilters != null && intentFilters.size() > 0) {
7728                    PackageParser.ProviderIntentInfo[] array =
7729                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7730                    intentFilters.toArray(array);
7731                    listCut.add(array);
7732                }
7733            }
7734            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7735        }
7736
7737        public final void addProvider(PackageParser.Provider p) {
7738            if (mProviders.containsKey(p.getComponentName())) {
7739                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7740                return;
7741            }
7742
7743            mProviders.put(p.getComponentName(), p);
7744            if (DEBUG_SHOW_INFO) {
7745                Log.v(TAG, "  "
7746                        + (p.info.nonLocalizedLabel != null
7747                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7748                Log.v(TAG, "    Class=" + p.info.name);
7749            }
7750            final int NI = p.intents.size();
7751            int j;
7752            for (j = 0; j < NI; j++) {
7753                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7754                if (DEBUG_SHOW_INFO) {
7755                    Log.v(TAG, "    IntentFilter:");
7756                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7757                }
7758                if (!intent.debugCheck()) {
7759                    Log.w(TAG, "==> For Provider " + p.info.name);
7760                }
7761                addFilter(intent);
7762            }
7763        }
7764
7765        public final void removeProvider(PackageParser.Provider p) {
7766            mProviders.remove(p.getComponentName());
7767            if (DEBUG_SHOW_INFO) {
7768                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7769                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7770                Log.v(TAG, "    Class=" + p.info.name);
7771            }
7772            final int NI = p.intents.size();
7773            int j;
7774            for (j = 0; j < NI; j++) {
7775                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7776                if (DEBUG_SHOW_INFO) {
7777                    Log.v(TAG, "    IntentFilter:");
7778                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7779                }
7780                removeFilter(intent);
7781            }
7782        }
7783
7784        @Override
7785        protected boolean allowFilterResult(
7786                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7787            ProviderInfo filterPi = filter.provider.info;
7788            for (int i = dest.size() - 1; i >= 0; i--) {
7789                ProviderInfo destPi = dest.get(i).providerInfo;
7790                if (destPi.name == filterPi.name
7791                        && destPi.packageName == filterPi.packageName) {
7792                    return false;
7793                }
7794            }
7795            return true;
7796        }
7797
7798        @Override
7799        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7800            return new PackageParser.ProviderIntentInfo[size];
7801        }
7802
7803        @Override
7804        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7805            if (!sUserManager.exists(userId))
7806                return true;
7807            PackageParser.Package p = filter.provider.owner;
7808            if (p != null) {
7809                PackageSetting ps = (PackageSetting) p.mExtras;
7810                if (ps != null) {
7811                    // System apps are never considered stopped for purposes of
7812                    // filtering, because there may be no way for the user to
7813                    // actually re-launch them.
7814                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7815                            && ps.getStopped(userId);
7816                }
7817            }
7818            return false;
7819        }
7820
7821        @Override
7822        protected boolean isPackageForFilter(String packageName,
7823                PackageParser.ProviderIntentInfo info) {
7824            return packageName.equals(info.provider.owner.packageName);
7825        }
7826
7827        @Override
7828        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7829                int match, int userId) {
7830            if (!sUserManager.exists(userId))
7831                return null;
7832            final PackageParser.ProviderIntentInfo info = filter;
7833            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7834                return null;
7835            }
7836            final PackageParser.Provider provider = info.provider;
7837            if (mSafeMode && (provider.info.applicationInfo.flags
7838                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7839                return null;
7840            }
7841            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7842            if (ps == null) {
7843                return null;
7844            }
7845            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7846                    ps.readUserState(userId), userId);
7847            if (pi == null) {
7848                return null;
7849            }
7850            final ResolveInfo res = new ResolveInfo();
7851            res.providerInfo = pi;
7852            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7853                res.filter = filter;
7854            }
7855            res.priority = info.getPriority();
7856            res.preferredOrder = provider.owner.mPreferredOrder;
7857            res.match = match;
7858            res.isDefault = info.hasDefault;
7859            res.labelRes = info.labelRes;
7860            res.nonLocalizedLabel = info.nonLocalizedLabel;
7861            res.icon = info.icon;
7862            res.system = isSystemApp(res.providerInfo.applicationInfo);
7863            return res;
7864        }
7865
7866        @Override
7867        protected void sortResults(List<ResolveInfo> results) {
7868            Collections.sort(results, mResolvePrioritySorter);
7869        }
7870
7871        @Override
7872        protected void dumpFilter(PrintWriter out, String prefix,
7873                PackageParser.ProviderIntentInfo filter) {
7874            out.print(prefix);
7875            out.print(
7876                    Integer.toHexString(System.identityHashCode(filter.provider)));
7877            out.print(' ');
7878            filter.provider.printComponentShortName(out);
7879            out.print(" filter ");
7880            out.println(Integer.toHexString(System.identityHashCode(filter)));
7881        }
7882
7883        @Override
7884        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
7885            return filter.provider;
7886        }
7887
7888        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7889            PackageParser.Provider provider = (PackageParser.Provider)label;
7890            out.print(prefix); out.print(
7891                    Integer.toHexString(System.identityHashCode(provider)));
7892                    out.print(' ');
7893                    provider.printComponentShortName(out);
7894            if (count > 1) {
7895                out.print(" ("); out.print(count); out.print(" filters)");
7896            }
7897            out.println();
7898        }
7899
7900        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
7901                = new ArrayMap<ComponentName, PackageParser.Provider>();
7902        private int mFlags;
7903    };
7904
7905    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7906            new Comparator<ResolveInfo>() {
7907        public int compare(ResolveInfo r1, ResolveInfo r2) {
7908            int v1 = r1.priority;
7909            int v2 = r2.priority;
7910            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7911            if (v1 != v2) {
7912                return (v1 > v2) ? -1 : 1;
7913            }
7914            v1 = r1.preferredOrder;
7915            v2 = r2.preferredOrder;
7916            if (v1 != v2) {
7917                return (v1 > v2) ? -1 : 1;
7918            }
7919            if (r1.isDefault != r2.isDefault) {
7920                return r1.isDefault ? -1 : 1;
7921            }
7922            v1 = r1.match;
7923            v2 = r2.match;
7924            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7925            if (v1 != v2) {
7926                return (v1 > v2) ? -1 : 1;
7927            }
7928            if (r1.system != r2.system) {
7929                return r1.system ? -1 : 1;
7930            }
7931            return 0;
7932        }
7933    };
7934
7935    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7936            new Comparator<ProviderInfo>() {
7937        public int compare(ProviderInfo p1, ProviderInfo p2) {
7938            final int v1 = p1.initOrder;
7939            final int v2 = p2.initOrder;
7940            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7941        }
7942    };
7943
7944    static final void sendPackageBroadcast(String action, String pkg,
7945            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7946            int[] userIds) {
7947        IActivityManager am = ActivityManagerNative.getDefault();
7948        if (am != null) {
7949            try {
7950                if (userIds == null) {
7951                    userIds = am.getRunningUserIds();
7952                }
7953                for (int id : userIds) {
7954                    final Intent intent = new Intent(action,
7955                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7956                    if (extras != null) {
7957                        intent.putExtras(extras);
7958                    }
7959                    if (targetPkg != null) {
7960                        intent.setPackage(targetPkg);
7961                    }
7962                    // Modify the UID when posting to other users
7963                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7964                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7965                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7966                        intent.putExtra(Intent.EXTRA_UID, uid);
7967                    }
7968                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7969                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7970                    if (DEBUG_BROADCASTS) {
7971                        RuntimeException here = new RuntimeException("here");
7972                        here.fillInStackTrace();
7973                        Slog.d(TAG, "Sending to user " + id + ": "
7974                                + intent.toShortString(false, true, false, false)
7975                                + " " + intent.getExtras(), here);
7976                    }
7977                    am.broadcastIntent(null, intent, null, finishedReceiver,
7978                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7979                            finishedReceiver != null, false, id);
7980                }
7981            } catch (RemoteException ex) {
7982            }
7983        }
7984    }
7985
7986    /**
7987     * Check if the external storage media is available. This is true if there
7988     * is a mounted external storage medium or if the external storage is
7989     * emulated.
7990     */
7991    private boolean isExternalMediaAvailable() {
7992        return mMediaMounted || Environment.isExternalStorageEmulated();
7993    }
7994
7995    @Override
7996    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7997        // writer
7998        synchronized (mPackages) {
7999            if (!isExternalMediaAvailable()) {
8000                // If the external storage is no longer mounted at this point,
8001                // the caller may not have been able to delete all of this
8002                // packages files and can not delete any more.  Bail.
8003                return null;
8004            }
8005            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8006            if (lastPackage != null) {
8007                pkgs.remove(lastPackage);
8008            }
8009            if (pkgs.size() > 0) {
8010                return pkgs.get(0);
8011            }
8012        }
8013        return null;
8014    }
8015
8016    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8017        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8018                userId, andCode ? 1 : 0, packageName);
8019        if (mSystemReady) {
8020            msg.sendToTarget();
8021        } else {
8022            if (mPostSystemReadyMessages == null) {
8023                mPostSystemReadyMessages = new ArrayList<>();
8024            }
8025            mPostSystemReadyMessages.add(msg);
8026        }
8027    }
8028
8029    void startCleaningPackages() {
8030        // reader
8031        synchronized (mPackages) {
8032            if (!isExternalMediaAvailable()) {
8033                return;
8034            }
8035            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8036                return;
8037            }
8038        }
8039        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8040        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8041        IActivityManager am = ActivityManagerNative.getDefault();
8042        if (am != null) {
8043            try {
8044                am.startService(null, intent, null, UserHandle.USER_OWNER);
8045            } catch (RemoteException e) {
8046            }
8047        }
8048    }
8049
8050    @Override
8051    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8052            int installFlags, String installerPackageName, VerificationParams verificationParams,
8053            String packageAbiOverride) {
8054        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
8055                packageAbiOverride, UserHandle.getCallingUserId());
8056    }
8057
8058    @Override
8059    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8060            int installFlags, String installerPackageName, VerificationParams verificationParams,
8061            String packageAbiOverride, int userId) {
8062        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8063
8064        final int callingUid = Binder.getCallingUid();
8065        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8066
8067        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8068            try {
8069                if (observer != null) {
8070                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8071                }
8072            } catch (RemoteException re) {
8073            }
8074            return;
8075        }
8076
8077        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8078            installFlags |= PackageManager.INSTALL_FROM_ADB;
8079
8080        } else {
8081            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8082            // about installerPackageName.
8083
8084            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8085            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8086        }
8087
8088        UserHandle user;
8089        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8090            user = UserHandle.ALL;
8091        } else {
8092            user = new UserHandle(userId);
8093        }
8094
8095        verificationParams.setInstallerUid(callingUid);
8096
8097        final File originFile = new File(originPath);
8098        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8099
8100        final Message msg = mHandler.obtainMessage(INIT_COPY);
8101        msg.obj = new InstallParams(origin, observer, installFlags,
8102                installerPackageName, verificationParams, user, packageAbiOverride);
8103        mHandler.sendMessage(msg);
8104    }
8105
8106    void installStage(String packageName, File stagedDir, String stagedCid,
8107            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8108            String installerPackageName, int installerUid, UserHandle user) {
8109        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8110                params.referrerUri, installerUid, null);
8111
8112        final OriginInfo origin;
8113        if (stagedDir != null) {
8114            origin = OriginInfo.fromStagedFile(stagedDir);
8115        } else {
8116            origin = OriginInfo.fromStagedContainer(stagedCid);
8117        }
8118
8119        final Message msg = mHandler.obtainMessage(INIT_COPY);
8120        msg.obj = new InstallParams(origin, observer, params.installFlags,
8121                installerPackageName, verifParams, user, params.abiOverride);
8122        mHandler.sendMessage(msg);
8123    }
8124
8125    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8126        Bundle extras = new Bundle(1);
8127        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8128
8129        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8130                packageName, extras, null, null, new int[] {userId});
8131        try {
8132            IActivityManager am = ActivityManagerNative.getDefault();
8133            final boolean isSystem =
8134                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8135            if (isSystem && am.isUserRunning(userId, false)) {
8136                // The just-installed/enabled app is bundled on the system, so presumed
8137                // to be able to run automatically without needing an explicit launch.
8138                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8139                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8140                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8141                        .setPackage(packageName);
8142                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8143                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8144            }
8145        } catch (RemoteException e) {
8146            // shouldn't happen
8147            Slog.w(TAG, "Unable to bootstrap installed package", e);
8148        }
8149    }
8150
8151    @Override
8152    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8153            int userId) {
8154        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8155        PackageSetting pkgSetting;
8156        final int uid = Binder.getCallingUid();
8157        enforceCrossUserPermission(uid, userId, true, true,
8158                "setApplicationHiddenSetting for user " + userId);
8159
8160        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8161            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8162            return false;
8163        }
8164
8165        long callingId = Binder.clearCallingIdentity();
8166        try {
8167            boolean sendAdded = false;
8168            boolean sendRemoved = false;
8169            // writer
8170            synchronized (mPackages) {
8171                pkgSetting = mSettings.mPackages.get(packageName);
8172                if (pkgSetting == null) {
8173                    return false;
8174                }
8175                if (pkgSetting.getHidden(userId) != hidden) {
8176                    pkgSetting.setHidden(hidden, userId);
8177                    mSettings.writePackageRestrictionsLPr(userId);
8178                    if (hidden) {
8179                        sendRemoved = true;
8180                    } else {
8181                        sendAdded = true;
8182                    }
8183                }
8184            }
8185            if (sendAdded) {
8186                sendPackageAddedForUser(packageName, pkgSetting, userId);
8187                return true;
8188            }
8189            if (sendRemoved) {
8190                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8191                        "hiding pkg");
8192                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8193            }
8194        } finally {
8195            Binder.restoreCallingIdentity(callingId);
8196        }
8197        return false;
8198    }
8199
8200    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8201            int userId) {
8202        final PackageRemovedInfo info = new PackageRemovedInfo();
8203        info.removedPackage = packageName;
8204        info.removedUsers = new int[] {userId};
8205        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8206        info.sendBroadcast(false, false, false);
8207    }
8208
8209    /**
8210     * Returns true if application is not found or there was an error. Otherwise it returns
8211     * the hidden state of the package for the given user.
8212     */
8213    @Override
8214    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8215        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8216        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8217                false, "getApplicationHidden for user " + userId);
8218        PackageSetting pkgSetting;
8219        long callingId = Binder.clearCallingIdentity();
8220        try {
8221            // writer
8222            synchronized (mPackages) {
8223                pkgSetting = mSettings.mPackages.get(packageName);
8224                if (pkgSetting == null) {
8225                    return true;
8226                }
8227                return pkgSetting.getHidden(userId);
8228            }
8229        } finally {
8230            Binder.restoreCallingIdentity(callingId);
8231        }
8232    }
8233
8234    /**
8235     * @hide
8236     */
8237    @Override
8238    public int installExistingPackageAsUser(String packageName, int userId) {
8239        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8240                null);
8241        PackageSetting pkgSetting;
8242        final int uid = Binder.getCallingUid();
8243        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8244                + userId);
8245        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8246            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8247        }
8248
8249        long callingId = Binder.clearCallingIdentity();
8250        try {
8251            boolean sendAdded = false;
8252            Bundle extras = new Bundle(1);
8253
8254            // writer
8255            synchronized (mPackages) {
8256                pkgSetting = mSettings.mPackages.get(packageName);
8257                if (pkgSetting == null) {
8258                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8259                }
8260                if (!pkgSetting.getInstalled(userId)) {
8261                    pkgSetting.setInstalled(true, userId);
8262                    pkgSetting.setHidden(false, userId);
8263                    mSettings.writePackageRestrictionsLPr(userId);
8264                    sendAdded = true;
8265                }
8266            }
8267
8268            if (sendAdded) {
8269                sendPackageAddedForUser(packageName, pkgSetting, userId);
8270            }
8271        } finally {
8272            Binder.restoreCallingIdentity(callingId);
8273        }
8274
8275        return PackageManager.INSTALL_SUCCEEDED;
8276    }
8277
8278    boolean isUserRestricted(int userId, String restrictionKey) {
8279        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8280        if (restrictions.getBoolean(restrictionKey, false)) {
8281            Log.w(TAG, "User is restricted: " + restrictionKey);
8282            return true;
8283        }
8284        return false;
8285    }
8286
8287    @Override
8288    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8289        mContext.enforceCallingOrSelfPermission(
8290                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8291                "Only package verification agents can verify applications");
8292
8293        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8294        final PackageVerificationResponse response = new PackageVerificationResponse(
8295                verificationCode, Binder.getCallingUid());
8296        msg.arg1 = id;
8297        msg.obj = response;
8298        mHandler.sendMessage(msg);
8299    }
8300
8301    @Override
8302    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8303            long millisecondsToDelay) {
8304        mContext.enforceCallingOrSelfPermission(
8305                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8306                "Only package verification agents can extend verification timeouts");
8307
8308        final PackageVerificationState state = mPendingVerification.get(id);
8309        final PackageVerificationResponse response = new PackageVerificationResponse(
8310                verificationCodeAtTimeout, Binder.getCallingUid());
8311
8312        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8313            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8314        }
8315        if (millisecondsToDelay < 0) {
8316            millisecondsToDelay = 0;
8317        }
8318        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8319                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8320            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8321        }
8322
8323        if ((state != null) && !state.timeoutExtended()) {
8324            state.extendTimeout();
8325
8326            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8327            msg.arg1 = id;
8328            msg.obj = response;
8329            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8330        }
8331    }
8332
8333    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8334            int verificationCode, UserHandle user) {
8335        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8336        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8337        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8338        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8339        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8340
8341        mContext.sendBroadcastAsUser(intent, user,
8342                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8343    }
8344
8345    private ComponentName matchComponentForVerifier(String packageName,
8346            List<ResolveInfo> receivers) {
8347        ActivityInfo targetReceiver = null;
8348
8349        final int NR = receivers.size();
8350        for (int i = 0; i < NR; i++) {
8351            final ResolveInfo info = receivers.get(i);
8352            if (info.activityInfo == null) {
8353                continue;
8354            }
8355
8356            if (packageName.equals(info.activityInfo.packageName)) {
8357                targetReceiver = info.activityInfo;
8358                break;
8359            }
8360        }
8361
8362        if (targetReceiver == null) {
8363            return null;
8364        }
8365
8366        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8367    }
8368
8369    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8370            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8371        if (pkgInfo.verifiers.length == 0) {
8372            return null;
8373        }
8374
8375        final int N = pkgInfo.verifiers.length;
8376        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8377        for (int i = 0; i < N; i++) {
8378            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8379
8380            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8381                    receivers);
8382            if (comp == null) {
8383                continue;
8384            }
8385
8386            final int verifierUid = getUidForVerifier(verifierInfo);
8387            if (verifierUid == -1) {
8388                continue;
8389            }
8390
8391            if (DEBUG_VERIFY) {
8392                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8393                        + " with the correct signature");
8394            }
8395            sufficientVerifiers.add(comp);
8396            verificationState.addSufficientVerifier(verifierUid);
8397        }
8398
8399        return sufficientVerifiers;
8400    }
8401
8402    private int getUidForVerifier(VerifierInfo verifierInfo) {
8403        synchronized (mPackages) {
8404            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8405            if (pkg == null) {
8406                return -1;
8407            } else if (pkg.mSignatures.length != 1) {
8408                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8409                        + " has more than one signature; ignoring");
8410                return -1;
8411            }
8412
8413            /*
8414             * If the public key of the package's signature does not match
8415             * our expected public key, then this is a different package and
8416             * we should skip.
8417             */
8418
8419            final byte[] expectedPublicKey;
8420            try {
8421                final Signature verifierSig = pkg.mSignatures[0];
8422                final PublicKey publicKey = verifierSig.getPublicKey();
8423                expectedPublicKey = publicKey.getEncoded();
8424            } catch (CertificateException e) {
8425                return -1;
8426            }
8427
8428            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8429
8430            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8431                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8432                        + " does not have the expected public key; ignoring");
8433                return -1;
8434            }
8435
8436            return pkg.applicationInfo.uid;
8437        }
8438    }
8439
8440    @Override
8441    public void finishPackageInstall(int token) {
8442        enforceSystemOrRoot("Only the system is allowed to finish installs");
8443
8444        if (DEBUG_INSTALL) {
8445            Slog.v(TAG, "BM finishing package install for " + token);
8446        }
8447
8448        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8449        mHandler.sendMessage(msg);
8450    }
8451
8452    /**
8453     * Get the verification agent timeout.
8454     *
8455     * @return verification timeout in milliseconds
8456     */
8457    private long getVerificationTimeout() {
8458        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8459                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8460                DEFAULT_VERIFICATION_TIMEOUT);
8461    }
8462
8463    /**
8464     * Get the default verification agent response code.
8465     *
8466     * @return default verification response code
8467     */
8468    private int getDefaultVerificationResponse() {
8469        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8470                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8471                DEFAULT_VERIFICATION_RESPONSE);
8472    }
8473
8474    /**
8475     * Check whether or not package verification has been enabled.
8476     *
8477     * @return true if verification should be performed
8478     */
8479    private boolean isVerificationEnabled(int userId, int installFlags) {
8480        if (!DEFAULT_VERIFY_ENABLE) {
8481            return false;
8482        }
8483
8484        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8485
8486        // Check if installing from ADB
8487        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8488            // Do not run verification in a test harness environment
8489            if (ActivityManager.isRunningInTestHarness()) {
8490                return false;
8491            }
8492            if (ensureVerifyAppsEnabled) {
8493                return true;
8494            }
8495            // Check if the developer does not want package verification for ADB installs
8496            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8497                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8498                return false;
8499            }
8500        }
8501
8502        if (ensureVerifyAppsEnabled) {
8503            return true;
8504        }
8505
8506        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8507                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8508    }
8509
8510    /**
8511     * Get the "allow unknown sources" setting.
8512     *
8513     * @return the current "allow unknown sources" setting
8514     */
8515    private int getUnknownSourcesSettings() {
8516        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8517                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8518                -1);
8519    }
8520
8521    @Override
8522    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8523        final int uid = Binder.getCallingUid();
8524        // writer
8525        synchronized (mPackages) {
8526            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8527            if (targetPackageSetting == null) {
8528                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8529            }
8530
8531            PackageSetting installerPackageSetting;
8532            if (installerPackageName != null) {
8533                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8534                if (installerPackageSetting == null) {
8535                    throw new IllegalArgumentException("Unknown installer package: "
8536                            + installerPackageName);
8537                }
8538            } else {
8539                installerPackageSetting = null;
8540            }
8541
8542            Signature[] callerSignature;
8543            Object obj = mSettings.getUserIdLPr(uid);
8544            if (obj != null) {
8545                if (obj instanceof SharedUserSetting) {
8546                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8547                } else if (obj instanceof PackageSetting) {
8548                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8549                } else {
8550                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8551                }
8552            } else {
8553                throw new SecurityException("Unknown calling uid " + uid);
8554            }
8555
8556            // Verify: can't set installerPackageName to a package that is
8557            // not signed with the same cert as the caller.
8558            if (installerPackageSetting != null) {
8559                if (compareSignatures(callerSignature,
8560                        installerPackageSetting.signatures.mSignatures)
8561                        != PackageManager.SIGNATURE_MATCH) {
8562                    throw new SecurityException(
8563                            "Caller does not have same cert as new installer package "
8564                            + installerPackageName);
8565                }
8566            }
8567
8568            // Verify: if target already has an installer package, it must
8569            // be signed with the same cert as the caller.
8570            if (targetPackageSetting.installerPackageName != null) {
8571                PackageSetting setting = mSettings.mPackages.get(
8572                        targetPackageSetting.installerPackageName);
8573                // If the currently set package isn't valid, then it's always
8574                // okay to change it.
8575                if (setting != null) {
8576                    if (compareSignatures(callerSignature,
8577                            setting.signatures.mSignatures)
8578                            != PackageManager.SIGNATURE_MATCH) {
8579                        throw new SecurityException(
8580                                "Caller does not have same cert as old installer package "
8581                                + targetPackageSetting.installerPackageName);
8582                    }
8583                }
8584            }
8585
8586            // Okay!
8587            targetPackageSetting.installerPackageName = installerPackageName;
8588            scheduleWriteSettingsLocked();
8589        }
8590    }
8591
8592    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8593        // Queue up an async operation since the package installation may take a little while.
8594        mHandler.post(new Runnable() {
8595            public void run() {
8596                mHandler.removeCallbacks(this);
8597                 // Result object to be returned
8598                PackageInstalledInfo res = new PackageInstalledInfo();
8599                res.returnCode = currentStatus;
8600                res.uid = -1;
8601                res.pkg = null;
8602                res.removedInfo = new PackageRemovedInfo();
8603                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8604                    args.doPreInstall(res.returnCode);
8605                    synchronized (mInstallLock) {
8606                        installPackageLI(args, res);
8607                    }
8608                    args.doPostInstall(res.returnCode, res.uid);
8609                }
8610
8611                // A restore should be performed at this point if (a) the install
8612                // succeeded, (b) the operation is not an update, and (c) the new
8613                // package has not opted out of backup participation.
8614                final boolean update = res.removedInfo.removedPackage != null;
8615                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8616                boolean doRestore = !update
8617                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8618
8619                // Set up the post-install work request bookkeeping.  This will be used
8620                // and cleaned up by the post-install event handling regardless of whether
8621                // there's a restore pass performed.  Token values are >= 1.
8622                int token;
8623                if (mNextInstallToken < 0) mNextInstallToken = 1;
8624                token = mNextInstallToken++;
8625
8626                PostInstallData data = new PostInstallData(args, res);
8627                mRunningInstalls.put(token, data);
8628                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8629
8630                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8631                    // Pass responsibility to the Backup Manager.  It will perform a
8632                    // restore if appropriate, then pass responsibility back to the
8633                    // Package Manager to run the post-install observer callbacks
8634                    // and broadcasts.
8635                    IBackupManager bm = IBackupManager.Stub.asInterface(
8636                            ServiceManager.getService(Context.BACKUP_SERVICE));
8637                    if (bm != null) {
8638                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8639                                + " to BM for possible restore");
8640                        try {
8641                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
8642                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8643                            } else {
8644                                doRestore = false;
8645                            }
8646                        } catch (RemoteException e) {
8647                            // can't happen; the backup manager is local
8648                        } catch (Exception e) {
8649                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8650                            doRestore = false;
8651                        }
8652                    } else {
8653                        Slog.e(TAG, "Backup Manager not found!");
8654                        doRestore = false;
8655                    }
8656                }
8657
8658                if (!doRestore) {
8659                    // No restore possible, or the Backup Manager was mysteriously not
8660                    // available -- just fire the post-install work request directly.
8661                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8662                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8663                    mHandler.sendMessage(msg);
8664                }
8665            }
8666        });
8667    }
8668
8669    private abstract class HandlerParams {
8670        private static final int MAX_RETRIES = 4;
8671
8672        /**
8673         * Number of times startCopy() has been attempted and had a non-fatal
8674         * error.
8675         */
8676        private int mRetries = 0;
8677
8678        /** User handle for the user requesting the information or installation. */
8679        private final UserHandle mUser;
8680
8681        HandlerParams(UserHandle user) {
8682            mUser = user;
8683        }
8684
8685        UserHandle getUser() {
8686            return mUser;
8687        }
8688
8689        final boolean startCopy() {
8690            boolean res;
8691            try {
8692                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8693
8694                if (++mRetries > MAX_RETRIES) {
8695                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8696                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8697                    handleServiceError();
8698                    return false;
8699                } else {
8700                    handleStartCopy();
8701                    res = true;
8702                }
8703            } catch (RemoteException e) {
8704                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8705                mHandler.sendEmptyMessage(MCS_RECONNECT);
8706                res = false;
8707            }
8708            handleReturnCode();
8709            return res;
8710        }
8711
8712        final void serviceError() {
8713            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8714            handleServiceError();
8715            handleReturnCode();
8716        }
8717
8718        abstract void handleStartCopy() throws RemoteException;
8719        abstract void handleServiceError();
8720        abstract void handleReturnCode();
8721    }
8722
8723    class MeasureParams extends HandlerParams {
8724        private final PackageStats mStats;
8725        private boolean mSuccess;
8726
8727        private final IPackageStatsObserver mObserver;
8728
8729        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8730            super(new UserHandle(stats.userHandle));
8731            mObserver = observer;
8732            mStats = stats;
8733        }
8734
8735        @Override
8736        public String toString() {
8737            return "MeasureParams{"
8738                + Integer.toHexString(System.identityHashCode(this))
8739                + " " + mStats.packageName + "}";
8740        }
8741
8742        @Override
8743        void handleStartCopy() throws RemoteException {
8744            synchronized (mInstallLock) {
8745                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8746            }
8747
8748            if (mSuccess) {
8749                final boolean mounted;
8750                if (Environment.isExternalStorageEmulated()) {
8751                    mounted = true;
8752                } else {
8753                    final String status = Environment.getExternalStorageState();
8754                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8755                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8756                }
8757
8758                if (mounted) {
8759                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8760
8761                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8762                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8763
8764                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8765                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8766
8767                    // Always subtract cache size, since it's a subdirectory
8768                    mStats.externalDataSize -= mStats.externalCacheSize;
8769
8770                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8771                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8772
8773                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8774                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8775                }
8776            }
8777        }
8778
8779        @Override
8780        void handleReturnCode() {
8781            if (mObserver != null) {
8782                try {
8783                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8784                } catch (RemoteException e) {
8785                    Slog.i(TAG, "Observer no longer exists.");
8786                }
8787            }
8788        }
8789
8790        @Override
8791        void handleServiceError() {
8792            Slog.e(TAG, "Could not measure application " + mStats.packageName
8793                            + " external storage");
8794        }
8795    }
8796
8797    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8798            throws RemoteException {
8799        long result = 0;
8800        for (File path : paths) {
8801            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8802        }
8803        return result;
8804    }
8805
8806    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8807        for (File path : paths) {
8808            try {
8809                mcs.clearDirectory(path.getAbsolutePath());
8810            } catch (RemoteException e) {
8811            }
8812        }
8813    }
8814
8815    static class OriginInfo {
8816        /**
8817         * Location where install is coming from, before it has been
8818         * copied/renamed into place. This could be a single monolithic APK
8819         * file, or a cluster directory. This location may be untrusted.
8820         */
8821        final File file;
8822        final String cid;
8823
8824        /**
8825         * Flag indicating that {@link #file} or {@link #cid} has already been
8826         * staged, meaning downstream users don't need to defensively copy the
8827         * contents.
8828         */
8829        final boolean staged;
8830
8831        /**
8832         * Flag indicating that {@link #file} or {@link #cid} is an already
8833         * installed app that is being moved.
8834         */
8835        final boolean existing;
8836
8837        final String resolvedPath;
8838        final File resolvedFile;
8839
8840        static OriginInfo fromNothing() {
8841            return new OriginInfo(null, null, false, false);
8842        }
8843
8844        static OriginInfo fromUntrustedFile(File file) {
8845            return new OriginInfo(file, null, false, false);
8846        }
8847
8848        static OriginInfo fromExistingFile(File file) {
8849            return new OriginInfo(file, null, false, true);
8850        }
8851
8852        static OriginInfo fromStagedFile(File file) {
8853            return new OriginInfo(file, null, true, false);
8854        }
8855
8856        static OriginInfo fromStagedContainer(String cid) {
8857            return new OriginInfo(null, cid, true, false);
8858        }
8859
8860        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8861            this.file = file;
8862            this.cid = cid;
8863            this.staged = staged;
8864            this.existing = existing;
8865
8866            if (cid != null) {
8867                resolvedPath = PackageHelper.getSdDir(cid);
8868                resolvedFile = new File(resolvedPath);
8869            } else if (file != null) {
8870                resolvedPath = file.getAbsolutePath();
8871                resolvedFile = file;
8872            } else {
8873                resolvedPath = null;
8874                resolvedFile = null;
8875            }
8876        }
8877    }
8878
8879    class InstallParams extends HandlerParams {
8880        final OriginInfo origin;
8881        final IPackageInstallObserver2 observer;
8882        int installFlags;
8883        final String installerPackageName;
8884        final VerificationParams verificationParams;
8885        private InstallArgs mArgs;
8886        private int mRet;
8887        final String packageAbiOverride;
8888
8889        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8890                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8891                String packageAbiOverride) {
8892            super(user);
8893            this.origin = origin;
8894            this.observer = observer;
8895            this.installFlags = installFlags;
8896            this.installerPackageName = installerPackageName;
8897            this.verificationParams = verificationParams;
8898            this.packageAbiOverride = packageAbiOverride;
8899        }
8900
8901        @Override
8902        public String toString() {
8903            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8904                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8905        }
8906
8907        public ManifestDigest getManifestDigest() {
8908            if (verificationParams == null) {
8909                return null;
8910            }
8911            return verificationParams.getManifestDigest();
8912        }
8913
8914        private int installLocationPolicy(PackageInfoLite pkgLite) {
8915            String packageName = pkgLite.packageName;
8916            int installLocation = pkgLite.installLocation;
8917            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8918            // reader
8919            synchronized (mPackages) {
8920                PackageParser.Package pkg = mPackages.get(packageName);
8921                if (pkg != null) {
8922                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8923                        // Check for downgrading.
8924                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8925                            try {
8926                                checkDowngrade(pkg, pkgLite);
8927                            } catch (PackageManagerException e) {
8928                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
8929                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8930                            }
8931                        }
8932                        // Check for updated system application.
8933                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8934                            if (onSd) {
8935                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8936                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8937                            }
8938                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8939                        } else {
8940                            if (onSd) {
8941                                // Install flag overrides everything.
8942                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8943                            }
8944                            // If current upgrade specifies particular preference
8945                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8946                                // Application explicitly specified internal.
8947                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8948                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8949                                // App explictly prefers external. Let policy decide
8950                            } else {
8951                                // Prefer previous location
8952                                if (isExternal(pkg)) {
8953                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8954                                }
8955                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8956                            }
8957                        }
8958                    } else {
8959                        // Invalid install. Return error code
8960                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8961                    }
8962                }
8963            }
8964            // All the special cases have been taken care of.
8965            // Return result based on recommended install location.
8966            if (onSd) {
8967                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8968            }
8969            return pkgLite.recommendedInstallLocation;
8970        }
8971
8972        /*
8973         * Invoke remote method to get package information and install
8974         * location values. Override install location based on default
8975         * policy if needed and then create install arguments based
8976         * on the install location.
8977         */
8978        public void handleStartCopy() throws RemoteException {
8979            int ret = PackageManager.INSTALL_SUCCEEDED;
8980
8981            // If we're already staged, we've firmly committed to an install location
8982            if (origin.staged) {
8983                if (origin.file != null) {
8984                    installFlags |= PackageManager.INSTALL_INTERNAL;
8985                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8986                } else if (origin.cid != null) {
8987                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8988                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8989                } else {
8990                    throw new IllegalStateException("Invalid stage location");
8991                }
8992            }
8993
8994            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8995            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8996
8997            PackageInfoLite pkgLite = null;
8998
8999            if (onInt && onSd) {
9000                // Check if both bits are set.
9001                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9002                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9003            } else {
9004                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9005                        packageAbiOverride);
9006
9007                /*
9008                 * If we have too little free space, try to free cache
9009                 * before giving up.
9010                 */
9011                if (!origin.staged && pkgLite.recommendedInstallLocation
9012                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9013                    // TODO: focus freeing disk space on the target device
9014                    final StorageManager storage = StorageManager.from(mContext);
9015                    final long lowThreshold = storage.getStorageLowBytes(
9016                            Environment.getDataDirectory());
9017
9018                    final long sizeBytes = mContainerService.calculateInstalledSize(
9019                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9020
9021                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
9022                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9023                                installFlags, packageAbiOverride);
9024                    }
9025
9026                    /*
9027                     * The cache free must have deleted the file we
9028                     * downloaded to install.
9029                     *
9030                     * TODO: fix the "freeCache" call to not delete
9031                     *       the file we care about.
9032                     */
9033                    if (pkgLite.recommendedInstallLocation
9034                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9035                        pkgLite.recommendedInstallLocation
9036                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9037                    }
9038                }
9039            }
9040
9041            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9042                int loc = pkgLite.recommendedInstallLocation;
9043                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9044                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9045                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9046                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9047                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9048                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9049                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9050                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9051                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9052                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9053                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9054                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9055                } else {
9056                    // Override with defaults if needed.
9057                    loc = installLocationPolicy(pkgLite);
9058                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9059                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9060                    } else if (!onSd && !onInt) {
9061                        // Override install location with flags
9062                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9063                            // Set the flag to install on external media.
9064                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9065                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9066                        } else {
9067                            // Make sure the flag for installing on external
9068                            // media is unset
9069                            installFlags |= PackageManager.INSTALL_INTERNAL;
9070                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9071                        }
9072                    }
9073                }
9074            }
9075
9076            final InstallArgs args = createInstallArgs(this);
9077            mArgs = args;
9078
9079            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9080                 /*
9081                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9082                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9083                 */
9084                int userIdentifier = getUser().getIdentifier();
9085                if (userIdentifier == UserHandle.USER_ALL
9086                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9087                    userIdentifier = UserHandle.USER_OWNER;
9088                }
9089
9090                /*
9091                 * Determine if we have any installed package verifiers. If we
9092                 * do, then we'll defer to them to verify the packages.
9093                 */
9094                final int requiredUid = mRequiredVerifierPackage == null ? -1
9095                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9096                if (!origin.existing && requiredUid != -1
9097                        && isVerificationEnabled(userIdentifier, installFlags)) {
9098                    final Intent verification = new Intent(
9099                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9100                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9101                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9102                            PACKAGE_MIME_TYPE);
9103                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9104
9105                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9106                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9107                            0 /* TODO: Which userId? */);
9108
9109                    if (DEBUG_VERIFY) {
9110                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9111                                + verification.toString() + " with " + pkgLite.verifiers.length
9112                                + " optional verifiers");
9113                    }
9114
9115                    final int verificationId = mPendingVerificationToken++;
9116
9117                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9118
9119                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9120                            installerPackageName);
9121
9122                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9123                            installFlags);
9124
9125                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9126                            pkgLite.packageName);
9127
9128                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9129                            pkgLite.versionCode);
9130
9131                    if (verificationParams != null) {
9132                        if (verificationParams.getVerificationURI() != null) {
9133                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9134                                 verificationParams.getVerificationURI());
9135                        }
9136                        if (verificationParams.getOriginatingURI() != null) {
9137                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9138                                  verificationParams.getOriginatingURI());
9139                        }
9140                        if (verificationParams.getReferrer() != null) {
9141                            verification.putExtra(Intent.EXTRA_REFERRER,
9142                                  verificationParams.getReferrer());
9143                        }
9144                        if (verificationParams.getOriginatingUid() >= 0) {
9145                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9146                                  verificationParams.getOriginatingUid());
9147                        }
9148                        if (verificationParams.getInstallerUid() >= 0) {
9149                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9150                                  verificationParams.getInstallerUid());
9151                        }
9152                    }
9153
9154                    final PackageVerificationState verificationState = new PackageVerificationState(
9155                            requiredUid, args);
9156
9157                    mPendingVerification.append(verificationId, verificationState);
9158
9159                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9160                            receivers, verificationState);
9161
9162                    /*
9163                     * If any sufficient verifiers were listed in the package
9164                     * manifest, attempt to ask them.
9165                     */
9166                    if (sufficientVerifiers != null) {
9167                        final int N = sufficientVerifiers.size();
9168                        if (N == 0) {
9169                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9170                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9171                        } else {
9172                            for (int i = 0; i < N; i++) {
9173                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9174
9175                                final Intent sufficientIntent = new Intent(verification);
9176                                sufficientIntent.setComponent(verifierComponent);
9177
9178                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9179                            }
9180                        }
9181                    }
9182
9183                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9184                            mRequiredVerifierPackage, receivers);
9185                    if (ret == PackageManager.INSTALL_SUCCEEDED
9186                            && mRequiredVerifierPackage != null) {
9187                        /*
9188                         * Send the intent to the required verification agent,
9189                         * but only start the verification timeout after the
9190                         * target BroadcastReceivers have run.
9191                         */
9192                        verification.setComponent(requiredVerifierComponent);
9193                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9194                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9195                                new BroadcastReceiver() {
9196                                    @Override
9197                                    public void onReceive(Context context, Intent intent) {
9198                                        final Message msg = mHandler
9199                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9200                                        msg.arg1 = verificationId;
9201                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9202                                    }
9203                                }, null, 0, null, null);
9204
9205                        /*
9206                         * We don't want the copy to proceed until verification
9207                         * succeeds, so null out this field.
9208                         */
9209                        mArgs = null;
9210                    }
9211                } else {
9212                    /*
9213                     * No package verification is enabled, so immediately start
9214                     * the remote call to initiate copy using temporary file.
9215                     */
9216                    ret = args.copyApk(mContainerService, true);
9217                }
9218            }
9219
9220            mRet = ret;
9221        }
9222
9223        @Override
9224        void handleReturnCode() {
9225            // If mArgs is null, then MCS couldn't be reached. When it
9226            // reconnects, it will try again to install. At that point, this
9227            // will succeed.
9228            if (mArgs != null) {
9229                processPendingInstall(mArgs, mRet);
9230            }
9231        }
9232
9233        @Override
9234        void handleServiceError() {
9235            mArgs = createInstallArgs(this);
9236            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9237        }
9238
9239        public boolean isForwardLocked() {
9240            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9241        }
9242    }
9243
9244    /**
9245     * Used during creation of InstallArgs
9246     *
9247     * @param installFlags package installation flags
9248     * @return true if should be installed on external storage
9249     */
9250    private static boolean installOnSd(int installFlags) {
9251        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9252            return false;
9253        }
9254        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9255            return true;
9256        }
9257        return false;
9258    }
9259
9260    /**
9261     * Used during creation of InstallArgs
9262     *
9263     * @param installFlags package installation flags
9264     * @return true if should be installed as forward locked
9265     */
9266    private static boolean installForwardLocked(int installFlags) {
9267        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9268    }
9269
9270    private InstallArgs createInstallArgs(InstallParams params) {
9271        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
9272            return new AsecInstallArgs(params);
9273        } else {
9274            return new FileInstallArgs(params);
9275        }
9276    }
9277
9278    /**
9279     * Create args that describe an existing installed package. Typically used
9280     * when cleaning up old installs, or used as a move source.
9281     */
9282    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9283            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9284        final boolean isInAsec;
9285        if (installOnSd(installFlags)) {
9286            /* Apps on SD card are always in ASEC containers. */
9287            isInAsec = true;
9288        } else if (installForwardLocked(installFlags)
9289                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9290            /*
9291             * Forward-locked apps are only in ASEC containers if they're the
9292             * new style
9293             */
9294            isInAsec = true;
9295        } else {
9296            isInAsec = false;
9297        }
9298
9299        if (isInAsec) {
9300            return new AsecInstallArgs(codePath, instructionSets,
9301                    installOnSd(installFlags), installForwardLocked(installFlags));
9302        } else {
9303            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9304                    instructionSets);
9305        }
9306    }
9307
9308    static abstract class InstallArgs {
9309        /** @see InstallParams#origin */
9310        final OriginInfo origin;
9311
9312        final IPackageInstallObserver2 observer;
9313        // Always refers to PackageManager flags only
9314        final int installFlags;
9315        final String installerPackageName;
9316        final ManifestDigest manifestDigest;
9317        final UserHandle user;
9318        final String abiOverride;
9319
9320        // The list of instruction sets supported by this app. This is currently
9321        // only used during the rmdex() phase to clean up resources. We can get rid of this
9322        // if we move dex files under the common app path.
9323        /* nullable */ String[] instructionSets;
9324
9325        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9326                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9327                String[] instructionSets, String abiOverride) {
9328            this.origin = origin;
9329            this.installFlags = installFlags;
9330            this.observer = observer;
9331            this.installerPackageName = installerPackageName;
9332            this.manifestDigest = manifestDigest;
9333            this.user = user;
9334            this.instructionSets = instructionSets;
9335            this.abiOverride = abiOverride;
9336        }
9337
9338        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9339        abstract int doPreInstall(int status);
9340
9341        /**
9342         * Rename package into final resting place. All paths on the given
9343         * scanned package should be updated to reflect the rename.
9344         */
9345        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9346        abstract int doPostInstall(int status, int uid);
9347
9348        /** @see PackageSettingBase#codePathString */
9349        abstract String getCodePath();
9350        /** @see PackageSettingBase#resourcePathString */
9351        abstract String getResourcePath();
9352        abstract String getLegacyNativeLibraryPath();
9353
9354        // Need installer lock especially for dex file removal.
9355        abstract void cleanUpResourcesLI();
9356        abstract boolean doPostDeleteLI(boolean delete);
9357        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9358
9359        /**
9360         * Called before the source arguments are copied. This is used mostly
9361         * for MoveParams when it needs to read the source file to put it in the
9362         * destination.
9363         */
9364        int doPreCopy() {
9365            return PackageManager.INSTALL_SUCCEEDED;
9366        }
9367
9368        /**
9369         * Called after the source arguments are copied. This is used mostly for
9370         * MoveParams when it needs to read the source file to put it in the
9371         * destination.
9372         *
9373         * @return
9374         */
9375        int doPostCopy(int uid) {
9376            return PackageManager.INSTALL_SUCCEEDED;
9377        }
9378
9379        protected boolean isFwdLocked() {
9380            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9381        }
9382
9383        protected boolean isExternal() {
9384            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9385        }
9386
9387        UserHandle getUser() {
9388            return user;
9389        }
9390    }
9391
9392    /**
9393     * Logic to handle installation of non-ASEC applications, including copying
9394     * and renaming logic.
9395     */
9396    class FileInstallArgs extends InstallArgs {
9397        private File codeFile;
9398        private File resourceFile;
9399        private File legacyNativeLibraryPath;
9400
9401        // Example topology:
9402        // /data/app/com.example/base.apk
9403        // /data/app/com.example/split_foo.apk
9404        // /data/app/com.example/lib/arm/libfoo.so
9405        // /data/app/com.example/lib/arm64/libfoo.so
9406        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9407
9408        /** New install */
9409        FileInstallArgs(InstallParams params) {
9410            super(params.origin, params.observer, params.installFlags,
9411                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9412                    null /* instruction sets */, params.packageAbiOverride);
9413            if (isFwdLocked()) {
9414                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9415            }
9416        }
9417
9418        /** Existing install */
9419        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9420                String[] instructionSets) {
9421            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9422            this.codeFile = (codePath != null) ? new File(codePath) : null;
9423            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9424            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9425                    new File(legacyNativeLibraryPath) : null;
9426        }
9427
9428        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9429            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9430                    isFwdLocked(), abiOverride);
9431
9432            final StorageManager storage = StorageManager.from(mContext);
9433            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9434        }
9435
9436        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9437            if (origin.staged) {
9438                Slog.d(TAG, origin.file + " already staged; skipping copy");
9439                codeFile = origin.file;
9440                resourceFile = origin.file;
9441                return PackageManager.INSTALL_SUCCEEDED;
9442            }
9443
9444            try {
9445                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9446                codeFile = tempDir;
9447                resourceFile = tempDir;
9448            } catch (IOException e) {
9449                Slog.w(TAG, "Failed to create copy file: " + e);
9450                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9451            }
9452
9453            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9454                @Override
9455                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9456                    if (!FileUtils.isValidExtFilename(name)) {
9457                        throw new IllegalArgumentException("Invalid filename: " + name);
9458                    }
9459                    try {
9460                        final File file = new File(codeFile, name);
9461                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9462                                O_RDWR | O_CREAT, 0644);
9463                        Os.chmod(file.getAbsolutePath(), 0644);
9464                        return new ParcelFileDescriptor(fd);
9465                    } catch (ErrnoException e) {
9466                        throw new RemoteException("Failed to open: " + e.getMessage());
9467                    }
9468                }
9469            };
9470
9471            int ret = PackageManager.INSTALL_SUCCEEDED;
9472            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9473            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9474                Slog.e(TAG, "Failed to copy package");
9475                return ret;
9476            }
9477
9478            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9479            NativeLibraryHelper.Handle handle = null;
9480            try {
9481                handle = NativeLibraryHelper.Handle.create(codeFile);
9482                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9483                        abiOverride);
9484            } catch (IOException e) {
9485                Slog.e(TAG, "Copying native libraries failed", e);
9486                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9487            } finally {
9488                IoUtils.closeQuietly(handle);
9489            }
9490
9491            return ret;
9492        }
9493
9494        int doPreInstall(int status) {
9495            if (status != PackageManager.INSTALL_SUCCEEDED) {
9496                cleanUp();
9497            }
9498            return status;
9499        }
9500
9501        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9502            if (status != PackageManager.INSTALL_SUCCEEDED) {
9503                cleanUp();
9504                return false;
9505            } else {
9506                final File beforeCodeFile = codeFile;
9507                final File afterCodeFile = getNextCodePath(pkg.packageName);
9508
9509                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9510                try {
9511                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9512                } catch (ErrnoException e) {
9513                    Slog.d(TAG, "Failed to rename", e);
9514                    return false;
9515                }
9516
9517                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9518                    Slog.d(TAG, "Failed to restorecon");
9519                    return false;
9520                }
9521
9522                // Reflect the rename internally
9523                codeFile = afterCodeFile;
9524                resourceFile = afterCodeFile;
9525
9526                // Reflect the rename in scanned details
9527                pkg.codePath = afterCodeFile.getAbsolutePath();
9528                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9529                        pkg.baseCodePath);
9530                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9531                        pkg.splitCodePaths);
9532
9533                // Reflect the rename in app info
9534                pkg.applicationInfo.setCodePath(pkg.codePath);
9535                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9536                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9537                pkg.applicationInfo.setResourcePath(pkg.codePath);
9538                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9539                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9540
9541                return true;
9542            }
9543        }
9544
9545        int doPostInstall(int status, int uid) {
9546            if (status != PackageManager.INSTALL_SUCCEEDED) {
9547                cleanUp();
9548            }
9549            return status;
9550        }
9551
9552        @Override
9553        String getCodePath() {
9554            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9555        }
9556
9557        @Override
9558        String getResourcePath() {
9559            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9560        }
9561
9562        @Override
9563        String getLegacyNativeLibraryPath() {
9564            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9565        }
9566
9567        private boolean cleanUp() {
9568            if (codeFile == null || !codeFile.exists()) {
9569                return false;
9570            }
9571
9572            if (codeFile.isDirectory()) {
9573                FileUtils.deleteContents(codeFile);
9574            }
9575            codeFile.delete();
9576
9577            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9578                resourceFile.delete();
9579            }
9580
9581            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9582                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9583                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9584                }
9585                legacyNativeLibraryPath.delete();
9586            }
9587
9588            return true;
9589        }
9590
9591        void cleanUpResourcesLI() {
9592            // Try enumerating all code paths before deleting
9593            List<String> allCodePaths = Collections.EMPTY_LIST;
9594            if (codeFile != null && codeFile.exists()) {
9595                try {
9596                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9597                    allCodePaths = pkg.getAllCodePaths();
9598                } catch (PackageParserException e) {
9599                    // Ignored; we tried our best
9600                }
9601            }
9602
9603            cleanUp();
9604
9605            if (!allCodePaths.isEmpty()) {
9606                if (instructionSets == null) {
9607                    throw new IllegalStateException("instructionSet == null");
9608                }
9609                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9610                for (String codePath : allCodePaths) {
9611                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9612                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9613                        if (retCode < 0) {
9614                            Slog.w(TAG, "Couldn't remove dex file for package: "
9615                                    + " at location " + codePath + ", retcode=" + retCode);
9616                            // we don't consider this to be a failure of the core package deletion
9617                        }
9618                    }
9619                }
9620            }
9621        }
9622
9623        boolean doPostDeleteLI(boolean delete) {
9624            // XXX err, shouldn't we respect the delete flag?
9625            cleanUpResourcesLI();
9626            return true;
9627        }
9628    }
9629
9630    private boolean isAsecExternal(String cid) {
9631        final String asecPath = PackageHelper.getSdFilesystem(cid);
9632        return !asecPath.startsWith(mAsecInternalPath);
9633    }
9634
9635    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9636            PackageManagerException {
9637        if (copyRet < 0) {
9638            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9639                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9640                throw new PackageManagerException(copyRet, message);
9641            }
9642        }
9643    }
9644
9645    /**
9646     * Extract the MountService "container ID" from the full code path of an
9647     * .apk.
9648     */
9649    static String cidFromCodePath(String fullCodePath) {
9650        int eidx = fullCodePath.lastIndexOf("/");
9651        String subStr1 = fullCodePath.substring(0, eidx);
9652        int sidx = subStr1.lastIndexOf("/");
9653        return subStr1.substring(sidx+1, eidx);
9654    }
9655
9656    /**
9657     * Logic to handle installation of ASEC applications, including copying and
9658     * renaming logic.
9659     */
9660    class AsecInstallArgs extends InstallArgs {
9661        static final String RES_FILE_NAME = "pkg.apk";
9662        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9663
9664        String cid;
9665        String packagePath;
9666        String resourcePath;
9667        String legacyNativeLibraryDir;
9668
9669        /** New install */
9670        AsecInstallArgs(InstallParams params) {
9671            super(params.origin, params.observer, params.installFlags,
9672                    params.installerPackageName, params.getManifestDigest(),
9673                    params.getUser(), null /* instruction sets */,
9674                    params.packageAbiOverride);
9675        }
9676
9677        /** Existing install */
9678        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9679                        boolean isExternal, boolean isForwardLocked) {
9680            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9681                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9682                    instructionSets, null);
9683            // Hackily pretend we're still looking at a full code path
9684            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9685                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9686            }
9687
9688            // Extract cid from fullCodePath
9689            int eidx = fullCodePath.lastIndexOf("/");
9690            String subStr1 = fullCodePath.substring(0, eidx);
9691            int sidx = subStr1.lastIndexOf("/");
9692            cid = subStr1.substring(sidx+1, eidx);
9693            setMountPath(subStr1);
9694        }
9695
9696        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9697            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9698                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9699                    instructionSets, null);
9700            this.cid = cid;
9701            setMountPath(PackageHelper.getSdDir(cid));
9702        }
9703
9704        void createCopyFile() {
9705            cid = mInstallerService.allocateExternalStageCidLegacy();
9706        }
9707
9708        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9709            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9710                    abiOverride);
9711
9712            final File target;
9713            if (isExternal()) {
9714                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9715            } else {
9716                target = Environment.getDataDirectory();
9717            }
9718
9719            final StorageManager storage = StorageManager.from(mContext);
9720            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9721        }
9722
9723        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9724            if (origin.staged) {
9725                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9726                cid = origin.cid;
9727                setMountPath(PackageHelper.getSdDir(cid));
9728                return PackageManager.INSTALL_SUCCEEDED;
9729            }
9730
9731            if (temp) {
9732                createCopyFile();
9733            } else {
9734                /*
9735                 * Pre-emptively destroy the container since it's destroyed if
9736                 * copying fails due to it existing anyway.
9737                 */
9738                PackageHelper.destroySdDir(cid);
9739            }
9740
9741            final String newMountPath = imcs.copyPackageToContainer(
9742                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9743                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9744
9745            if (newMountPath != null) {
9746                setMountPath(newMountPath);
9747                return PackageManager.INSTALL_SUCCEEDED;
9748            } else {
9749                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9750            }
9751        }
9752
9753        @Override
9754        String getCodePath() {
9755            return packagePath;
9756        }
9757
9758        @Override
9759        String getResourcePath() {
9760            return resourcePath;
9761        }
9762
9763        @Override
9764        String getLegacyNativeLibraryPath() {
9765            return legacyNativeLibraryDir;
9766        }
9767
9768        int doPreInstall(int status) {
9769            if (status != PackageManager.INSTALL_SUCCEEDED) {
9770                // Destroy container
9771                PackageHelper.destroySdDir(cid);
9772            } else {
9773                boolean mounted = PackageHelper.isContainerMounted(cid);
9774                if (!mounted) {
9775                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9776                            Process.SYSTEM_UID);
9777                    if (newMountPath != null) {
9778                        setMountPath(newMountPath);
9779                    } else {
9780                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9781                    }
9782                }
9783            }
9784            return status;
9785        }
9786
9787        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9788            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9789            String newMountPath = null;
9790            if (PackageHelper.isContainerMounted(cid)) {
9791                // Unmount the container
9792                if (!PackageHelper.unMountSdDir(cid)) {
9793                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9794                    return false;
9795                }
9796            }
9797            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9798                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9799                        " which might be stale. Will try to clean up.");
9800                // Clean up the stale container and proceed to recreate.
9801                if (!PackageHelper.destroySdDir(newCacheId)) {
9802                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9803                    return false;
9804                }
9805                // Successfully cleaned up stale container. Try to rename again.
9806                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9807                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9808                            + " inspite of cleaning it up.");
9809                    return false;
9810                }
9811            }
9812            if (!PackageHelper.isContainerMounted(newCacheId)) {
9813                Slog.w(TAG, "Mounting container " + newCacheId);
9814                newMountPath = PackageHelper.mountSdDir(newCacheId,
9815                        getEncryptKey(), Process.SYSTEM_UID);
9816            } else {
9817                newMountPath = PackageHelper.getSdDir(newCacheId);
9818            }
9819            if (newMountPath == null) {
9820                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9821                return false;
9822            }
9823            Log.i(TAG, "Succesfully renamed " + cid +
9824                    " to " + newCacheId +
9825                    " at new path: " + newMountPath);
9826            cid = newCacheId;
9827
9828            final File beforeCodeFile = new File(packagePath);
9829            setMountPath(newMountPath);
9830            final File afterCodeFile = new File(packagePath);
9831
9832            // Reflect the rename in scanned details
9833            pkg.codePath = afterCodeFile.getAbsolutePath();
9834            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9835                    pkg.baseCodePath);
9836            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9837                    pkg.splitCodePaths);
9838
9839            // Reflect the rename in app info
9840            pkg.applicationInfo.setCodePath(pkg.codePath);
9841            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9842            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9843            pkg.applicationInfo.setResourcePath(pkg.codePath);
9844            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9845            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9846
9847            return true;
9848        }
9849
9850        private void setMountPath(String mountPath) {
9851            final File mountFile = new File(mountPath);
9852
9853            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9854            if (monolithicFile.exists()) {
9855                packagePath = monolithicFile.getAbsolutePath();
9856                if (isFwdLocked()) {
9857                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9858                } else {
9859                    resourcePath = packagePath;
9860                }
9861            } else {
9862                packagePath = mountFile.getAbsolutePath();
9863                resourcePath = packagePath;
9864            }
9865
9866            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9867        }
9868
9869        int doPostInstall(int status, int uid) {
9870            if (status != PackageManager.INSTALL_SUCCEEDED) {
9871                cleanUp();
9872            } else {
9873                final int groupOwner;
9874                final String protectedFile;
9875                if (isFwdLocked()) {
9876                    groupOwner = UserHandle.getSharedAppGid(uid);
9877                    protectedFile = RES_FILE_NAME;
9878                } else {
9879                    groupOwner = -1;
9880                    protectedFile = null;
9881                }
9882
9883                if (uid < Process.FIRST_APPLICATION_UID
9884                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9885                    Slog.e(TAG, "Failed to finalize " + cid);
9886                    PackageHelper.destroySdDir(cid);
9887                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9888                }
9889
9890                boolean mounted = PackageHelper.isContainerMounted(cid);
9891                if (!mounted) {
9892                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9893                }
9894            }
9895            return status;
9896        }
9897
9898        private void cleanUp() {
9899            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9900
9901            // Destroy secure container
9902            PackageHelper.destroySdDir(cid);
9903        }
9904
9905        private List<String> getAllCodePaths() {
9906            final File codeFile = new File(getCodePath());
9907            if (codeFile != null && codeFile.exists()) {
9908                try {
9909                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9910                    return pkg.getAllCodePaths();
9911                } catch (PackageParserException e) {
9912                    // Ignored; we tried our best
9913                }
9914            }
9915            return Collections.EMPTY_LIST;
9916        }
9917
9918        void cleanUpResourcesLI() {
9919            // Enumerate all code paths before deleting
9920            cleanUpResourcesLI(getAllCodePaths());
9921        }
9922
9923        private void cleanUpResourcesLI(List<String> allCodePaths) {
9924            cleanUp();
9925
9926            if (!allCodePaths.isEmpty()) {
9927                if (instructionSets == null) {
9928                    throw new IllegalStateException("instructionSet == null");
9929                }
9930                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9931                for (String codePath : allCodePaths) {
9932                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9933                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9934                        if (retCode < 0) {
9935                            Slog.w(TAG, "Couldn't remove dex file for package: "
9936                                    + " at location " + codePath + ", retcode=" + retCode);
9937                            // we don't consider this to be a failure of the core package deletion
9938                        }
9939                    }
9940                }
9941            }
9942        }
9943
9944        boolean matchContainer(String app) {
9945            if (cid.startsWith(app)) {
9946                return true;
9947            }
9948            return false;
9949        }
9950
9951        String getPackageName() {
9952            return getAsecPackageName(cid);
9953        }
9954
9955        boolean doPostDeleteLI(boolean delete) {
9956            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9957            final List<String> allCodePaths = getAllCodePaths();
9958            boolean mounted = PackageHelper.isContainerMounted(cid);
9959            if (mounted) {
9960                // Unmount first
9961                if (PackageHelper.unMountSdDir(cid)) {
9962                    mounted = false;
9963                }
9964            }
9965            if (!mounted && delete) {
9966                cleanUpResourcesLI(allCodePaths);
9967            }
9968            return !mounted;
9969        }
9970
9971        @Override
9972        int doPreCopy() {
9973            if (isFwdLocked()) {
9974                if (!PackageHelper.fixSdPermissions(cid,
9975                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9976                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9977                }
9978            }
9979
9980            return PackageManager.INSTALL_SUCCEEDED;
9981        }
9982
9983        @Override
9984        int doPostCopy(int uid) {
9985            if (isFwdLocked()) {
9986                if (uid < Process.FIRST_APPLICATION_UID
9987                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9988                                RES_FILE_NAME)) {
9989                    Slog.e(TAG, "Failed to finalize " + cid);
9990                    PackageHelper.destroySdDir(cid);
9991                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9992                }
9993            }
9994
9995            return PackageManager.INSTALL_SUCCEEDED;
9996        }
9997    }
9998
9999    static String getAsecPackageName(String packageCid) {
10000        int idx = packageCid.lastIndexOf("-");
10001        if (idx == -1) {
10002            return packageCid;
10003        }
10004        return packageCid.substring(0, idx);
10005    }
10006
10007    // Utility method used to create code paths based on package name and available index.
10008    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
10009        String idxStr = "";
10010        int idx = 1;
10011        // Fall back to default value of idx=1 if prefix is not
10012        // part of oldCodePath
10013        if (oldCodePath != null) {
10014            String subStr = oldCodePath;
10015            // Drop the suffix right away
10016            if (suffix != null && subStr.endsWith(suffix)) {
10017                subStr = subStr.substring(0, subStr.length() - suffix.length());
10018            }
10019            // If oldCodePath already contains prefix find out the
10020            // ending index to either increment or decrement.
10021            int sidx = subStr.lastIndexOf(prefix);
10022            if (sidx != -1) {
10023                subStr = subStr.substring(sidx + prefix.length());
10024                if (subStr != null) {
10025                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10026                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10027                    }
10028                    try {
10029                        idx = Integer.parseInt(subStr);
10030                        if (idx <= 1) {
10031                            idx++;
10032                        } else {
10033                            idx--;
10034                        }
10035                    } catch(NumberFormatException e) {
10036                    }
10037                }
10038            }
10039        }
10040        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10041        return prefix + idxStr;
10042    }
10043
10044    private File getNextCodePath(String packageName) {
10045        int suffix = 1;
10046        File result;
10047        do {
10048            result = new File(mAppInstallDir, packageName + "-" + suffix);
10049            suffix++;
10050        } while (result.exists());
10051        return result;
10052    }
10053
10054    // Utility method used to ignore ADD/REMOVE events
10055    // by directory observer.
10056    private static boolean ignoreCodePath(String fullPathStr) {
10057        String apkName = deriveCodePathName(fullPathStr);
10058        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
10059        if (idx != -1 && ((idx+1) < apkName.length())) {
10060            // Make sure the package ends with a numeral
10061            String version = apkName.substring(idx+1);
10062            try {
10063                Integer.parseInt(version);
10064                return true;
10065            } catch (NumberFormatException e) {}
10066        }
10067        return false;
10068    }
10069
10070    // Utility method that returns the relative package path with respect
10071    // to the installation directory. Like say for /data/data/com.test-1.apk
10072    // string com.test-1 is returned.
10073    static String deriveCodePathName(String codePath) {
10074        if (codePath == null) {
10075            return null;
10076        }
10077        final File codeFile = new File(codePath);
10078        final String name = codeFile.getName();
10079        if (codeFile.isDirectory()) {
10080            return name;
10081        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10082            final int lastDot = name.lastIndexOf('.');
10083            return name.substring(0, lastDot);
10084        } else {
10085            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10086            return null;
10087        }
10088    }
10089
10090    class PackageInstalledInfo {
10091        String name;
10092        int uid;
10093        // The set of users that originally had this package installed.
10094        int[] origUsers;
10095        // The set of users that now have this package installed.
10096        int[] newUsers;
10097        PackageParser.Package pkg;
10098        int returnCode;
10099        String returnMsg;
10100        PackageRemovedInfo removedInfo;
10101
10102        public void setError(int code, String msg) {
10103            returnCode = code;
10104            returnMsg = msg;
10105            Slog.w(TAG, msg);
10106        }
10107
10108        public void setError(String msg, PackageParserException e) {
10109            returnCode = e.error;
10110            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10111            Slog.w(TAG, msg, e);
10112        }
10113
10114        public void setError(String msg, PackageManagerException e) {
10115            returnCode = e.error;
10116            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10117            Slog.w(TAG, msg, e);
10118        }
10119
10120        // In some error cases we want to convey more info back to the observer
10121        String origPackage;
10122        String origPermission;
10123    }
10124
10125    /*
10126     * Install a non-existing package.
10127     */
10128    private void installNewPackageLI(PackageParser.Package pkg,
10129            int parseFlags, int scanFlags, UserHandle user,
10130            String installerPackageName, PackageInstalledInfo res) {
10131        // Remember this for later, in case we need to rollback this install
10132        String pkgName = pkg.packageName;
10133
10134        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10135        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
10136        synchronized(mPackages) {
10137            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10138                // A package with the same name is already installed, though
10139                // it has been renamed to an older name.  The package we
10140                // are trying to install should be installed as an update to
10141                // the existing one, but that has not been requested, so bail.
10142                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10143                        + " without first uninstalling package running as "
10144                        + mSettings.mRenamedPackages.get(pkgName));
10145                return;
10146            }
10147            if (mPackages.containsKey(pkgName)) {
10148                // Don't allow installation over an existing package with the same name.
10149                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10150                        + " without first uninstalling.");
10151                return;
10152            }
10153        }
10154
10155        try {
10156            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10157                    System.currentTimeMillis(), user);
10158
10159            updateSettingsLI(newPackage, installerPackageName, null, null, res);
10160            // delete the partially installed application. the data directory will have to be
10161            // restored if it was already existing
10162            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10163                // remove package from internal structures.  Note that we want deletePackageX to
10164                // delete the package data and cache directories that it created in
10165                // scanPackageLocked, unless those directories existed before we even tried to
10166                // install.
10167                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10168                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10169                                res.removedInfo, true);
10170            }
10171
10172        } catch (PackageManagerException e) {
10173            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10174        }
10175    }
10176
10177    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10178        // Upgrade keysets are being used.  Determine if new package has a superset of the
10179        // required keys.
10180        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10181        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10182        for (int i = 0; i < upgradeKeySets.length; i++) {
10183            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10184            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10185                return true;
10186            }
10187        }
10188        return false;
10189    }
10190
10191    private void replacePackageLI(PackageParser.Package pkg,
10192            int parseFlags, int scanFlags, UserHandle user,
10193            String installerPackageName, PackageInstalledInfo res) {
10194        PackageParser.Package oldPackage;
10195        String pkgName = pkg.packageName;
10196        int[] allUsers;
10197        boolean[] perUserInstalled;
10198
10199        // First find the old package info and check signatures
10200        synchronized(mPackages) {
10201            oldPackage = mPackages.get(pkgName);
10202            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10203            PackageSetting ps = mSettings.mPackages.get(pkgName);
10204            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10205                // default to original signature matching
10206                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10207                    != PackageManager.SIGNATURE_MATCH) {
10208                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10209                            "New package has a different signature: " + pkgName);
10210                    return;
10211                }
10212            } else {
10213                if(!checkUpgradeKeySetLP(ps, pkg)) {
10214                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10215                            "New package not signed by keys specified by upgrade-keysets: "
10216                            + pkgName);
10217                    return;
10218                }
10219            }
10220
10221            // In case of rollback, remember per-user/profile install state
10222            allUsers = sUserManager.getUserIds();
10223            perUserInstalled = new boolean[allUsers.length];
10224            for (int i = 0; i < allUsers.length; i++) {
10225                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10226            }
10227        }
10228
10229        boolean sysPkg = (isSystemApp(oldPackage));
10230        if (sysPkg) {
10231            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10232                    user, allUsers, perUserInstalled, installerPackageName, res);
10233        } else {
10234            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10235                    user, allUsers, perUserInstalled, installerPackageName, res);
10236        }
10237    }
10238
10239    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10240            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10241            int[] allUsers, boolean[] perUserInstalled,
10242            String installerPackageName, PackageInstalledInfo res) {
10243        String pkgName = deletedPackage.packageName;
10244        boolean deletedPkg = true;
10245        boolean updatedSettings = false;
10246
10247        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10248                + deletedPackage);
10249        long origUpdateTime;
10250        if (pkg.mExtras != null) {
10251            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10252        } else {
10253            origUpdateTime = 0;
10254        }
10255
10256        // First delete the existing package while retaining the data directory
10257        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10258                res.removedInfo, true)) {
10259            // If the existing package wasn't successfully deleted
10260            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10261            deletedPkg = false;
10262        } else {
10263            // Successfully deleted the old package; proceed with replace.
10264
10265            // If deleted package lived in a container, give users a chance to
10266            // relinquish resources before killing.
10267            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
10268                if (DEBUG_INSTALL) {
10269                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10270                }
10271                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10272                final ArrayList<String> pkgList = new ArrayList<String>(1);
10273                pkgList.add(deletedPackage.applicationInfo.packageName);
10274                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10275            }
10276
10277            deleteCodeCacheDirsLI(pkgName);
10278            try {
10279                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10280                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10281                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10282                updatedSettings = true;
10283            } catch (PackageManagerException e) {
10284                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10285            }
10286        }
10287
10288        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10289            // remove package from internal structures.  Note that we want deletePackageX to
10290            // delete the package data and cache directories that it created in
10291            // scanPackageLocked, unless those directories existed before we even tried to
10292            // install.
10293            if(updatedSettings) {
10294                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10295                deletePackageLI(
10296                        pkgName, null, true, allUsers, perUserInstalled,
10297                        PackageManager.DELETE_KEEP_DATA,
10298                                res.removedInfo, true);
10299            }
10300            // Since we failed to install the new package we need to restore the old
10301            // package that we deleted.
10302            if (deletedPkg) {
10303                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10304                File restoreFile = new File(deletedPackage.codePath);
10305                // Parse old package
10306                boolean oldOnSd = isExternal(deletedPackage);
10307                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10308                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10309                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10310                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10311                try {
10312                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10313                } catch (PackageManagerException e) {
10314                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10315                            + e.getMessage());
10316                    return;
10317                }
10318                // Restore of old package succeeded. Update permissions.
10319                // writer
10320                synchronized (mPackages) {
10321                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10322                            UPDATE_PERMISSIONS_ALL);
10323                    // can downgrade to reader
10324                    mSettings.writeLPr();
10325                }
10326                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10327            }
10328        }
10329    }
10330
10331    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10332            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10333            int[] allUsers, boolean[] perUserInstalled,
10334            String installerPackageName, PackageInstalledInfo res) {
10335        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10336                + ", old=" + deletedPackage);
10337        boolean disabledSystem = false;
10338        boolean updatedSettings = false;
10339        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10340        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10341            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10342        }
10343        String packageName = deletedPackage.packageName;
10344        if (packageName == null) {
10345            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10346                    "Attempt to delete null packageName.");
10347            return;
10348        }
10349        PackageParser.Package oldPkg;
10350        PackageSetting oldPkgSetting;
10351        // reader
10352        synchronized (mPackages) {
10353            oldPkg = mPackages.get(packageName);
10354            oldPkgSetting = mSettings.mPackages.get(packageName);
10355            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10356                    (oldPkgSetting == null)) {
10357                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10358                        "Couldn't find package:" + packageName + " information");
10359                return;
10360            }
10361        }
10362
10363        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10364
10365        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10366        res.removedInfo.removedPackage = packageName;
10367        // Remove existing system package
10368        removePackageLI(oldPkgSetting, true);
10369        // writer
10370        synchronized (mPackages) {
10371            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10372            if (!disabledSystem && deletedPackage != null) {
10373                // We didn't need to disable the .apk as a current system package,
10374                // which means we are replacing another update that is already
10375                // installed.  We need to make sure to delete the older one's .apk.
10376                res.removedInfo.args = createInstallArgsForExisting(0,
10377                        deletedPackage.applicationInfo.getCodePath(),
10378                        deletedPackage.applicationInfo.getResourcePath(),
10379                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10380                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10381            } else {
10382                res.removedInfo.args = null;
10383            }
10384        }
10385
10386        // Successfully disabled the old package. Now proceed with re-installation
10387        deleteCodeCacheDirsLI(packageName);
10388
10389        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10390        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10391
10392        PackageParser.Package newPackage = null;
10393        try {
10394            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10395            if (newPackage.mExtras != null) {
10396                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10397                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10398                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10399
10400                // is the update attempting to change shared user? that isn't going to work...
10401                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10402                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10403                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10404                            + " to " + newPkgSetting.sharedUser);
10405                    updatedSettings = true;
10406                }
10407            }
10408
10409            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10410                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10411                updatedSettings = true;
10412            }
10413
10414        } catch (PackageManagerException e) {
10415            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10416        }
10417
10418        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10419            // Re installation failed. Restore old information
10420            // Remove new pkg information
10421            if (newPackage != null) {
10422                removeInstalledPackageLI(newPackage, true);
10423            }
10424            // Add back the old system package
10425            try {
10426                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10427            } catch (PackageManagerException e) {
10428                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10429            }
10430            // Restore the old system information in Settings
10431            synchronized (mPackages) {
10432                if (disabledSystem) {
10433                    mSettings.enableSystemPackageLPw(packageName);
10434                }
10435                if (updatedSettings) {
10436                    mSettings.setInstallerPackageName(packageName,
10437                            oldPkgSetting.installerPackageName);
10438                }
10439                mSettings.writeLPr();
10440            }
10441        }
10442    }
10443
10444    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10445            int[] allUsers, boolean[] perUserInstalled,
10446            PackageInstalledInfo res) {
10447        String pkgName = newPackage.packageName;
10448        synchronized (mPackages) {
10449            //write settings. the installStatus will be incomplete at this stage.
10450            //note that the new package setting would have already been
10451            //added to mPackages. It hasn't been persisted yet.
10452            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10453            mSettings.writeLPr();
10454        }
10455
10456        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10457
10458        synchronized (mPackages) {
10459            updatePermissionsLPw(newPackage.packageName, newPackage,
10460                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10461                            ? UPDATE_PERMISSIONS_ALL : 0));
10462            // For system-bundled packages, we assume that installing an upgraded version
10463            // of the package implies that the user actually wants to run that new code,
10464            // so we enable the package.
10465            if (isSystemApp(newPackage)) {
10466                // NB: implicit assumption that system package upgrades apply to all users
10467                if (DEBUG_INSTALL) {
10468                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10469                }
10470                PackageSetting ps = mSettings.mPackages.get(pkgName);
10471                if (ps != null) {
10472                    if (res.origUsers != null) {
10473                        for (int userHandle : res.origUsers) {
10474                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10475                                    userHandle, installerPackageName);
10476                        }
10477                    }
10478                    // Also convey the prior install/uninstall state
10479                    if (allUsers != null && perUserInstalled != null) {
10480                        for (int i = 0; i < allUsers.length; i++) {
10481                            if (DEBUG_INSTALL) {
10482                                Slog.d(TAG, "    user " + allUsers[i]
10483                                        + " => " + perUserInstalled[i]);
10484                            }
10485                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10486                        }
10487                        // these install state changes will be persisted in the
10488                        // upcoming call to mSettings.writeLPr().
10489                    }
10490                }
10491            }
10492            res.name = pkgName;
10493            res.uid = newPackage.applicationInfo.uid;
10494            res.pkg = newPackage;
10495            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10496            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10497            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10498            //to update install status
10499            mSettings.writeLPr();
10500        }
10501    }
10502
10503    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10504        final int installFlags = args.installFlags;
10505        String installerPackageName = args.installerPackageName;
10506        File tmpPackageFile = new File(args.getCodePath());
10507        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10508        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10509        boolean replace = false;
10510        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10511        // Result object to be returned
10512        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10513
10514        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10515        // Retrieve PackageSettings and parse package
10516        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10517                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10518                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10519        PackageParser pp = new PackageParser();
10520        pp.setSeparateProcesses(mSeparateProcesses);
10521        pp.setDisplayMetrics(mMetrics);
10522
10523        final PackageParser.Package pkg;
10524        try {
10525            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10526        } catch (PackageParserException e) {
10527            res.setError("Failed parse during installPackageLI", e);
10528            return;
10529        }
10530
10531        // Mark that we have an install time CPU ABI override.
10532        pkg.cpuAbiOverride = args.abiOverride;
10533
10534        String pkgName = res.name = pkg.packageName;
10535        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10536            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10537                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10538                return;
10539            }
10540        }
10541
10542        try {
10543            pp.collectCertificates(pkg, parseFlags);
10544            pp.collectManifestDigest(pkg);
10545        } catch (PackageParserException e) {
10546            res.setError("Failed collect during installPackageLI", e);
10547            return;
10548        }
10549
10550        /* If the installer passed in a manifest digest, compare it now. */
10551        if (args.manifestDigest != null) {
10552            if (DEBUG_INSTALL) {
10553                final String parsedManifest = pkg.manifestDigest == null ? "null"
10554                        : pkg.manifestDigest.toString();
10555                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10556                        + parsedManifest);
10557            }
10558
10559            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10560                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10561                return;
10562            }
10563        } else if (DEBUG_INSTALL) {
10564            final String parsedManifest = pkg.manifestDigest == null
10565                    ? "null" : pkg.manifestDigest.toString();
10566            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10567        }
10568
10569        // Get rid of all references to package scan path via parser.
10570        pp = null;
10571        String oldCodePath = null;
10572        boolean systemApp = false;
10573        synchronized (mPackages) {
10574            // Check if installing already existing package
10575            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10576                String oldName = mSettings.mRenamedPackages.get(pkgName);
10577                if (pkg.mOriginalPackages != null
10578                        && pkg.mOriginalPackages.contains(oldName)
10579                        && mPackages.containsKey(oldName)) {
10580                    // This package is derived from an original package,
10581                    // and this device has been updating from that original
10582                    // name.  We must continue using the original name, so
10583                    // rename the new package here.
10584                    pkg.setPackageName(oldName);
10585                    pkgName = pkg.packageName;
10586                    replace = true;
10587                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10588                            + oldName + " pkgName=" + pkgName);
10589                } else if (mPackages.containsKey(pkgName)) {
10590                    // This package, under its official name, already exists
10591                    // on the device; we should replace it.
10592                    replace = true;
10593                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10594                }
10595            }
10596
10597            PackageSetting ps = mSettings.mPackages.get(pkgName);
10598            if (ps != null) {
10599                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10600
10601                // Quick sanity check that we're signed correctly if updating;
10602                // we'll check this again later when scanning, but we want to
10603                // bail early here before tripping over redefined permissions.
10604                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10605                    try {
10606                        verifySignaturesLP(ps, pkg);
10607                    } catch (PackageManagerException e) {
10608                        res.setError(e.error, e.getMessage());
10609                        return;
10610                    }
10611                } else {
10612                    if (!checkUpgradeKeySetLP(ps, pkg)) {
10613                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
10614                                + pkg.packageName + " upgrade keys do not match the "
10615                                + "previously installed version");
10616                        return;
10617                    }
10618                }
10619
10620                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10621                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10622                    systemApp = (ps.pkg.applicationInfo.flags &
10623                            ApplicationInfo.FLAG_SYSTEM) != 0;
10624                }
10625                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10626            }
10627
10628            // Check whether the newly-scanned package wants to define an already-defined perm
10629            int N = pkg.permissions.size();
10630            for (int i = N-1; i >= 0; i--) {
10631                PackageParser.Permission perm = pkg.permissions.get(i);
10632                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10633                if (bp != null) {
10634                    // If the defining package is signed with our cert, it's okay.  This
10635                    // also includes the "updating the same package" case, of course.
10636                    // "updating same package" could also involve key-rotation.
10637                    final boolean sigsOk;
10638                    if (!bp.sourcePackage.equals(pkg.packageName)
10639                            || !(bp.packageSetting instanceof PackageSetting)
10640                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10641                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10642                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10643                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10644                    } else {
10645                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10646                    }
10647                    if (!sigsOk) {
10648                        // If the owning package is the system itself, we log but allow
10649                        // install to proceed; we fail the install on all other permission
10650                        // redefinitions.
10651                        if (!bp.sourcePackage.equals("android")) {
10652                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10653                                    + pkg.packageName + " attempting to redeclare permission "
10654                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10655                            res.origPermission = perm.info.name;
10656                            res.origPackage = bp.sourcePackage;
10657                            return;
10658                        } else {
10659                            Slog.w(TAG, "Package " + pkg.packageName
10660                                    + " attempting to redeclare system permission "
10661                                    + perm.info.name + "; ignoring new declaration");
10662                            pkg.permissions.remove(i);
10663                        }
10664                    }
10665                }
10666            }
10667
10668        }
10669
10670        if (systemApp && onSd) {
10671            // Disable updates to system apps on sdcard
10672            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10673                    "Cannot install updates to system apps on sdcard");
10674            return;
10675        }
10676
10677        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10678            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10679            return;
10680        }
10681
10682        if (replace) {
10683            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10684                    installerPackageName, res);
10685        } else {
10686            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10687                    args.user, installerPackageName, res);
10688        }
10689        synchronized (mPackages) {
10690            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10691            if (ps != null) {
10692                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10693            }
10694        }
10695    }
10696
10697    private static boolean isForwardLocked(PackageParser.Package pkg) {
10698        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10699    }
10700
10701    private static boolean isForwardLocked(ApplicationInfo info) {
10702        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10703    }
10704
10705    private boolean isForwardLocked(PackageSetting ps) {
10706        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10707    }
10708
10709    private static boolean isMultiArch(PackageSetting ps) {
10710        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10711    }
10712
10713    private static boolean isMultiArch(ApplicationInfo info) {
10714        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10715    }
10716
10717    private static boolean isExternal(PackageParser.Package pkg) {
10718        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10719    }
10720
10721    private static boolean isExternal(PackageSetting ps) {
10722        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10723    }
10724
10725    private static boolean isExternal(ApplicationInfo info) {
10726        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10727    }
10728
10729    private static boolean isSystemApp(PackageParser.Package pkg) {
10730        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10731    }
10732
10733    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10734        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10735    }
10736
10737    private static boolean isSystemApp(ApplicationInfo info) {
10738        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10739    }
10740
10741    private static boolean isSystemApp(PackageSetting ps) {
10742        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10743    }
10744
10745    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10746        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10747    }
10748
10749    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10750        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10751    }
10752
10753    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10754        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10755    }
10756
10757    private int packageFlagsToInstallFlags(PackageSetting ps) {
10758        int installFlags = 0;
10759        if (isExternal(ps)) {
10760            installFlags |= PackageManager.INSTALL_EXTERNAL;
10761        }
10762        if (isForwardLocked(ps)) {
10763            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10764        }
10765        return installFlags;
10766    }
10767
10768    private void deleteTempPackageFiles() {
10769        final FilenameFilter filter = new FilenameFilter() {
10770            public boolean accept(File dir, String name) {
10771                return name.startsWith("vmdl") && name.endsWith(".tmp");
10772            }
10773        };
10774        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10775            file.delete();
10776        }
10777    }
10778
10779    @Override
10780    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10781            int flags) {
10782        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10783                flags);
10784    }
10785
10786    @Override
10787    public void deletePackage(final String packageName,
10788            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10789        mContext.enforceCallingOrSelfPermission(
10790                android.Manifest.permission.DELETE_PACKAGES, null);
10791        final int uid = Binder.getCallingUid();
10792        if (UserHandle.getUserId(uid) != userId) {
10793            mContext.enforceCallingPermission(
10794                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10795                    "deletePackage for user " + userId);
10796        }
10797        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10798            try {
10799                observer.onPackageDeleted(packageName,
10800                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10801            } catch (RemoteException re) {
10802            }
10803            return;
10804        }
10805
10806        boolean uninstallBlocked = false;
10807        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10808            int[] users = sUserManager.getUserIds();
10809            for (int i = 0; i < users.length; ++i) {
10810                if (getBlockUninstallForUser(packageName, users[i])) {
10811                    uninstallBlocked = true;
10812                    break;
10813                }
10814            }
10815        } else {
10816            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10817        }
10818        if (uninstallBlocked) {
10819            try {
10820                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10821                        null);
10822            } catch (RemoteException re) {
10823            }
10824            return;
10825        }
10826
10827        if (DEBUG_REMOVE) {
10828            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10829        }
10830        // Queue up an async operation since the package deletion may take a little while.
10831        mHandler.post(new Runnable() {
10832            public void run() {
10833                mHandler.removeCallbacks(this);
10834                final int returnCode = deletePackageX(packageName, userId, flags);
10835                if (observer != null) {
10836                    try {
10837                        observer.onPackageDeleted(packageName, returnCode, null);
10838                    } catch (RemoteException e) {
10839                        Log.i(TAG, "Observer no longer exists.");
10840                    } //end catch
10841                } //end if
10842            } //end run
10843        });
10844    }
10845
10846    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10847        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10848                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10849        try {
10850            if (dpm != null) {
10851                if (dpm.isDeviceOwner(packageName)) {
10852                    return true;
10853                }
10854                int[] users;
10855                if (userId == UserHandle.USER_ALL) {
10856                    users = sUserManager.getUserIds();
10857                } else {
10858                    users = new int[]{userId};
10859                }
10860                for (int i = 0; i < users.length; ++i) {
10861                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10862                        return true;
10863                    }
10864                }
10865            }
10866        } catch (RemoteException e) {
10867        }
10868        return false;
10869    }
10870
10871    /**
10872     *  This method is an internal method that could be get invoked either
10873     *  to delete an installed package or to clean up a failed installation.
10874     *  After deleting an installed package, a broadcast is sent to notify any
10875     *  listeners that the package has been installed. For cleaning up a failed
10876     *  installation, the broadcast is not necessary since the package's
10877     *  installation wouldn't have sent the initial broadcast either
10878     *  The key steps in deleting a package are
10879     *  deleting the package information in internal structures like mPackages,
10880     *  deleting the packages base directories through installd
10881     *  updating mSettings to reflect current status
10882     *  persisting settings for later use
10883     *  sending a broadcast if necessary
10884     */
10885    private int deletePackageX(String packageName, int userId, int flags) {
10886        final PackageRemovedInfo info = new PackageRemovedInfo();
10887        final boolean res;
10888
10889        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10890                ? UserHandle.ALL : new UserHandle(userId);
10891
10892        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10893            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10894            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10895        }
10896
10897        boolean removedForAllUsers = false;
10898        boolean systemUpdate = false;
10899
10900        // for the uninstall-updates case and restricted profiles, remember the per-
10901        // userhandle installed state
10902        int[] allUsers;
10903        boolean[] perUserInstalled;
10904        synchronized (mPackages) {
10905            PackageSetting ps = mSettings.mPackages.get(packageName);
10906            allUsers = sUserManager.getUserIds();
10907            perUserInstalled = new boolean[allUsers.length];
10908            for (int i = 0; i < allUsers.length; i++) {
10909                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10910            }
10911        }
10912
10913        synchronized (mInstallLock) {
10914            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10915            res = deletePackageLI(packageName, removeForUser,
10916                    true, allUsers, perUserInstalled,
10917                    flags | REMOVE_CHATTY, info, true);
10918            systemUpdate = info.isRemovedPackageSystemUpdate;
10919            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10920                removedForAllUsers = true;
10921            }
10922            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10923                    + " removedForAllUsers=" + removedForAllUsers);
10924        }
10925
10926        if (res) {
10927            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10928
10929            // If the removed package was a system update, the old system package
10930            // was re-enabled; we need to broadcast this information
10931            if (systemUpdate) {
10932                Bundle extras = new Bundle(1);
10933                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10934                        ? info.removedAppId : info.uid);
10935                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10936
10937                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10938                        extras, null, null, null);
10939                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10940                        extras, null, null, null);
10941                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10942                        null, packageName, null, null);
10943            }
10944        }
10945        // Force a gc here.
10946        Runtime.getRuntime().gc();
10947        // Delete the resources here after sending the broadcast to let
10948        // other processes clean up before deleting resources.
10949        if (info.args != null) {
10950            synchronized (mInstallLock) {
10951                info.args.doPostDeleteLI(true);
10952            }
10953        }
10954
10955        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10956    }
10957
10958    static class PackageRemovedInfo {
10959        String removedPackage;
10960        int uid = -1;
10961        int removedAppId = -1;
10962        int[] removedUsers = null;
10963        boolean isRemovedPackageSystemUpdate = false;
10964        // Clean up resources deleted packages.
10965        InstallArgs args = null;
10966
10967        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10968            Bundle extras = new Bundle(1);
10969            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10970            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10971            if (replacing) {
10972                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10973            }
10974            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10975            if (removedPackage != null) {
10976                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10977                        extras, null, null, removedUsers);
10978                if (fullRemove && !replacing) {
10979                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10980                            extras, null, null, removedUsers);
10981                }
10982            }
10983            if (removedAppId >= 0) {
10984                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10985                        removedUsers);
10986            }
10987        }
10988    }
10989
10990    /*
10991     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10992     * flag is not set, the data directory is removed as well.
10993     * make sure this flag is set for partially installed apps. If not its meaningless to
10994     * delete a partially installed application.
10995     */
10996    private void removePackageDataLI(PackageSetting ps,
10997            int[] allUserHandles, boolean[] perUserInstalled,
10998            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10999        String packageName = ps.name;
11000        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
11001        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
11002        // Retrieve object to delete permissions for shared user later on
11003        final PackageSetting deletedPs;
11004        // reader
11005        synchronized (mPackages) {
11006            deletedPs = mSettings.mPackages.get(packageName);
11007            if (outInfo != null) {
11008                outInfo.removedPackage = packageName;
11009                outInfo.removedUsers = deletedPs != null
11010                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
11011                        : null;
11012            }
11013        }
11014        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11015            removeDataDirsLI(packageName);
11016            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
11017        }
11018        // writer
11019        synchronized (mPackages) {
11020            if (deletedPs != null) {
11021                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11022                    if (outInfo != null) {
11023                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
11024                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
11025                    }
11026                    if (deletedPs != null) {
11027                        updatePermissionsLPw(deletedPs.name, null, 0);
11028                        if (deletedPs.sharedUser != null) {
11029                            // remove permissions associated with package
11030                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
11031                        }
11032                    }
11033                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
11034                }
11035                // make sure to preserve per-user disabled state if this removal was just
11036                // a downgrade of a system app to the factory package
11037                if (allUserHandles != null && perUserInstalled != null) {
11038                    if (DEBUG_REMOVE) {
11039                        Slog.d(TAG, "Propagating install state across downgrade");
11040                    }
11041                    for (int i = 0; i < allUserHandles.length; i++) {
11042                        if (DEBUG_REMOVE) {
11043                            Slog.d(TAG, "    user " + allUserHandles[i]
11044                                    + " => " + perUserInstalled[i]);
11045                        }
11046                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11047                    }
11048                }
11049            }
11050            // can downgrade to reader
11051            if (writeSettings) {
11052                // Save settings now
11053                mSettings.writeLPr();
11054            }
11055        }
11056        if (outInfo != null) {
11057            // A user ID was deleted here. Go through all users and remove it
11058            // from KeyStore.
11059            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
11060        }
11061    }
11062
11063    static boolean locationIsPrivileged(File path) {
11064        try {
11065            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
11066                    .getCanonicalPath();
11067            return path.getCanonicalPath().startsWith(privilegedAppDir);
11068        } catch (IOException e) {
11069            Slog.e(TAG, "Unable to access code path " + path);
11070        }
11071        return false;
11072    }
11073
11074    /*
11075     * Tries to delete system package.
11076     */
11077    private boolean deleteSystemPackageLI(PackageSetting newPs,
11078            int[] allUserHandles, boolean[] perUserInstalled,
11079            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
11080        final boolean applyUserRestrictions
11081                = (allUserHandles != null) && (perUserInstalled != null);
11082        PackageSetting disabledPs = null;
11083        // Confirm if the system package has been updated
11084        // An updated system app can be deleted. This will also have to restore
11085        // the system pkg from system partition
11086        // reader
11087        synchronized (mPackages) {
11088            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
11089        }
11090        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
11091                + " disabledPs=" + disabledPs);
11092        if (disabledPs == null) {
11093            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
11094            return false;
11095        } else if (DEBUG_REMOVE) {
11096            Slog.d(TAG, "Deleting system pkg from data partition");
11097        }
11098        if (DEBUG_REMOVE) {
11099            if (applyUserRestrictions) {
11100                Slog.d(TAG, "Remembering install states:");
11101                for (int i = 0; i < allUserHandles.length; i++) {
11102                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
11103                }
11104            }
11105        }
11106        // Delete the updated package
11107        outInfo.isRemovedPackageSystemUpdate = true;
11108        if (disabledPs.versionCode < newPs.versionCode) {
11109            // Delete data for downgrades
11110            flags &= ~PackageManager.DELETE_KEEP_DATA;
11111        } else {
11112            // Preserve data by setting flag
11113            flags |= PackageManager.DELETE_KEEP_DATA;
11114        }
11115        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
11116                allUserHandles, perUserInstalled, outInfo, writeSettings);
11117        if (!ret) {
11118            return false;
11119        }
11120        // writer
11121        synchronized (mPackages) {
11122            // Reinstate the old system package
11123            mSettings.enableSystemPackageLPw(newPs.name);
11124            // Remove any native libraries from the upgraded package.
11125            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
11126        }
11127        // Install the system package
11128        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
11129        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
11130        if (locationIsPrivileged(disabledPs.codePath)) {
11131            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11132        }
11133
11134        final PackageParser.Package newPkg;
11135        try {
11136            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
11137        } catch (PackageManagerException e) {
11138            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
11139            return false;
11140        }
11141
11142        // writer
11143        synchronized (mPackages) {
11144            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
11145            updatePermissionsLPw(newPkg.packageName, newPkg,
11146                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
11147            if (applyUserRestrictions) {
11148                if (DEBUG_REMOVE) {
11149                    Slog.d(TAG, "Propagating install state across reinstall");
11150                }
11151                for (int i = 0; i < allUserHandles.length; i++) {
11152                    if (DEBUG_REMOVE) {
11153                        Slog.d(TAG, "    user " + allUserHandles[i]
11154                                + " => " + perUserInstalled[i]);
11155                    }
11156                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11157                }
11158                // Regardless of writeSettings we need to ensure that this restriction
11159                // state propagation is persisted
11160                mSettings.writeAllUsersPackageRestrictionsLPr();
11161            }
11162            // can downgrade to reader here
11163            if (writeSettings) {
11164                mSettings.writeLPr();
11165            }
11166        }
11167        return true;
11168    }
11169
11170    private boolean deleteInstalledPackageLI(PackageSetting ps,
11171            boolean deleteCodeAndResources, int flags,
11172            int[] allUserHandles, boolean[] perUserInstalled,
11173            PackageRemovedInfo outInfo, boolean writeSettings) {
11174        if (outInfo != null) {
11175            outInfo.uid = ps.appId;
11176        }
11177
11178        // Delete package data from internal structures and also remove data if flag is set
11179        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
11180
11181        // Delete application code and resources
11182        if (deleteCodeAndResources && (outInfo != null)) {
11183            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
11184                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
11185                    getAppDexInstructionSets(ps));
11186            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
11187        }
11188        return true;
11189    }
11190
11191    @Override
11192    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11193            int userId) {
11194        mContext.enforceCallingOrSelfPermission(
11195                android.Manifest.permission.DELETE_PACKAGES, null);
11196        synchronized (mPackages) {
11197            PackageSetting ps = mSettings.mPackages.get(packageName);
11198            if (ps == null) {
11199                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11200                return false;
11201            }
11202            if (!ps.getInstalled(userId)) {
11203                // Can't block uninstall for an app that is not installed or enabled.
11204                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11205                return false;
11206            }
11207            ps.setBlockUninstall(blockUninstall, userId);
11208            mSettings.writePackageRestrictionsLPr(userId);
11209        }
11210        return true;
11211    }
11212
11213    @Override
11214    public boolean getBlockUninstallForUser(String packageName, int userId) {
11215        synchronized (mPackages) {
11216            PackageSetting ps = mSettings.mPackages.get(packageName);
11217            if (ps == null) {
11218                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11219                return false;
11220            }
11221            return ps.getBlockUninstall(userId);
11222        }
11223    }
11224
11225    /*
11226     * This method handles package deletion in general
11227     */
11228    private boolean deletePackageLI(String packageName, UserHandle user,
11229            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11230            int flags, PackageRemovedInfo outInfo,
11231            boolean writeSettings) {
11232        if (packageName == null) {
11233            Slog.w(TAG, "Attempt to delete null packageName.");
11234            return false;
11235        }
11236        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11237        PackageSetting ps;
11238        boolean dataOnly = false;
11239        int removeUser = -1;
11240        int appId = -1;
11241        synchronized (mPackages) {
11242            ps = mSettings.mPackages.get(packageName);
11243            if (ps == null) {
11244                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11245                return false;
11246            }
11247            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11248                    && user.getIdentifier() != UserHandle.USER_ALL) {
11249                // The caller is asking that the package only be deleted for a single
11250                // user.  To do this, we just mark its uninstalled state and delete
11251                // its data.  If this is a system app, we only allow this to happen if
11252                // they have set the special DELETE_SYSTEM_APP which requests different
11253                // semantics than normal for uninstalling system apps.
11254                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11255                ps.setUserState(user.getIdentifier(),
11256                        COMPONENT_ENABLED_STATE_DEFAULT,
11257                        false, //installed
11258                        true,  //stopped
11259                        true,  //notLaunched
11260                        false, //hidden
11261                        null, null, null,
11262                        false // blockUninstall
11263                        );
11264                if (!isSystemApp(ps)) {
11265                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11266                        // Other user still have this package installed, so all
11267                        // we need to do is clear this user's data and save that
11268                        // it is uninstalled.
11269                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11270                        removeUser = user.getIdentifier();
11271                        appId = ps.appId;
11272                        mSettings.writePackageRestrictionsLPr(removeUser);
11273                    } else {
11274                        // We need to set it back to 'installed' so the uninstall
11275                        // broadcasts will be sent correctly.
11276                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11277                        ps.setInstalled(true, user.getIdentifier());
11278                    }
11279                } else {
11280                    // This is a system app, so we assume that the
11281                    // other users still have this package installed, so all
11282                    // we need to do is clear this user's data and save that
11283                    // it is uninstalled.
11284                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11285                    removeUser = user.getIdentifier();
11286                    appId = ps.appId;
11287                    mSettings.writePackageRestrictionsLPr(removeUser);
11288                }
11289            }
11290        }
11291
11292        if (removeUser >= 0) {
11293            // From above, we determined that we are deleting this only
11294            // for a single user.  Continue the work here.
11295            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11296            if (outInfo != null) {
11297                outInfo.removedPackage = packageName;
11298                outInfo.removedAppId = appId;
11299                outInfo.removedUsers = new int[] {removeUser};
11300            }
11301            mInstaller.clearUserData(packageName, removeUser);
11302            removeKeystoreDataIfNeeded(removeUser, appId);
11303            schedulePackageCleaning(packageName, removeUser, false);
11304            return true;
11305        }
11306
11307        if (dataOnly) {
11308            // Delete application data first
11309            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11310            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11311            return true;
11312        }
11313
11314        boolean ret = false;
11315        if (isSystemApp(ps)) {
11316            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11317            // When an updated system application is deleted we delete the existing resources as well and
11318            // fall back to existing code in system partition
11319            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11320                    flags, outInfo, writeSettings);
11321        } else {
11322            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11323            // Kill application pre-emptively especially for apps on sd.
11324            killApplication(packageName, ps.appId, "uninstall pkg");
11325            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11326                    allUserHandles, perUserInstalled,
11327                    outInfo, writeSettings);
11328        }
11329
11330        return ret;
11331    }
11332
11333    private final class ClearStorageConnection implements ServiceConnection {
11334        IMediaContainerService mContainerService;
11335
11336        @Override
11337        public void onServiceConnected(ComponentName name, IBinder service) {
11338            synchronized (this) {
11339                mContainerService = IMediaContainerService.Stub.asInterface(service);
11340                notifyAll();
11341            }
11342        }
11343
11344        @Override
11345        public void onServiceDisconnected(ComponentName name) {
11346        }
11347    }
11348
11349    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11350        final boolean mounted;
11351        if (Environment.isExternalStorageEmulated()) {
11352            mounted = true;
11353        } else {
11354            final String status = Environment.getExternalStorageState();
11355
11356            mounted = status.equals(Environment.MEDIA_MOUNTED)
11357                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11358        }
11359
11360        if (!mounted) {
11361            return;
11362        }
11363
11364        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11365        int[] users;
11366        if (userId == UserHandle.USER_ALL) {
11367            users = sUserManager.getUserIds();
11368        } else {
11369            users = new int[] { userId };
11370        }
11371        final ClearStorageConnection conn = new ClearStorageConnection();
11372        if (mContext.bindServiceAsUser(
11373                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11374            try {
11375                for (int curUser : users) {
11376                    long timeout = SystemClock.uptimeMillis() + 5000;
11377                    synchronized (conn) {
11378                        long now = SystemClock.uptimeMillis();
11379                        while (conn.mContainerService == null && now < timeout) {
11380                            try {
11381                                conn.wait(timeout - now);
11382                            } catch (InterruptedException e) {
11383                            }
11384                        }
11385                    }
11386                    if (conn.mContainerService == null) {
11387                        return;
11388                    }
11389
11390                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11391                    clearDirectory(conn.mContainerService,
11392                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11393                    if (allData) {
11394                        clearDirectory(conn.mContainerService,
11395                                userEnv.buildExternalStorageAppDataDirs(packageName));
11396                        clearDirectory(conn.mContainerService,
11397                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11398                    }
11399                }
11400            } finally {
11401                mContext.unbindService(conn);
11402            }
11403        }
11404    }
11405
11406    @Override
11407    public void clearApplicationUserData(final String packageName,
11408            final IPackageDataObserver observer, final int userId) {
11409        mContext.enforceCallingOrSelfPermission(
11410                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11411        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11412        // Queue up an async operation since the package deletion may take a little while.
11413        mHandler.post(new Runnable() {
11414            public void run() {
11415                mHandler.removeCallbacks(this);
11416                final boolean succeeded;
11417                synchronized (mInstallLock) {
11418                    succeeded = clearApplicationUserDataLI(packageName, userId);
11419                }
11420                clearExternalStorageDataSync(packageName, userId, true);
11421                if (succeeded) {
11422                    // invoke DeviceStorageMonitor's update method to clear any notifications
11423                    DeviceStorageMonitorInternal
11424                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11425                    if (dsm != null) {
11426                        dsm.checkMemory();
11427                    }
11428                }
11429                if(observer != null) {
11430                    try {
11431                        observer.onRemoveCompleted(packageName, succeeded);
11432                    } catch (RemoteException e) {
11433                        Log.i(TAG, "Observer no longer exists.");
11434                    }
11435                } //end if observer
11436            } //end run
11437        });
11438    }
11439
11440    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11441        if (packageName == null) {
11442            Slog.w(TAG, "Attempt to delete null packageName.");
11443            return false;
11444        }
11445
11446        // Try finding details about the requested package
11447        PackageParser.Package pkg;
11448        synchronized (mPackages) {
11449            pkg = mPackages.get(packageName);
11450            if (pkg == null) {
11451                final PackageSetting ps = mSettings.mPackages.get(packageName);
11452                if (ps != null) {
11453                    pkg = ps.pkg;
11454                }
11455            }
11456        }
11457
11458        if (pkg == null) {
11459            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11460        }
11461
11462        // Always delete data directories for package, even if we found no other
11463        // record of app. This helps users recover from UID mismatches without
11464        // resorting to a full data wipe.
11465        int retCode = mInstaller.clearUserData(packageName, userId);
11466        if (retCode < 0) {
11467            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11468            return false;
11469        }
11470
11471        if (pkg == null) {
11472            return false;
11473        }
11474
11475        if (pkg != null && pkg.applicationInfo != null) {
11476            final int appId = pkg.applicationInfo.uid;
11477            removeKeystoreDataIfNeeded(userId, appId);
11478        }
11479
11480        // Create a native library symlink only if we have native libraries
11481        // and if the native libraries are 32 bit libraries. We do not provide
11482        // this symlink for 64 bit libraries.
11483        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11484                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11485            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11486            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11487                Slog.w(TAG, "Failed linking native library dir");
11488                return false;
11489            }
11490        }
11491
11492        return true;
11493    }
11494
11495    /**
11496     * Remove entries from the keystore daemon. Will only remove it if the
11497     * {@code appId} is valid.
11498     */
11499    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11500        if (appId < 0) {
11501            return;
11502        }
11503
11504        final KeyStore keyStore = KeyStore.getInstance();
11505        if (keyStore != null) {
11506            if (userId == UserHandle.USER_ALL) {
11507                for (final int individual : sUserManager.getUserIds()) {
11508                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11509                }
11510            } else {
11511                keyStore.clearUid(UserHandle.getUid(userId, appId));
11512            }
11513        } else {
11514            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11515        }
11516    }
11517
11518    @Override
11519    public void deleteApplicationCacheFiles(final String packageName,
11520            final IPackageDataObserver observer) {
11521        mContext.enforceCallingOrSelfPermission(
11522                android.Manifest.permission.DELETE_CACHE_FILES, null);
11523        // Queue up an async operation since the package deletion may take a little while.
11524        final int userId = UserHandle.getCallingUserId();
11525        mHandler.post(new Runnable() {
11526            public void run() {
11527                mHandler.removeCallbacks(this);
11528                final boolean succeded;
11529                synchronized (mInstallLock) {
11530                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11531                }
11532                clearExternalStorageDataSync(packageName, userId, false);
11533                if(observer != null) {
11534                    try {
11535                        observer.onRemoveCompleted(packageName, succeded);
11536                    } catch (RemoteException e) {
11537                        Log.i(TAG, "Observer no longer exists.");
11538                    }
11539                } //end if observer
11540            } //end run
11541        });
11542    }
11543
11544    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11545        if (packageName == null) {
11546            Slog.w(TAG, "Attempt to delete null packageName.");
11547            return false;
11548        }
11549        PackageParser.Package p;
11550        synchronized (mPackages) {
11551            p = mPackages.get(packageName);
11552        }
11553        if (p == null) {
11554            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11555            return false;
11556        }
11557        final ApplicationInfo applicationInfo = p.applicationInfo;
11558        if (applicationInfo == null) {
11559            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11560            return false;
11561        }
11562        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11563        if (retCode < 0) {
11564            Slog.w(TAG, "Couldn't remove cache files for package: "
11565                       + packageName + " u" + userId);
11566            return false;
11567        }
11568        return true;
11569    }
11570
11571    @Override
11572    public void getPackageSizeInfo(final String packageName, int userHandle,
11573            final IPackageStatsObserver observer) {
11574        mContext.enforceCallingOrSelfPermission(
11575                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11576        if (packageName == null) {
11577            throw new IllegalArgumentException("Attempt to get size of null packageName");
11578        }
11579
11580        PackageStats stats = new PackageStats(packageName, userHandle);
11581
11582        /*
11583         * Queue up an async operation since the package measurement may take a
11584         * little while.
11585         */
11586        Message msg = mHandler.obtainMessage(INIT_COPY);
11587        msg.obj = new MeasureParams(stats, observer);
11588        mHandler.sendMessage(msg);
11589    }
11590
11591    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11592            PackageStats pStats) {
11593        if (packageName == null) {
11594            Slog.w(TAG, "Attempt to get size of null packageName.");
11595            return false;
11596        }
11597        PackageParser.Package p;
11598        boolean dataOnly = false;
11599        String libDirRoot = null;
11600        String asecPath = null;
11601        PackageSetting ps = null;
11602        synchronized (mPackages) {
11603            p = mPackages.get(packageName);
11604            ps = mSettings.mPackages.get(packageName);
11605            if(p == null) {
11606                dataOnly = true;
11607                if((ps == null) || (ps.pkg == null)) {
11608                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11609                    return false;
11610                }
11611                p = ps.pkg;
11612            }
11613            if (ps != null) {
11614                libDirRoot = ps.legacyNativeLibraryPathString;
11615            }
11616            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11617                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11618                if (secureContainerId != null) {
11619                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11620                }
11621            }
11622        }
11623        String publicSrcDir = null;
11624        if(!dataOnly) {
11625            final ApplicationInfo applicationInfo = p.applicationInfo;
11626            if (applicationInfo == null) {
11627                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11628                return false;
11629            }
11630            if (isForwardLocked(p)) {
11631                publicSrcDir = applicationInfo.getBaseResourcePath();
11632            }
11633        }
11634        // TODO: extend to measure size of split APKs
11635        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11636        // not just the first level.
11637        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11638        // just the primary.
11639        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11640        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11641                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11642        if (res < 0) {
11643            return false;
11644        }
11645
11646        // Fix-up for forward-locked applications in ASEC containers.
11647        if (!isExternal(p)) {
11648            pStats.codeSize += pStats.externalCodeSize;
11649            pStats.externalCodeSize = 0L;
11650        }
11651
11652        return true;
11653    }
11654
11655
11656    @Override
11657    public void addPackageToPreferred(String packageName) {
11658        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11659    }
11660
11661    @Override
11662    public void removePackageFromPreferred(String packageName) {
11663        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11664    }
11665
11666    @Override
11667    public List<PackageInfo> getPreferredPackages(int flags) {
11668        return new ArrayList<PackageInfo>();
11669    }
11670
11671    private int getUidTargetSdkVersionLockedLPr(int uid) {
11672        Object obj = mSettings.getUserIdLPr(uid);
11673        if (obj instanceof SharedUserSetting) {
11674            final SharedUserSetting sus = (SharedUserSetting) obj;
11675            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11676            final Iterator<PackageSetting> it = sus.packages.iterator();
11677            while (it.hasNext()) {
11678                final PackageSetting ps = it.next();
11679                if (ps.pkg != null) {
11680                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11681                    if (v < vers) vers = v;
11682                }
11683            }
11684            return vers;
11685        } else if (obj instanceof PackageSetting) {
11686            final PackageSetting ps = (PackageSetting) obj;
11687            if (ps.pkg != null) {
11688                return ps.pkg.applicationInfo.targetSdkVersion;
11689            }
11690        }
11691        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11692    }
11693
11694    @Override
11695    public void addPreferredActivity(IntentFilter filter, int match,
11696            ComponentName[] set, ComponentName activity, int userId) {
11697        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11698                "Adding preferred");
11699    }
11700
11701    private void addPreferredActivityInternal(IntentFilter filter, int match,
11702            ComponentName[] set, ComponentName activity, boolean always, int userId,
11703            String opname) {
11704        // writer
11705        int callingUid = Binder.getCallingUid();
11706        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11707        if (filter.countActions() == 0) {
11708            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11709            return;
11710        }
11711        synchronized (mPackages) {
11712            if (mContext.checkCallingOrSelfPermission(
11713                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11714                    != PackageManager.PERMISSION_GRANTED) {
11715                if (getUidTargetSdkVersionLockedLPr(callingUid)
11716                        < Build.VERSION_CODES.FROYO) {
11717                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11718                            + callingUid);
11719                    return;
11720                }
11721                mContext.enforceCallingOrSelfPermission(
11722                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11723            }
11724
11725            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11726            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11727                    + userId + ":");
11728            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11729            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11730            scheduleWritePackageRestrictionsLocked(userId);
11731        }
11732    }
11733
11734    @Override
11735    public void replacePreferredActivity(IntentFilter filter, int match,
11736            ComponentName[] set, ComponentName activity, int userId) {
11737        if (filter.countActions() != 1) {
11738            throw new IllegalArgumentException(
11739                    "replacePreferredActivity expects filter to have only 1 action.");
11740        }
11741        if (filter.countDataAuthorities() != 0
11742                || filter.countDataPaths() != 0
11743                || filter.countDataSchemes() > 1
11744                || filter.countDataTypes() != 0) {
11745            throw new IllegalArgumentException(
11746                    "replacePreferredActivity expects filter to have no data authorities, " +
11747                    "paths, or types; and at most one scheme.");
11748        }
11749
11750        final int callingUid = Binder.getCallingUid();
11751        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11752        synchronized (mPackages) {
11753            if (mContext.checkCallingOrSelfPermission(
11754                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11755                    != PackageManager.PERMISSION_GRANTED) {
11756                if (getUidTargetSdkVersionLockedLPr(callingUid)
11757                        < Build.VERSION_CODES.FROYO) {
11758                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11759                            + Binder.getCallingUid());
11760                    return;
11761                }
11762                mContext.enforceCallingOrSelfPermission(
11763                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11764            }
11765
11766            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11767            if (pir != null) {
11768                // Get all of the existing entries that exactly match this filter.
11769                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11770                if (existing != null && existing.size() == 1) {
11771                    PreferredActivity cur = existing.get(0);
11772                    if (DEBUG_PREFERRED) {
11773                        Slog.i(TAG, "Checking replace of preferred:");
11774                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11775                        if (!cur.mPref.mAlways) {
11776                            Slog.i(TAG, "  -- CUR; not mAlways!");
11777                        } else {
11778                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11779                            Slog.i(TAG, "  -- CUR: mSet="
11780                                    + Arrays.toString(cur.mPref.mSetComponents));
11781                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11782                            Slog.i(TAG, "  -- NEW: mMatch="
11783                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11784                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11785                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11786                        }
11787                    }
11788                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11789                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11790                            && cur.mPref.sameSet(set)) {
11791                        // Setting the preferred activity to what it happens to be already
11792                        if (DEBUG_PREFERRED) {
11793                            Slog.i(TAG, "Replacing with same preferred activity "
11794                                    + cur.mPref.mShortComponent + " for user "
11795                                    + userId + ":");
11796                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11797                        }
11798                        return;
11799                    }
11800                }
11801
11802                if (existing != null) {
11803                    if (DEBUG_PREFERRED) {
11804                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11805                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11806                    }
11807                    for (int i = 0; i < existing.size(); i++) {
11808                        PreferredActivity pa = existing.get(i);
11809                        if (DEBUG_PREFERRED) {
11810                            Slog.i(TAG, "Removing existing preferred activity "
11811                                    + pa.mPref.mComponent + ":");
11812                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11813                        }
11814                        pir.removeFilter(pa);
11815                    }
11816                }
11817            }
11818            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11819                    "Replacing preferred");
11820        }
11821    }
11822
11823    @Override
11824    public void clearPackagePreferredActivities(String packageName) {
11825        final int uid = Binder.getCallingUid();
11826        // writer
11827        synchronized (mPackages) {
11828            PackageParser.Package pkg = mPackages.get(packageName);
11829            if (pkg == null || pkg.applicationInfo.uid != uid) {
11830                if (mContext.checkCallingOrSelfPermission(
11831                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11832                        != PackageManager.PERMISSION_GRANTED) {
11833                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11834                            < Build.VERSION_CODES.FROYO) {
11835                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11836                                + Binder.getCallingUid());
11837                        return;
11838                    }
11839                    mContext.enforceCallingOrSelfPermission(
11840                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11841                }
11842            }
11843
11844            int user = UserHandle.getCallingUserId();
11845            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11846                scheduleWritePackageRestrictionsLocked(user);
11847            }
11848        }
11849    }
11850
11851    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11852    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11853        ArrayList<PreferredActivity> removed = null;
11854        boolean changed = false;
11855        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11856            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11857            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11858            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11859                continue;
11860            }
11861            Iterator<PreferredActivity> it = pir.filterIterator();
11862            while (it.hasNext()) {
11863                PreferredActivity pa = it.next();
11864                // Mark entry for removal only if it matches the package name
11865                // and the entry is of type "always".
11866                if (packageName == null ||
11867                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11868                                && pa.mPref.mAlways)) {
11869                    if (removed == null) {
11870                        removed = new ArrayList<PreferredActivity>();
11871                    }
11872                    removed.add(pa);
11873                }
11874            }
11875            if (removed != null) {
11876                for (int j=0; j<removed.size(); j++) {
11877                    PreferredActivity pa = removed.get(j);
11878                    pir.removeFilter(pa);
11879                }
11880                changed = true;
11881            }
11882        }
11883        return changed;
11884    }
11885
11886    @Override
11887    public void resetPreferredActivities(int userId) {
11888        /* TODO: Actually use userId. Why is it being passed in? */
11889        mContext.enforceCallingOrSelfPermission(
11890                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11891        // writer
11892        synchronized (mPackages) {
11893            int user = UserHandle.getCallingUserId();
11894            clearPackagePreferredActivitiesLPw(null, user);
11895            mSettings.readDefaultPreferredAppsLPw(this, user);
11896            scheduleWritePackageRestrictionsLocked(user);
11897        }
11898    }
11899
11900    @Override
11901    public int getPreferredActivities(List<IntentFilter> outFilters,
11902            List<ComponentName> outActivities, String packageName) {
11903
11904        int num = 0;
11905        final int userId = UserHandle.getCallingUserId();
11906        // reader
11907        synchronized (mPackages) {
11908            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11909            if (pir != null) {
11910                final Iterator<PreferredActivity> it = pir.filterIterator();
11911                while (it.hasNext()) {
11912                    final PreferredActivity pa = it.next();
11913                    if (packageName == null
11914                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11915                                    && pa.mPref.mAlways)) {
11916                        if (outFilters != null) {
11917                            outFilters.add(new IntentFilter(pa));
11918                        }
11919                        if (outActivities != null) {
11920                            outActivities.add(pa.mPref.mComponent);
11921                        }
11922                    }
11923                }
11924            }
11925        }
11926
11927        return num;
11928    }
11929
11930    @Override
11931    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11932            int userId) {
11933        int callingUid = Binder.getCallingUid();
11934        if (callingUid != Process.SYSTEM_UID) {
11935            throw new SecurityException(
11936                    "addPersistentPreferredActivity can only be run by the system");
11937        }
11938        if (filter.countActions() == 0) {
11939            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11940            return;
11941        }
11942        synchronized (mPackages) {
11943            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11944                    " :");
11945            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11946            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11947                    new PersistentPreferredActivity(filter, activity));
11948            scheduleWritePackageRestrictionsLocked(userId);
11949        }
11950    }
11951
11952    @Override
11953    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11954        int callingUid = Binder.getCallingUid();
11955        if (callingUid != Process.SYSTEM_UID) {
11956            throw new SecurityException(
11957                    "clearPackagePersistentPreferredActivities can only be run by the system");
11958        }
11959        ArrayList<PersistentPreferredActivity> removed = null;
11960        boolean changed = false;
11961        synchronized (mPackages) {
11962            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11963                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11964                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11965                        .valueAt(i);
11966                if (userId != thisUserId) {
11967                    continue;
11968                }
11969                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11970                while (it.hasNext()) {
11971                    PersistentPreferredActivity ppa = it.next();
11972                    // Mark entry for removal only if it matches the package name.
11973                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11974                        if (removed == null) {
11975                            removed = new ArrayList<PersistentPreferredActivity>();
11976                        }
11977                        removed.add(ppa);
11978                    }
11979                }
11980                if (removed != null) {
11981                    for (int j=0; j<removed.size(); j++) {
11982                        PersistentPreferredActivity ppa = removed.get(j);
11983                        ppir.removeFilter(ppa);
11984                    }
11985                    changed = true;
11986                }
11987            }
11988
11989            if (changed) {
11990                scheduleWritePackageRestrictionsLocked(userId);
11991            }
11992        }
11993    }
11994
11995    @Override
11996    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11997            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11998        mContext.enforceCallingOrSelfPermission(
11999                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12000        int callingUid = Binder.getCallingUid();
12001        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
12002        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12003        if (intentFilter.countActions() == 0) {
12004            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
12005            return;
12006        }
12007        synchronized (mPackages) {
12008            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
12009                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
12010            CrossProfileIntentResolver resolver =
12011                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12012            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
12013            // We have all those whose filter is equal. Now checking if the rest is equal as well.
12014            if (existing != null) {
12015                int size = existing.size();
12016                for (int i = 0; i < size; i++) {
12017                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
12018                        return;
12019                    }
12020                }
12021            }
12022            resolver.addFilter(newFilter);
12023            scheduleWritePackageRestrictionsLocked(sourceUserId);
12024        }
12025    }
12026
12027    @Override
12028    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
12029            int ownerUserId) {
12030        mContext.enforceCallingOrSelfPermission(
12031                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12032        int callingUid = Binder.getCallingUid();
12033        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
12034        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12035        int callingUserId = UserHandle.getUserId(callingUid);
12036        synchronized (mPackages) {
12037            CrossProfileIntentResolver resolver =
12038                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12039            ArraySet<CrossProfileIntentFilter> set =
12040                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
12041            for (CrossProfileIntentFilter filter : set) {
12042                if (filter.getOwnerPackage().equals(ownerPackage)
12043                        && filter.getOwnerUserId() == callingUserId) {
12044                    resolver.removeFilter(filter);
12045                }
12046            }
12047            scheduleWritePackageRestrictionsLocked(sourceUserId);
12048        }
12049    }
12050
12051    // Enforcing that callingUid is owning pkg on userId
12052    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
12053        // The system owns everything.
12054        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
12055            return;
12056        }
12057        int callingUserId = UserHandle.getUserId(callingUid);
12058        if (callingUserId != userId) {
12059            throw new SecurityException("calling uid " + callingUid
12060                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
12061                    + callingUserId);
12062        }
12063        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
12064        if (pi == null) {
12065            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
12066                    + callingUserId);
12067        }
12068        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
12069            throw new SecurityException("Calling uid " + callingUid
12070                    + " does not own package " + pkg);
12071        }
12072    }
12073
12074    @Override
12075    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
12076        Intent intent = new Intent(Intent.ACTION_MAIN);
12077        intent.addCategory(Intent.CATEGORY_HOME);
12078
12079        final int callingUserId = UserHandle.getCallingUserId();
12080        List<ResolveInfo> list = queryIntentActivities(intent, null,
12081                PackageManager.GET_META_DATA, callingUserId);
12082        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
12083                true, false, false, callingUserId);
12084
12085        allHomeCandidates.clear();
12086        if (list != null) {
12087            for (ResolveInfo ri : list) {
12088                allHomeCandidates.add(ri);
12089            }
12090        }
12091        return (preferred == null || preferred.activityInfo == null)
12092                ? null
12093                : new ComponentName(preferred.activityInfo.packageName,
12094                        preferred.activityInfo.name);
12095    }
12096
12097    @Override
12098    public void setApplicationEnabledSetting(String appPackageName,
12099            int newState, int flags, int userId, String callingPackage) {
12100        if (!sUserManager.exists(userId)) return;
12101        if (callingPackage == null) {
12102            callingPackage = Integer.toString(Binder.getCallingUid());
12103        }
12104        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
12105    }
12106
12107    @Override
12108    public void setComponentEnabledSetting(ComponentName componentName,
12109            int newState, int flags, int userId) {
12110        if (!sUserManager.exists(userId)) return;
12111        setEnabledSetting(componentName.getPackageName(),
12112                componentName.getClassName(), newState, flags, userId, null);
12113    }
12114
12115    private void setEnabledSetting(final String packageName, String className, int newState,
12116            final int flags, int userId, String callingPackage) {
12117        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
12118              || newState == COMPONENT_ENABLED_STATE_ENABLED
12119              || newState == COMPONENT_ENABLED_STATE_DISABLED
12120              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
12121              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
12122            throw new IllegalArgumentException("Invalid new component state: "
12123                    + newState);
12124        }
12125        PackageSetting pkgSetting;
12126        final int uid = Binder.getCallingUid();
12127        final int permission = mContext.checkCallingOrSelfPermission(
12128                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12129        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
12130        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12131        boolean sendNow = false;
12132        boolean isApp = (className == null);
12133        String componentName = isApp ? packageName : className;
12134        int packageUid = -1;
12135        ArrayList<String> components;
12136
12137        // writer
12138        synchronized (mPackages) {
12139            pkgSetting = mSettings.mPackages.get(packageName);
12140            if (pkgSetting == null) {
12141                if (className == null) {
12142                    throw new IllegalArgumentException(
12143                            "Unknown package: " + packageName);
12144                }
12145                throw new IllegalArgumentException(
12146                        "Unknown component: " + packageName
12147                        + "/" + className);
12148            }
12149            // Allow root and verify that userId is not being specified by a different user
12150            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
12151                throw new SecurityException(
12152                        "Permission Denial: attempt to change component state from pid="
12153                        + Binder.getCallingPid()
12154                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
12155            }
12156            if (className == null) {
12157                // We're dealing with an application/package level state change
12158                if (pkgSetting.getEnabled(userId) == newState) {
12159                    // Nothing to do
12160                    return;
12161                }
12162                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
12163                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
12164                    // Don't care about who enables an app.
12165                    callingPackage = null;
12166                }
12167                pkgSetting.setEnabled(newState, userId, callingPackage);
12168                // pkgSetting.pkg.mSetEnabled = newState;
12169            } else {
12170                // We're dealing with a component level state change
12171                // First, verify that this is a valid class name.
12172                PackageParser.Package pkg = pkgSetting.pkg;
12173                if (pkg == null || !pkg.hasComponentClassName(className)) {
12174                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
12175                        throw new IllegalArgumentException("Component class " + className
12176                                + " does not exist in " + packageName);
12177                    } else {
12178                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
12179                                + className + " does not exist in " + packageName);
12180                    }
12181                }
12182                switch (newState) {
12183                case COMPONENT_ENABLED_STATE_ENABLED:
12184                    if (!pkgSetting.enableComponentLPw(className, userId)) {
12185                        return;
12186                    }
12187                    break;
12188                case COMPONENT_ENABLED_STATE_DISABLED:
12189                    if (!pkgSetting.disableComponentLPw(className, userId)) {
12190                        return;
12191                    }
12192                    break;
12193                case COMPONENT_ENABLED_STATE_DEFAULT:
12194                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
12195                        return;
12196                    }
12197                    break;
12198                default:
12199                    Slog.e(TAG, "Invalid new component state: " + newState);
12200                    return;
12201                }
12202            }
12203            mSettings.writePackageRestrictionsLPr(userId);
12204            components = mPendingBroadcasts.get(userId, packageName);
12205            final boolean newPackage = components == null;
12206            if (newPackage) {
12207                components = new ArrayList<String>();
12208            }
12209            if (!components.contains(componentName)) {
12210                components.add(componentName);
12211            }
12212            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12213                sendNow = true;
12214                // Purge entry from pending broadcast list if another one exists already
12215                // since we are sending one right away.
12216                mPendingBroadcasts.remove(userId, packageName);
12217            } else {
12218                if (newPackage) {
12219                    mPendingBroadcasts.put(userId, packageName, components);
12220                }
12221                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12222                    // Schedule a message
12223                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12224                }
12225            }
12226        }
12227
12228        long callingId = Binder.clearCallingIdentity();
12229        try {
12230            if (sendNow) {
12231                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12232                sendPackageChangedBroadcast(packageName,
12233                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12234            }
12235        } finally {
12236            Binder.restoreCallingIdentity(callingId);
12237        }
12238    }
12239
12240    private void sendPackageChangedBroadcast(String packageName,
12241            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12242        if (DEBUG_INSTALL)
12243            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12244                    + componentNames);
12245        Bundle extras = new Bundle(4);
12246        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12247        String nameList[] = new String[componentNames.size()];
12248        componentNames.toArray(nameList);
12249        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12250        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12251        extras.putInt(Intent.EXTRA_UID, packageUid);
12252        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12253                new int[] {UserHandle.getUserId(packageUid)});
12254    }
12255
12256    @Override
12257    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12258        if (!sUserManager.exists(userId)) return;
12259        final int uid = Binder.getCallingUid();
12260        final int permission = mContext.checkCallingOrSelfPermission(
12261                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12262        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12263        enforceCrossUserPermission(uid, userId, true, true, "stop package");
12264        // writer
12265        synchronized (mPackages) {
12266            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12267                    uid, userId)) {
12268                scheduleWritePackageRestrictionsLocked(userId);
12269            }
12270        }
12271    }
12272
12273    @Override
12274    public String getInstallerPackageName(String packageName) {
12275        // reader
12276        synchronized (mPackages) {
12277            return mSettings.getInstallerPackageNameLPr(packageName);
12278        }
12279    }
12280
12281    @Override
12282    public int getApplicationEnabledSetting(String packageName, int userId) {
12283        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12284        int uid = Binder.getCallingUid();
12285        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
12286        // reader
12287        synchronized (mPackages) {
12288            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12289        }
12290    }
12291
12292    @Override
12293    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12294        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12295        int uid = Binder.getCallingUid();
12296        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
12297        // reader
12298        synchronized (mPackages) {
12299            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12300        }
12301    }
12302
12303    @Override
12304    public void enterSafeMode() {
12305        enforceSystemOrRoot("Only the system can request entering safe mode");
12306
12307        if (!mSystemReady) {
12308            mSafeMode = true;
12309        }
12310    }
12311
12312    @Override
12313    public void systemReady() {
12314        mSystemReady = true;
12315
12316        // Read the compatibilty setting when the system is ready.
12317        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12318                mContext.getContentResolver(),
12319                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12320        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12321        if (DEBUG_SETTINGS) {
12322            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12323        }
12324
12325        synchronized (mPackages) {
12326            // Verify that all of the preferred activity components actually
12327            // exist.  It is possible for applications to be updated and at
12328            // that point remove a previously declared activity component that
12329            // had been set as a preferred activity.  We try to clean this up
12330            // the next time we encounter that preferred activity, but it is
12331            // possible for the user flow to never be able to return to that
12332            // situation so here we do a sanity check to make sure we haven't
12333            // left any junk around.
12334            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12335            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12336                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12337                removed.clear();
12338                for (PreferredActivity pa : pir.filterSet()) {
12339                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12340                        removed.add(pa);
12341                    }
12342                }
12343                if (removed.size() > 0) {
12344                    for (int r=0; r<removed.size(); r++) {
12345                        PreferredActivity pa = removed.get(r);
12346                        Slog.w(TAG, "Removing dangling preferred activity: "
12347                                + pa.mPref.mComponent);
12348                        pir.removeFilter(pa);
12349                    }
12350                    mSettings.writePackageRestrictionsLPr(
12351                            mSettings.mPreferredActivities.keyAt(i));
12352                }
12353            }
12354        }
12355        sUserManager.systemReady();
12356
12357        // Kick off any messages waiting for system ready
12358        if (mPostSystemReadyMessages != null) {
12359            for (Message msg : mPostSystemReadyMessages) {
12360                msg.sendToTarget();
12361            }
12362            mPostSystemReadyMessages = null;
12363        }
12364    }
12365
12366    @Override
12367    public boolean isSafeMode() {
12368        return mSafeMode;
12369    }
12370
12371    @Override
12372    public boolean hasSystemUidErrors() {
12373        return mHasSystemUidErrors;
12374    }
12375
12376    static String arrayToString(int[] array) {
12377        StringBuffer buf = new StringBuffer(128);
12378        buf.append('[');
12379        if (array != null) {
12380            for (int i=0; i<array.length; i++) {
12381                if (i > 0) buf.append(", ");
12382                buf.append(array[i]);
12383            }
12384        }
12385        buf.append(']');
12386        return buf.toString();
12387    }
12388
12389    static class DumpState {
12390        public static final int DUMP_LIBS = 1 << 0;
12391        public static final int DUMP_FEATURES = 1 << 1;
12392        public static final int DUMP_RESOLVERS = 1 << 2;
12393        public static final int DUMP_PERMISSIONS = 1 << 3;
12394        public static final int DUMP_PACKAGES = 1 << 4;
12395        public static final int DUMP_SHARED_USERS = 1 << 5;
12396        public static final int DUMP_MESSAGES = 1 << 6;
12397        public static final int DUMP_PROVIDERS = 1 << 7;
12398        public static final int DUMP_VERIFIERS = 1 << 8;
12399        public static final int DUMP_PREFERRED = 1 << 9;
12400        public static final int DUMP_PREFERRED_XML = 1 << 10;
12401        public static final int DUMP_KEYSETS = 1 << 11;
12402        public static final int DUMP_VERSION = 1 << 12;
12403        public static final int DUMP_INSTALLS = 1 << 13;
12404
12405        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12406
12407        private int mTypes;
12408
12409        private int mOptions;
12410
12411        private boolean mTitlePrinted;
12412
12413        private SharedUserSetting mSharedUser;
12414
12415        public boolean isDumping(int type) {
12416            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12417                return true;
12418            }
12419
12420            return (mTypes & type) != 0;
12421        }
12422
12423        public void setDump(int type) {
12424            mTypes |= type;
12425        }
12426
12427        public boolean isOptionEnabled(int option) {
12428            return (mOptions & option) != 0;
12429        }
12430
12431        public void setOptionEnabled(int option) {
12432            mOptions |= option;
12433        }
12434
12435        public boolean onTitlePrinted() {
12436            final boolean printed = mTitlePrinted;
12437            mTitlePrinted = true;
12438            return printed;
12439        }
12440
12441        public boolean getTitlePrinted() {
12442            return mTitlePrinted;
12443        }
12444
12445        public void setTitlePrinted(boolean enabled) {
12446            mTitlePrinted = enabled;
12447        }
12448
12449        public SharedUserSetting getSharedUser() {
12450            return mSharedUser;
12451        }
12452
12453        public void setSharedUser(SharedUserSetting user) {
12454            mSharedUser = user;
12455        }
12456    }
12457
12458    @Override
12459    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12460        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12461                != PackageManager.PERMISSION_GRANTED) {
12462            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12463                    + Binder.getCallingPid()
12464                    + ", uid=" + Binder.getCallingUid()
12465                    + " without permission "
12466                    + android.Manifest.permission.DUMP);
12467            return;
12468        }
12469
12470        DumpState dumpState = new DumpState();
12471        boolean fullPreferred = false;
12472        boolean checkin = false;
12473
12474        String packageName = null;
12475
12476        int opti = 0;
12477        while (opti < args.length) {
12478            String opt = args[opti];
12479            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12480                break;
12481            }
12482            opti++;
12483
12484            if ("-a".equals(opt)) {
12485                // Right now we only know how to print all.
12486            } else if ("-h".equals(opt)) {
12487                pw.println("Package manager dump options:");
12488                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12489                pw.println("    --checkin: dump for a checkin");
12490                pw.println("    -f: print details of intent filters");
12491                pw.println("    -h: print this help");
12492                pw.println("  cmd may be one of:");
12493                pw.println("    l[ibraries]: list known shared libraries");
12494                pw.println("    f[ibraries]: list device features");
12495                pw.println("    k[eysets]: print known keysets");
12496                pw.println("    r[esolvers]: dump intent resolvers");
12497                pw.println("    perm[issions]: dump permissions");
12498                pw.println("    pref[erred]: print preferred package settings");
12499                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12500                pw.println("    prov[iders]: dump content providers");
12501                pw.println("    p[ackages]: dump installed packages");
12502                pw.println("    s[hared-users]: dump shared user IDs");
12503                pw.println("    m[essages]: print collected runtime messages");
12504                pw.println("    v[erifiers]: print package verifier info");
12505                pw.println("    version: print database version info");
12506                pw.println("    write: write current settings now");
12507                pw.println("    <package.name>: info about given package");
12508                pw.println("    installs: details about install sessions");
12509                return;
12510            } else if ("--checkin".equals(opt)) {
12511                checkin = true;
12512            } else if ("-f".equals(opt)) {
12513                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12514            } else {
12515                pw.println("Unknown argument: " + opt + "; use -h for help");
12516            }
12517        }
12518
12519        // Is the caller requesting to dump a particular piece of data?
12520        if (opti < args.length) {
12521            String cmd = args[opti];
12522            opti++;
12523            // Is this a package name?
12524            if ("android".equals(cmd) || cmd.contains(".")) {
12525                packageName = cmd;
12526                // When dumping a single package, we always dump all of its
12527                // filter information since the amount of data will be reasonable.
12528                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12529            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12530                dumpState.setDump(DumpState.DUMP_LIBS);
12531            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12532                dumpState.setDump(DumpState.DUMP_FEATURES);
12533            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12534                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12535            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12536                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12537            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12538                dumpState.setDump(DumpState.DUMP_PREFERRED);
12539            } else if ("preferred-xml".equals(cmd)) {
12540                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12541                if (opti < args.length && "--full".equals(args[opti])) {
12542                    fullPreferred = true;
12543                    opti++;
12544                }
12545            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12546                dumpState.setDump(DumpState.DUMP_PACKAGES);
12547            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12548                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12549            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12550                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12551            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12552                dumpState.setDump(DumpState.DUMP_MESSAGES);
12553            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12554                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12555            } else if ("version".equals(cmd)) {
12556                dumpState.setDump(DumpState.DUMP_VERSION);
12557            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12558                dumpState.setDump(DumpState.DUMP_KEYSETS);
12559            } else if ("installs".equals(cmd)) {
12560                dumpState.setDump(DumpState.DUMP_INSTALLS);
12561            } else if ("write".equals(cmd)) {
12562                synchronized (mPackages) {
12563                    mSettings.writeLPr();
12564                    pw.println("Settings written.");
12565                    return;
12566                }
12567            }
12568        }
12569
12570        if (checkin) {
12571            pw.println("vers,1");
12572        }
12573
12574        // reader
12575        synchronized (mPackages) {
12576            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12577                if (!checkin) {
12578                    if (dumpState.onTitlePrinted())
12579                        pw.println();
12580                    pw.println("Database versions:");
12581                    pw.print("  SDK Version:");
12582                    pw.print(" internal=");
12583                    pw.print(mSettings.mInternalSdkPlatform);
12584                    pw.print(" external=");
12585                    pw.println(mSettings.mExternalSdkPlatform);
12586                    pw.print("  DB Version:");
12587                    pw.print(" internal=");
12588                    pw.print(mSettings.mInternalDatabaseVersion);
12589                    pw.print(" external=");
12590                    pw.println(mSettings.mExternalDatabaseVersion);
12591                }
12592            }
12593
12594            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12595                if (!checkin) {
12596                    if (dumpState.onTitlePrinted())
12597                        pw.println();
12598                    pw.println("Verifiers:");
12599                    pw.print("  Required: ");
12600                    pw.print(mRequiredVerifierPackage);
12601                    pw.print(" (uid=");
12602                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12603                    pw.println(")");
12604                } else if (mRequiredVerifierPackage != null) {
12605                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12606                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12607                }
12608            }
12609
12610            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12611                boolean printedHeader = false;
12612                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12613                while (it.hasNext()) {
12614                    String name = it.next();
12615                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12616                    if (!checkin) {
12617                        if (!printedHeader) {
12618                            if (dumpState.onTitlePrinted())
12619                                pw.println();
12620                            pw.println("Libraries:");
12621                            printedHeader = true;
12622                        }
12623                        pw.print("  ");
12624                    } else {
12625                        pw.print("lib,");
12626                    }
12627                    pw.print(name);
12628                    if (!checkin) {
12629                        pw.print(" -> ");
12630                    }
12631                    if (ent.path != null) {
12632                        if (!checkin) {
12633                            pw.print("(jar) ");
12634                            pw.print(ent.path);
12635                        } else {
12636                            pw.print(",jar,");
12637                            pw.print(ent.path);
12638                        }
12639                    } else {
12640                        if (!checkin) {
12641                            pw.print("(apk) ");
12642                            pw.print(ent.apk);
12643                        } else {
12644                            pw.print(",apk,");
12645                            pw.print(ent.apk);
12646                        }
12647                    }
12648                    pw.println();
12649                }
12650            }
12651
12652            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12653                if (dumpState.onTitlePrinted())
12654                    pw.println();
12655                if (!checkin) {
12656                    pw.println("Features:");
12657                }
12658                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12659                while (it.hasNext()) {
12660                    String name = it.next();
12661                    if (!checkin) {
12662                        pw.print("  ");
12663                    } else {
12664                        pw.print("feat,");
12665                    }
12666                    pw.println(name);
12667                }
12668            }
12669
12670            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12671                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12672                        : "Activity Resolver Table:", "  ", packageName,
12673                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12674                    dumpState.setTitlePrinted(true);
12675                }
12676                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12677                        : "Receiver Resolver Table:", "  ", packageName,
12678                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12679                    dumpState.setTitlePrinted(true);
12680                }
12681                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12682                        : "Service Resolver Table:", "  ", packageName,
12683                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12684                    dumpState.setTitlePrinted(true);
12685                }
12686                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12687                        : "Provider Resolver Table:", "  ", packageName,
12688                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12689                    dumpState.setTitlePrinted(true);
12690                }
12691            }
12692
12693            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12694                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12695                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12696                    int user = mSettings.mPreferredActivities.keyAt(i);
12697                    if (pir.dump(pw,
12698                            dumpState.getTitlePrinted()
12699                                ? "\nPreferred Activities User " + user + ":"
12700                                : "Preferred Activities User " + user + ":", "  ",
12701                            packageName, true, false)) {
12702                        dumpState.setTitlePrinted(true);
12703                    }
12704                }
12705            }
12706
12707            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12708                pw.flush();
12709                FileOutputStream fout = new FileOutputStream(fd);
12710                BufferedOutputStream str = new BufferedOutputStream(fout);
12711                XmlSerializer serializer = new FastXmlSerializer();
12712                try {
12713                    serializer.setOutput(str, "utf-8");
12714                    serializer.startDocument(null, true);
12715                    serializer.setFeature(
12716                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12717                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12718                    serializer.endDocument();
12719                    serializer.flush();
12720                } catch (IllegalArgumentException e) {
12721                    pw.println("Failed writing: " + e);
12722                } catch (IllegalStateException e) {
12723                    pw.println("Failed writing: " + e);
12724                } catch (IOException e) {
12725                    pw.println("Failed writing: " + e);
12726                }
12727            }
12728
12729            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12730                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12731                if (packageName == null) {
12732                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12733                        if (iperm == 0) {
12734                            if (dumpState.onTitlePrinted())
12735                                pw.println();
12736                            pw.println("AppOp Permissions:");
12737                        }
12738                        pw.print("  AppOp Permission ");
12739                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12740                        pw.println(":");
12741                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12742                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12743                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12744                        }
12745                    }
12746                }
12747            }
12748
12749            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12750                boolean printedSomething = false;
12751                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12752                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12753                        continue;
12754                    }
12755                    if (!printedSomething) {
12756                        if (dumpState.onTitlePrinted())
12757                            pw.println();
12758                        pw.println("Registered ContentProviders:");
12759                        printedSomething = true;
12760                    }
12761                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12762                    pw.print("    "); pw.println(p.toString());
12763                }
12764                printedSomething = false;
12765                for (Map.Entry<String, PackageParser.Provider> entry :
12766                        mProvidersByAuthority.entrySet()) {
12767                    PackageParser.Provider p = entry.getValue();
12768                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12769                        continue;
12770                    }
12771                    if (!printedSomething) {
12772                        if (dumpState.onTitlePrinted())
12773                            pw.println();
12774                        pw.println("ContentProvider Authorities:");
12775                        printedSomething = true;
12776                    }
12777                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12778                    pw.print("    "); pw.println(p.toString());
12779                    if (p.info != null && p.info.applicationInfo != null) {
12780                        final String appInfo = p.info.applicationInfo.toString();
12781                        pw.print("      applicationInfo="); pw.println(appInfo);
12782                    }
12783                }
12784            }
12785
12786            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12787                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12788            }
12789
12790            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12791                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12792            }
12793
12794            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12795                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
12796            }
12797
12798            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12799                // XXX should handle packageName != null by dumping only install data that
12800                // the given package is involved with.
12801                if (dumpState.onTitlePrinted()) pw.println();
12802                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12803            }
12804
12805            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12806                if (dumpState.onTitlePrinted()) pw.println();
12807                mSettings.dumpReadMessagesLPr(pw, dumpState);
12808
12809                pw.println();
12810                pw.println("Package warning messages:");
12811                BufferedReader in = null;
12812                String line = null;
12813                try {
12814                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12815                    while ((line = in.readLine()) != null) {
12816                        if (line.contains("ignored: updated version")) continue;
12817                        pw.println(line);
12818                    }
12819                } catch (IOException ignored) {
12820                } finally {
12821                    IoUtils.closeQuietly(in);
12822                }
12823            }
12824
12825            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
12826                BufferedReader in = null;
12827                String line = null;
12828                try {
12829                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12830                    while ((line = in.readLine()) != null) {
12831                        if (line.contains("ignored: updated version")) continue;
12832                        pw.print("msg,");
12833                        pw.println(line);
12834                    }
12835                } catch (IOException ignored) {
12836                } finally {
12837                    IoUtils.closeQuietly(in);
12838                }
12839            }
12840        }
12841    }
12842
12843    // ------- apps on sdcard specific code -------
12844    static final boolean DEBUG_SD_INSTALL = false;
12845
12846    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12847
12848    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12849
12850    private boolean mMediaMounted = false;
12851
12852    static String getEncryptKey() {
12853        try {
12854            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12855                    SD_ENCRYPTION_KEYSTORE_NAME);
12856            if (sdEncKey == null) {
12857                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12858                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12859                if (sdEncKey == null) {
12860                    Slog.e(TAG, "Failed to create encryption keys");
12861                    return null;
12862                }
12863            }
12864            return sdEncKey;
12865        } catch (NoSuchAlgorithmException nsae) {
12866            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12867            return null;
12868        } catch (IOException ioe) {
12869            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12870            return null;
12871        }
12872    }
12873
12874    /*
12875     * Update media status on PackageManager.
12876     */
12877    @Override
12878    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12879        int callingUid = Binder.getCallingUid();
12880        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12881            throw new SecurityException("Media status can only be updated by the system");
12882        }
12883        // reader; this apparently protects mMediaMounted, but should probably
12884        // be a different lock in that case.
12885        synchronized (mPackages) {
12886            Log.i(TAG, "Updating external media status from "
12887                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12888                    + (mediaStatus ? "mounted" : "unmounted"));
12889            if (DEBUG_SD_INSTALL)
12890                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12891                        + ", mMediaMounted=" + mMediaMounted);
12892            if (mediaStatus == mMediaMounted) {
12893                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12894                        : 0, -1);
12895                mHandler.sendMessage(msg);
12896                return;
12897            }
12898            mMediaMounted = mediaStatus;
12899        }
12900        // Queue up an async operation since the package installation may take a
12901        // little while.
12902        mHandler.post(new Runnable() {
12903            public void run() {
12904                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12905            }
12906        });
12907    }
12908
12909    /**
12910     * Called by MountService when the initial ASECs to scan are available.
12911     * Should block until all the ASEC containers are finished being scanned.
12912     */
12913    public void scanAvailableAsecs() {
12914        updateExternalMediaStatusInner(true, false, false);
12915        if (mShouldRestoreconData) {
12916            SELinuxMMAC.setRestoreconDone();
12917            mShouldRestoreconData = false;
12918        }
12919    }
12920
12921    /*
12922     * Collect information of applications on external media, map them against
12923     * existing containers and update information based on current mount status.
12924     * Please note that we always have to report status if reportStatus has been
12925     * set to true especially when unloading packages.
12926     */
12927    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12928            boolean externalStorage) {
12929        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12930        int[] uidArr = EmptyArray.INT;
12931
12932        final String[] list = PackageHelper.getSecureContainerList();
12933        if (ArrayUtils.isEmpty(list)) {
12934            Log.i(TAG, "No secure containers found");
12935        } else {
12936            // Process list of secure containers and categorize them
12937            // as active or stale based on their package internal state.
12938
12939            // reader
12940            synchronized (mPackages) {
12941                for (String cid : list) {
12942                    // Leave stages untouched for now; installer service owns them
12943                    if (PackageInstallerService.isStageName(cid)) continue;
12944
12945                    if (DEBUG_SD_INSTALL)
12946                        Log.i(TAG, "Processing container " + cid);
12947                    String pkgName = getAsecPackageName(cid);
12948                    if (pkgName == null) {
12949                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12950                        continue;
12951                    }
12952                    if (DEBUG_SD_INSTALL)
12953                        Log.i(TAG, "Looking for pkg : " + pkgName);
12954
12955                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12956                    if (ps == null) {
12957                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12958                        continue;
12959                    }
12960
12961                    /*
12962                     * Skip packages that are not external if we're unmounting
12963                     * external storage.
12964                     */
12965                    if (externalStorage && !isMounted && !isExternal(ps)) {
12966                        continue;
12967                    }
12968
12969                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12970                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12971                    // The package status is changed only if the code path
12972                    // matches between settings and the container id.
12973                    if (ps.codePathString != null
12974                            && ps.codePathString.startsWith(args.getCodePath())) {
12975                        if (DEBUG_SD_INSTALL) {
12976                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12977                                    + " at code path: " + ps.codePathString);
12978                        }
12979
12980                        // We do have a valid package installed on sdcard
12981                        processCids.put(args, ps.codePathString);
12982                        final int uid = ps.appId;
12983                        if (uid != -1) {
12984                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12985                        }
12986                    } else {
12987                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12988                                + ps.codePathString);
12989                    }
12990                }
12991            }
12992
12993            Arrays.sort(uidArr);
12994        }
12995
12996        // Process packages with valid entries.
12997        if (isMounted) {
12998            if (DEBUG_SD_INSTALL)
12999                Log.i(TAG, "Loading packages");
13000            loadMediaPackages(processCids, uidArr);
13001            startCleaningPackages();
13002            mInstallerService.onSecureContainersAvailable();
13003        } else {
13004            if (DEBUG_SD_INSTALL)
13005                Log.i(TAG, "Unloading packages");
13006            unloadMediaPackages(processCids, uidArr, reportStatus);
13007        }
13008    }
13009
13010    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13011            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13012        int size = pkgList.size();
13013        if (size > 0) {
13014            // Send broadcasts here
13015            Bundle extras = new Bundle();
13016            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
13017                    .toArray(new String[size]));
13018            if (uidArr != null) {
13019                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
13020            }
13021            if (replacing) {
13022                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
13023            }
13024            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
13025                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
13026            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
13027        }
13028    }
13029
13030   /*
13031     * Look at potentially valid container ids from processCids If package
13032     * information doesn't match the one on record or package scanning fails,
13033     * the cid is added to list of removeCids. We currently don't delete stale
13034     * containers.
13035     */
13036    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
13037        ArrayList<String> pkgList = new ArrayList<String>();
13038        Set<AsecInstallArgs> keys = processCids.keySet();
13039
13040        for (AsecInstallArgs args : keys) {
13041            String codePath = processCids.get(args);
13042            if (DEBUG_SD_INSTALL)
13043                Log.i(TAG, "Loading container : " + args.cid);
13044            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13045            try {
13046                // Make sure there are no container errors first.
13047                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
13048                    Slog.e(TAG, "Failed to mount cid : " + args.cid
13049                            + " when installing from sdcard");
13050                    continue;
13051                }
13052                // Check code path here.
13053                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
13054                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
13055                            + " does not match one in settings " + codePath);
13056                    continue;
13057                }
13058                // Parse package
13059                int parseFlags = mDefParseFlags;
13060                if (args.isExternal()) {
13061                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
13062                }
13063                if (args.isFwdLocked()) {
13064                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
13065                }
13066
13067                synchronized (mInstallLock) {
13068                    PackageParser.Package pkg = null;
13069                    try {
13070                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
13071                    } catch (PackageManagerException e) {
13072                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
13073                    }
13074                    // Scan the package
13075                    if (pkg != null) {
13076                        /*
13077                         * TODO why is the lock being held? doPostInstall is
13078                         * called in other places without the lock. This needs
13079                         * to be straightened out.
13080                         */
13081                        // writer
13082                        synchronized (mPackages) {
13083                            retCode = PackageManager.INSTALL_SUCCEEDED;
13084                            pkgList.add(pkg.packageName);
13085                            // Post process args
13086                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
13087                                    pkg.applicationInfo.uid);
13088                        }
13089                    } else {
13090                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
13091                    }
13092                }
13093
13094            } finally {
13095                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
13096                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
13097                }
13098            }
13099        }
13100        // writer
13101        synchronized (mPackages) {
13102            // If the platform SDK has changed since the last time we booted,
13103            // we need to re-grant app permission to catch any new ones that
13104            // appear. This is really a hack, and means that apps can in some
13105            // cases get permissions that the user didn't initially explicitly
13106            // allow... it would be nice to have some better way to handle
13107            // this situation.
13108            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
13109            if (regrantPermissions)
13110                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
13111                        + mSdkVersion + "; regranting permissions for external storage");
13112            mSettings.mExternalSdkPlatform = mSdkVersion;
13113
13114            // Make sure group IDs have been assigned, and any permission
13115            // changes in other apps are accounted for
13116            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
13117                    | (regrantPermissions
13118                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
13119                            : 0));
13120
13121            mSettings.updateExternalDatabaseVersion();
13122
13123            // can downgrade to reader
13124            // Persist settings
13125            mSettings.writeLPr();
13126        }
13127        // Send a broadcast to let everyone know we are done processing
13128        if (pkgList.size() > 0) {
13129            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13130        }
13131    }
13132
13133   /*
13134     * Utility method to unload a list of specified containers
13135     */
13136    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
13137        // Just unmount all valid containers.
13138        for (AsecInstallArgs arg : cidArgs) {
13139            synchronized (mInstallLock) {
13140                arg.doPostDeleteLI(false);
13141           }
13142       }
13143   }
13144
13145    /*
13146     * Unload packages mounted on external media. This involves deleting package
13147     * data from internal structures, sending broadcasts about diabled packages,
13148     * gc'ing to free up references, unmounting all secure containers
13149     * corresponding to packages on external media, and posting a
13150     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
13151     * that we always have to post this message if status has been requested no
13152     * matter what.
13153     */
13154    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
13155            final boolean reportStatus) {
13156        if (DEBUG_SD_INSTALL)
13157            Log.i(TAG, "unloading media packages");
13158        ArrayList<String> pkgList = new ArrayList<String>();
13159        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
13160        final Set<AsecInstallArgs> keys = processCids.keySet();
13161        for (AsecInstallArgs args : keys) {
13162            String pkgName = args.getPackageName();
13163            if (DEBUG_SD_INSTALL)
13164                Log.i(TAG, "Trying to unload pkg : " + pkgName);
13165            // Delete package internally
13166            PackageRemovedInfo outInfo = new PackageRemovedInfo();
13167            synchronized (mInstallLock) {
13168                boolean res = deletePackageLI(pkgName, null, false, null, null,
13169                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
13170                if (res) {
13171                    pkgList.add(pkgName);
13172                } else {
13173                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
13174                    failedList.add(args);
13175                }
13176            }
13177        }
13178
13179        // reader
13180        synchronized (mPackages) {
13181            // We didn't update the settings after removing each package;
13182            // write them now for all packages.
13183            mSettings.writeLPr();
13184        }
13185
13186        // We have to absolutely send UPDATED_MEDIA_STATUS only
13187        // after confirming that all the receivers processed the ordered
13188        // broadcast when packages get disabled, force a gc to clean things up.
13189        // and unload all the containers.
13190        if (pkgList.size() > 0) {
13191            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
13192                    new IIntentReceiver.Stub() {
13193                public void performReceive(Intent intent, int resultCode, String data,
13194                        Bundle extras, boolean ordered, boolean sticky,
13195                        int sendingUser) throws RemoteException {
13196                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
13197                            reportStatus ? 1 : 0, 1, keys);
13198                    mHandler.sendMessage(msg);
13199                }
13200            });
13201        } else {
13202            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
13203                    keys);
13204            mHandler.sendMessage(msg);
13205        }
13206    }
13207
13208    /** Binder call */
13209    @Override
13210    public void movePackage(final String packageName, final IPackageMoveObserver observer,
13211            final int flags) {
13212        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
13213        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
13214        int returnCode = PackageManager.MOVE_SUCCEEDED;
13215        int currInstallFlags = 0;
13216        int newInstallFlags = 0;
13217
13218        File codeFile = null;
13219        String installerPackageName = null;
13220        String packageAbiOverride = null;
13221
13222        // reader
13223        synchronized (mPackages) {
13224            final PackageParser.Package pkg = mPackages.get(packageName);
13225            final PackageSetting ps = mSettings.mPackages.get(packageName);
13226            if (pkg == null || ps == null) {
13227                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13228            } else {
13229                // Disable moving fwd locked apps and system packages
13230                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
13231                    Slog.w(TAG, "Cannot move system application");
13232                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
13233                } else if (pkg.mOperationPending) {
13234                    Slog.w(TAG, "Attempt to move package which has pending operations");
13235                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
13236                } else {
13237                    // Find install location first
13238                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13239                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13240                        Slog.w(TAG, "Ambigous flags specified for move location.");
13241                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13242                    } else {
13243                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13244                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13245                        currInstallFlags = isExternal(pkg)
13246                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13247
13248                        if (newInstallFlags == currInstallFlags) {
13249                            Slog.w(TAG, "No move required. Trying to move to same location");
13250                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13251                        } else {
13252                            if (isForwardLocked(pkg)) {
13253                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13254                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13255                            }
13256                        }
13257                    }
13258                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13259                        pkg.mOperationPending = true;
13260                    }
13261                }
13262
13263                codeFile = new File(pkg.codePath);
13264                installerPackageName = ps.installerPackageName;
13265                packageAbiOverride = ps.cpuAbiOverrideString;
13266            }
13267        }
13268
13269        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13270            try {
13271                observer.packageMoved(packageName, returnCode);
13272            } catch (RemoteException ignored) {
13273            }
13274            return;
13275        }
13276
13277        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
13278            @Override
13279            public void onUserActionRequired(Intent intent) throws RemoteException {
13280                throw new IllegalStateException();
13281            }
13282
13283            @Override
13284            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
13285                    Bundle extras) throws RemoteException {
13286                Slog.d(TAG, "Install result for move: "
13287                        + PackageManager.installStatusToString(returnCode, msg));
13288
13289                // We usually have a new package now after the install, but if
13290                // we failed we need to clear the pending flag on the original
13291                // package object.
13292                synchronized (mPackages) {
13293                    final PackageParser.Package pkg = mPackages.get(packageName);
13294                    if (pkg != null) {
13295                        pkg.mOperationPending = false;
13296                    }
13297                }
13298
13299                final int status = PackageManager.installStatusToPublicStatus(returnCode);
13300                switch (status) {
13301                    case PackageInstaller.STATUS_SUCCESS:
13302                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
13303                        break;
13304                    case PackageInstaller.STATUS_FAILURE_STORAGE:
13305                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
13306                        break;
13307                    default:
13308                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
13309                        break;
13310                }
13311            }
13312        };
13313
13314        // Treat a move like reinstalling an existing app, which ensures that we
13315        // process everythign uniformly, like unpacking native libraries.
13316        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
13317
13318        final Message msg = mHandler.obtainMessage(INIT_COPY);
13319        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
13320        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
13321                installerPackageName, null, user, packageAbiOverride);
13322        mHandler.sendMessage(msg);
13323    }
13324
13325    @Override
13326    public boolean setInstallLocation(int loc) {
13327        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13328                null);
13329        if (getInstallLocation() == loc) {
13330            return true;
13331        }
13332        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13333                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13334            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13335                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13336            return true;
13337        }
13338        return false;
13339   }
13340
13341    @Override
13342    public int getInstallLocation() {
13343        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13344                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13345                PackageHelper.APP_INSTALL_AUTO);
13346    }
13347
13348    /** Called by UserManagerService */
13349    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13350        mDirtyUsers.remove(userHandle);
13351        mSettings.removeUserLPw(userHandle);
13352        mPendingBroadcasts.remove(userHandle);
13353        if (mInstaller != null) {
13354            // Technically, we shouldn't be doing this with the package lock
13355            // held.  However, this is very rare, and there is already so much
13356            // other disk I/O going on, that we'll let it slide for now.
13357            mInstaller.removeUserDataDirs(userHandle);
13358        }
13359        mUserNeedsBadging.delete(userHandle);
13360        removeUnusedPackagesLILPw(userManager, userHandle);
13361    }
13362
13363    /**
13364     * We're removing userHandle and would like to remove any downloaded packages
13365     * that are no longer in use by any other user.
13366     * @param userHandle the user being removed
13367     */
13368    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13369        final boolean DEBUG_CLEAN_APKS = false;
13370        int [] users = userManager.getUserIdsLPr();
13371        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13372        while (psit.hasNext()) {
13373            PackageSetting ps = psit.next();
13374            if (ps.pkg == null) {
13375                continue;
13376            }
13377            final String packageName = ps.pkg.packageName;
13378            // Skip over if system app
13379            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13380                continue;
13381            }
13382            if (DEBUG_CLEAN_APKS) {
13383                Slog.i(TAG, "Checking package " + packageName);
13384            }
13385            boolean keep = false;
13386            for (int i = 0; i < users.length; i++) {
13387                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13388                    keep = true;
13389                    if (DEBUG_CLEAN_APKS) {
13390                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13391                                + users[i]);
13392                    }
13393                    break;
13394                }
13395            }
13396            if (!keep) {
13397                if (DEBUG_CLEAN_APKS) {
13398                    Slog.i(TAG, "  Removing package " + packageName);
13399                }
13400                mHandler.post(new Runnable() {
13401                    public void run() {
13402                        deletePackageX(packageName, userHandle, 0);
13403                    } //end run
13404                });
13405            }
13406        }
13407    }
13408
13409    /** Called by UserManagerService */
13410    void createNewUserLILPw(int userHandle, File path) {
13411        if (mInstaller != null) {
13412            mInstaller.createUserConfig(userHandle);
13413            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13414        }
13415    }
13416
13417    @Override
13418    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13419        mContext.enforceCallingOrSelfPermission(
13420                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13421                "Only package verification agents can read the verifier device identity");
13422
13423        synchronized (mPackages) {
13424            return mSettings.getVerifierDeviceIdentityLPw();
13425        }
13426    }
13427
13428    @Override
13429    public void setPermissionEnforced(String permission, boolean enforced) {
13430        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13431        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13432            synchronized (mPackages) {
13433                if (mSettings.mReadExternalStorageEnforced == null
13434                        || mSettings.mReadExternalStorageEnforced != enforced) {
13435                    mSettings.mReadExternalStorageEnforced = enforced;
13436                    mSettings.writeLPr();
13437                }
13438            }
13439            // kill any non-foreground processes so we restart them and
13440            // grant/revoke the GID.
13441            final IActivityManager am = ActivityManagerNative.getDefault();
13442            if (am != null) {
13443                final long token = Binder.clearCallingIdentity();
13444                try {
13445                    am.killProcessesBelowForeground("setPermissionEnforcement");
13446                } catch (RemoteException e) {
13447                } finally {
13448                    Binder.restoreCallingIdentity(token);
13449                }
13450            }
13451        } else {
13452            throw new IllegalArgumentException("No selective enforcement for " + permission);
13453        }
13454    }
13455
13456    @Override
13457    @Deprecated
13458    public boolean isPermissionEnforced(String permission) {
13459        return true;
13460    }
13461
13462    @Override
13463    public boolean isStorageLow() {
13464        final long token = Binder.clearCallingIdentity();
13465        try {
13466            final DeviceStorageMonitorInternal
13467                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13468            if (dsm != null) {
13469                return dsm.isMemoryLow();
13470            } else {
13471                return false;
13472            }
13473        } finally {
13474            Binder.restoreCallingIdentity(token);
13475        }
13476    }
13477
13478    @Override
13479    public IPackageInstaller getPackageInstaller() {
13480        return mInstallerService;
13481    }
13482
13483    private boolean userNeedsBadging(int userId) {
13484        int index = mUserNeedsBadging.indexOfKey(userId);
13485        if (index < 0) {
13486            final UserInfo userInfo;
13487            final long token = Binder.clearCallingIdentity();
13488            try {
13489                userInfo = sUserManager.getUserInfo(userId);
13490            } finally {
13491                Binder.restoreCallingIdentity(token);
13492            }
13493            final boolean b;
13494            if (userInfo != null && userInfo.isManagedProfile()) {
13495                b = true;
13496            } else {
13497                b = false;
13498            }
13499            mUserNeedsBadging.put(userId, b);
13500            return b;
13501        }
13502        return mUserNeedsBadging.valueAt(index);
13503    }
13504
13505    @Override
13506    public KeySet getKeySetByAlias(String packageName, String alias) {
13507        if (packageName == null || alias == null) {
13508            return null;
13509        }
13510        synchronized(mPackages) {
13511            final PackageParser.Package pkg = mPackages.get(packageName);
13512            if (pkg == null) {
13513                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13514                throw new IllegalArgumentException("Unknown package: " + packageName);
13515            }
13516            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13517            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13518        }
13519    }
13520
13521    @Override
13522    public KeySet getSigningKeySet(String packageName) {
13523        if (packageName == null) {
13524            return null;
13525        }
13526        synchronized(mPackages) {
13527            final PackageParser.Package pkg = mPackages.get(packageName);
13528            if (pkg == null) {
13529                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13530                throw new IllegalArgumentException("Unknown package: " + packageName);
13531            }
13532            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13533                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13534                throw new SecurityException("May not access signing KeySet of other apps.");
13535            }
13536            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13537            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13538        }
13539    }
13540
13541    @Override
13542    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13543        if (packageName == null || ks == null) {
13544            return false;
13545        }
13546        synchronized(mPackages) {
13547            final PackageParser.Package pkg = mPackages.get(packageName);
13548            if (pkg == null) {
13549                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13550                throw new IllegalArgumentException("Unknown package: " + packageName);
13551            }
13552            IBinder ksh = ks.getToken();
13553            if (ksh instanceof KeySetHandle) {
13554                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13555                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13556            }
13557            return false;
13558        }
13559    }
13560
13561    @Override
13562    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13563        if (packageName == null || ks == null) {
13564            return false;
13565        }
13566        synchronized(mPackages) {
13567            final PackageParser.Package pkg = mPackages.get(packageName);
13568            if (pkg == null) {
13569                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13570                throw new IllegalArgumentException("Unknown package: " + packageName);
13571            }
13572            IBinder ksh = ks.getToken();
13573            if (ksh instanceof KeySetHandle) {
13574                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13575                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13576            }
13577            return false;
13578        }
13579    }
13580
13581    public void getUsageStatsIfNoPackageUsageInfo() {
13582        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
13583            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
13584            if (usm == null) {
13585                throw new IllegalStateException("UsageStatsManager must be initialized");
13586            }
13587            long now = System.currentTimeMillis();
13588            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
13589            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
13590                String packageName = entry.getKey();
13591                PackageParser.Package pkg = mPackages.get(packageName);
13592                if (pkg == null) {
13593                    continue;
13594                }
13595                UsageStats usage = entry.getValue();
13596                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
13597                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
13598            }
13599        }
13600    }
13601
13602    /**
13603     * Check and throw if the given before/after packages would be considered a
13604     * downgrade.
13605     */
13606    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
13607            throws PackageManagerException {
13608        if (after.versionCode < before.mVersionCode) {
13609            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13610                    "Update version code " + after.versionCode + " is older than current "
13611                    + before.mVersionCode);
13612        } else if (after.versionCode == before.mVersionCode) {
13613            if (after.baseRevisionCode < before.baseRevisionCode) {
13614                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13615                        "Update base revision code " + after.baseRevisionCode
13616                        + " is older than current " + before.baseRevisionCode);
13617            }
13618
13619            if (!ArrayUtils.isEmpty(after.splitNames)) {
13620                for (int i = 0; i < after.splitNames.length; i++) {
13621                    final String splitName = after.splitNames[i];
13622                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
13623                    if (j != -1) {
13624                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
13625                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13626                                    "Update split " + splitName + " revision code "
13627                                    + after.splitRevisionCodes[i] + " is older than current "
13628                                    + before.splitRevisionCodes[j]);
13629                        }
13630                    }
13631                }
13632            }
13633        }
13634    }
13635}
13636