PackageManagerService.java revision 7487657ee9f3f91a1fb4e52ce2a03b56496ac1f4
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;
58import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
59import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
60import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
61import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
62
63import android.util.ArrayMap;
64
65import com.android.internal.R;
66import com.android.internal.app.IMediaContainerService;
67import com.android.internal.app.ResolverActivity;
68import com.android.internal.content.NativeLibraryHelper;
69import com.android.internal.content.PackageHelper;
70import com.android.internal.os.IParcelFileDescriptorFactory;
71import com.android.internal.util.ArrayUtils;
72import com.android.internal.util.FastPrintWriter;
73import com.android.internal.util.FastXmlSerializer;
74import com.android.internal.util.IndentingPrintWriter;
75import com.android.server.EventLogTags;
76import com.android.server.IntentResolver;
77import com.android.server.LocalServices;
78import com.android.server.ServiceThread;
79import com.android.server.SystemConfig;
80import com.android.server.Watchdog;
81import com.android.server.pm.Settings.DatabaseVersion;
82import com.android.server.storage.DeviceStorageMonitorInternal;
83
84import org.xmlpull.v1.XmlSerializer;
85
86import android.app.ActivityManager;
87import android.app.ActivityManagerNative;
88import android.app.AppGlobals;
89import android.app.IActivityManager;
90import android.app.admin.IDevicePolicyManager;
91import android.app.backup.IBackupManager;
92import android.app.usage.UsageStats;
93import android.app.usage.UsageStatsManager;
94import android.content.BroadcastReceiver;
95import android.content.ComponentName;
96import android.content.Context;
97import android.content.IIntentReceiver;
98import android.content.Intent;
99import android.content.IntentFilter;
100import android.content.IntentSender;
101import android.content.IntentSender.SendIntentException;
102import android.content.ServiceConnection;
103import android.content.pm.ActivityInfo;
104import android.content.pm.ApplicationInfo;
105import android.content.pm.FeatureInfo;
106import android.content.pm.IPackageDataObserver;
107import android.content.pm.IPackageDeleteObserver;
108import android.content.pm.IPackageDeleteObserver2;
109import android.content.pm.IPackageInstallObserver2;
110import android.content.pm.IPackageInstaller;
111import android.content.pm.IPackageManager;
112import android.content.pm.IPackageMoveObserver;
113import android.content.pm.IPackageStatsObserver;
114import android.content.pm.InstrumentationInfo;
115import android.content.pm.KeySet;
116import android.content.pm.ManifestDigest;
117import android.content.pm.PackageCleanItem;
118import android.content.pm.PackageInfo;
119import android.content.pm.PackageInfoLite;
120import android.content.pm.PackageInstaller;
121import android.content.pm.PackageManager;
122import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
123import android.content.pm.PackageParser.ActivityIntentInfo;
124import android.content.pm.PackageParser.PackageLite;
125import android.content.pm.PackageParser.PackageParserException;
126import android.content.pm.PackageParser;
127import android.content.pm.PackageStats;
128import android.content.pm.PackageUserState;
129import android.content.pm.ParceledListSlice;
130import android.content.pm.PermissionGroupInfo;
131import android.content.pm.PermissionInfo;
132import android.content.pm.ProviderInfo;
133import android.content.pm.ResolveInfo;
134import android.content.pm.ServiceInfo;
135import android.content.pm.Signature;
136import android.content.pm.UserInfo;
137import android.content.pm.VerificationParams;
138import android.content.pm.VerifierDeviceIdentity;
139import android.content.pm.VerifierInfo;
140import android.content.res.Resources;
141import android.hardware.display.DisplayManager;
142import android.net.Uri;
143import android.os.Binder;
144import android.os.Build;
145import android.os.Bundle;
146import android.os.Environment;
147import android.os.Environment.UserEnvironment;
148import android.os.storage.IMountService;
149import android.os.storage.StorageManager;
150import android.os.Debug;
151import android.os.FileUtils;
152import android.os.Handler;
153import android.os.IBinder;
154import android.os.Looper;
155import android.os.Message;
156import android.os.Parcel;
157import android.os.ParcelFileDescriptor;
158import android.os.Process;
159import android.os.RemoteException;
160import android.os.SELinux;
161import android.os.ServiceManager;
162import android.os.SystemClock;
163import android.os.SystemProperties;
164import android.os.UserHandle;
165import android.os.UserManager;
166import android.security.KeyStore;
167import android.security.SystemKeyStore;
168import android.system.ErrnoException;
169import android.system.Os;
170import android.system.StructStat;
171import android.text.TextUtils;
172import android.text.format.DateUtils;
173import android.util.ArraySet;
174import android.util.AtomicFile;
175import android.util.DisplayMetrics;
176import android.util.EventLog;
177import android.util.ExceptionUtils;
178import android.util.Log;
179import android.util.LogPrinter;
180import android.util.PrintStreamPrinter;
181import android.util.Slog;
182import android.util.SparseArray;
183import android.util.SparseBooleanArray;
184import android.view.Display;
185
186import java.io.BufferedInputStream;
187import java.io.BufferedOutputStream;
188import java.io.BufferedReader;
189import java.io.File;
190import java.io.FileDescriptor;
191import java.io.FileNotFoundException;
192import java.io.FileOutputStream;
193import java.io.FileReader;
194import java.io.FilenameFilter;
195import java.io.IOException;
196import java.io.InputStream;
197import java.io.PrintWriter;
198import java.nio.charset.StandardCharsets;
199import java.security.NoSuchAlgorithmException;
200import java.security.PublicKey;
201import java.security.cert.CertificateEncodingException;
202import java.security.cert.CertificateException;
203import java.text.SimpleDateFormat;
204import java.util.ArrayList;
205import java.util.Arrays;
206import java.util.Collection;
207import java.util.Collections;
208import java.util.Comparator;
209import java.util.Date;
210import java.util.Iterator;
211import java.util.List;
212import java.util.Map;
213import java.util.Objects;
214import java.util.Set;
215import java.util.concurrent.atomic.AtomicBoolean;
216import java.util.concurrent.atomic.AtomicLong;
217
218import dalvik.system.DexFile;
219import dalvik.system.VMRuntime;
220
221import libcore.io.IoUtils;
222import libcore.util.EmptyArray;
223
224/**
225 * Keep track of all those .apks everywhere.
226 *
227 * This is very central to the platform's security; please run the unit
228 * tests whenever making modifications here:
229 *
230mmm frameworks/base/tests/AndroidTests
231adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
232adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
233 *
234 * {@hide}
235 */
236public class PackageManagerService extends IPackageManager.Stub {
237    static final String TAG = "PackageManager";
238    static final boolean DEBUG_SETTINGS = false;
239    static final boolean DEBUG_PREFERRED = false;
240    static final boolean DEBUG_UPGRADE = false;
241    private static final boolean DEBUG_INSTALL = false;
242    private static final boolean DEBUG_REMOVE = false;
243    private static final boolean DEBUG_BROADCASTS = false;
244    private static final boolean DEBUG_SHOW_INFO = false;
245    private static final boolean DEBUG_PACKAGE_INFO = false;
246    private static final boolean DEBUG_INTENT_MATCHING = false;
247    private static final boolean DEBUG_PACKAGE_SCANNING = false;
248    private static final boolean DEBUG_VERIFY = false;
249    private static final boolean DEBUG_DEXOPT = false;
250    private static final boolean DEBUG_ABI_SELECTION = false;
251
252    private static final int RADIO_UID = Process.PHONE_UID;
253    private static final int LOG_UID = Process.LOG_UID;
254    private static final int NFC_UID = Process.NFC_UID;
255    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
256    private static final int SHELL_UID = Process.SHELL_UID;
257
258    // Cap the size of permission trees that 3rd party apps can define
259    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
260
261    // Suffix used during package installation when copying/moving
262    // package apks to install directory.
263    private static final String INSTALL_PACKAGE_SUFFIX = "-";
264
265    static final int SCAN_NO_DEX = 1<<1;
266    static final int SCAN_FORCE_DEX = 1<<2;
267    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
268    static final int SCAN_NEW_INSTALL = 1<<4;
269    static final int SCAN_NO_PATHS = 1<<5;
270    static final int SCAN_UPDATE_TIME = 1<<6;
271    static final int SCAN_DEFER_DEX = 1<<7;
272    static final int SCAN_BOOTING = 1<<8;
273    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
274    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
275    static final int SCAN_REPLACING = 1<<11;
276
277    static final int REMOVE_CHATTY = 1<<16;
278
279    /**
280     * Timeout (in milliseconds) after which the watchdog should declare that
281     * our handler thread is wedged.  The usual default for such things is one
282     * minute but we sometimes do very lengthy I/O operations on this thread,
283     * such as installing multi-gigabyte applications, so ours needs to be longer.
284     */
285    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
286
287    /**
288     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
289     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
290     * settings entry if available, otherwise we use the hardcoded default.  If it's been
291     * more than this long since the last fstrim, we force one during the boot sequence.
292     *
293     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
294     * one gets run at the next available charging+idle time.  This final mandatory
295     * no-fstrim check kicks in only of the other scheduling criteria is never met.
296     */
297    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
298
299    /**
300     * Whether verification is enabled by default.
301     */
302    private static final boolean DEFAULT_VERIFY_ENABLE = true;
303
304    /**
305     * The default maximum time to wait for the verification agent to return in
306     * milliseconds.
307     */
308    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
309
310    /**
311     * The default response for package verification timeout.
312     *
313     * This can be either PackageManager.VERIFICATION_ALLOW or
314     * PackageManager.VERIFICATION_REJECT.
315     */
316    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
317
318    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
319
320    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
321            DEFAULT_CONTAINER_PACKAGE,
322            "com.android.defcontainer.DefaultContainerService");
323
324    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
325
326    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
327
328    final ServiceThread mHandlerThread;
329
330    final PackageHandler mHandler;
331
332    /**
333     * Messages for {@link #mHandler} that need to wait for system ready before
334     * being dispatched.
335     */
336    private ArrayList<Message> mPostSystemReadyMessages;
337
338    final int mSdkVersion = Build.VERSION.SDK_INT;
339
340    final Context mContext;
341    final boolean mFactoryTest;
342    final boolean mOnlyCore;
343    final boolean mLazyDexOpt;
344    final long mDexOptLRUThresholdInMills;
345    final DisplayMetrics mMetrics;
346    final int mDefParseFlags;
347    final String[] mSeparateProcesses;
348    final boolean mIsUpgrade;
349
350    // This is where all application persistent data goes.
351    final File mAppDataDir;
352
353    // This is where all application persistent data goes for secondary users.
354    final File mUserAppDataDir;
355
356    /** The location for ASEC container files on internal storage. */
357    final String mAsecInternalPath;
358
359    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
360    // LOCK HELD.  Can be called with mInstallLock held.
361    final Installer mInstaller;
362
363    /** Directory where installed third-party apps stored */
364    final File mAppInstallDir;
365
366    /**
367     * Directory to which applications installed internally have their
368     * 32 bit native libraries copied.
369     */
370    private File mAppLib32InstallDir;
371
372    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
373    // apps.
374    final File mDrmAppPrivateInstallDir;
375
376    // ----------------------------------------------------------------
377
378    // Lock for state used when installing and doing other long running
379    // operations.  Methods that must be called with this lock held have
380    // the suffix "LI".
381    final Object mInstallLock = new Object();
382
383    // ----------------------------------------------------------------
384
385    // Keys are String (package name), values are Package.  This also serves
386    // as the lock for the global state.  Methods that must be called with
387    // this lock held have the prefix "LP".
388    final ArrayMap<String, PackageParser.Package> mPackages =
389            new ArrayMap<String, PackageParser.Package>();
390
391    // Tracks available target package names -> overlay package paths.
392    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
393        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
394
395    final Settings mSettings;
396    boolean mRestoredSettings;
397
398    // System configuration read by SystemConfig.
399    final int[] mGlobalGids;
400    final SparseArray<ArraySet<String>> mSystemPermissions;
401    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
402
403    // If mac_permissions.xml was found for seinfo labeling.
404    boolean mFoundPolicyFile;
405
406    // If a recursive restorecon of /data/data/<pkg> is needed.
407    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
408
409    public static final class SharedLibraryEntry {
410        public final String path;
411        public final String apk;
412
413        SharedLibraryEntry(String _path, String _apk) {
414            path = _path;
415            apk = _apk;
416        }
417    }
418
419    // Currently known shared libraries.
420    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
421            new ArrayMap<String, SharedLibraryEntry>();
422
423    // All available activities, for your resolving pleasure.
424    final ActivityIntentResolver mActivities =
425            new ActivityIntentResolver();
426
427    // All available receivers, for your resolving pleasure.
428    final ActivityIntentResolver mReceivers =
429            new ActivityIntentResolver();
430
431    // All available services, for your resolving pleasure.
432    final ServiceIntentResolver mServices = new ServiceIntentResolver();
433
434    // All available providers, for your resolving pleasure.
435    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
436
437    // Mapping from provider base names (first directory in content URI codePath)
438    // to the provider information.
439    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
440            new ArrayMap<String, PackageParser.Provider>();
441
442    // Mapping from instrumentation class names to info about them.
443    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
444            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
445
446    // Mapping from permission names to info about them.
447    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
448            new ArrayMap<String, PackageParser.PermissionGroup>();
449
450    // Packages whose data we have transfered into another package, thus
451    // should no longer exist.
452    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
453
454    // Broadcast actions that are only available to the system.
455    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
456
457    /** List of packages waiting for verification. */
458    final SparseArray<PackageVerificationState> mPendingVerification
459            = new SparseArray<PackageVerificationState>();
460
461    /** Set of packages associated with each app op permission. */
462    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
463
464    final PackageInstallerService mInstallerService;
465
466    private final PackageDexOptimizer mPackageDexOptimizer;
467    // Cache of users who need badging.
468    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
469
470    /** Token for keys in mPendingVerification. */
471    private int mPendingVerificationToken = 0;
472
473    volatile boolean mSystemReady;
474    volatile boolean mSafeMode;
475    volatile boolean mHasSystemUidErrors;
476
477    ApplicationInfo mAndroidApplication;
478    final ActivityInfo mResolveActivity = new ActivityInfo();
479    final ResolveInfo mResolveInfo = new ResolveInfo();
480    ComponentName mResolveComponentName;
481    PackageParser.Package mPlatformPackage;
482    ComponentName mCustomResolverComponentName;
483
484    boolean mResolverReplaced = false;
485
486    // Set of pending broadcasts for aggregating enable/disable of components.
487    static class PendingPackageBroadcasts {
488        // for each user id, a map of <package name -> components within that package>
489        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
490
491        public PendingPackageBroadcasts() {
492            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
493        }
494
495        public ArrayList<String> get(int userId, String packageName) {
496            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
497            return packages.get(packageName);
498        }
499
500        public void put(int userId, String packageName, ArrayList<String> components) {
501            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
502            packages.put(packageName, components);
503        }
504
505        public void remove(int userId, String packageName) {
506            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
507            if (packages != null) {
508                packages.remove(packageName);
509            }
510        }
511
512        public void remove(int userId) {
513            mUidMap.remove(userId);
514        }
515
516        public int userIdCount() {
517            return mUidMap.size();
518        }
519
520        public int userIdAt(int n) {
521            return mUidMap.keyAt(n);
522        }
523
524        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
525            return mUidMap.get(userId);
526        }
527
528        public int size() {
529            // total number of pending broadcast entries across all userIds
530            int num = 0;
531            for (int i = 0; i< mUidMap.size(); i++) {
532                num += mUidMap.valueAt(i).size();
533            }
534            return num;
535        }
536
537        public void clear() {
538            mUidMap.clear();
539        }
540
541        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
542            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
543            if (map == null) {
544                map = new ArrayMap<String, ArrayList<String>>();
545                mUidMap.put(userId, map);
546            }
547            return map;
548        }
549    }
550    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
551
552    // Service Connection to remote media container service to copy
553    // package uri's from external media onto secure containers
554    // or internal storage.
555    private IMediaContainerService mContainerService = null;
556
557    static final int SEND_PENDING_BROADCAST = 1;
558    static final int MCS_BOUND = 3;
559    static final int END_COPY = 4;
560    static final int INIT_COPY = 5;
561    static final int MCS_UNBIND = 6;
562    static final int START_CLEANING_PACKAGE = 7;
563    static final int FIND_INSTALL_LOC = 8;
564    static final int POST_INSTALL = 9;
565    static final int MCS_RECONNECT = 10;
566    static final int MCS_GIVE_UP = 11;
567    static final int UPDATED_MEDIA_STATUS = 12;
568    static final int WRITE_SETTINGS = 13;
569    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
570    static final int PACKAGE_VERIFIED = 15;
571    static final int CHECK_PENDING_VERIFICATION = 16;
572
573    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
574
575    // Delay time in millisecs
576    static final int BROADCAST_DELAY = 10 * 1000;
577
578    static UserManagerService sUserManager;
579
580    // Stores a list of users whose package restrictions file needs to be updated
581    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
582
583    final private DefaultContainerConnection mDefContainerConn =
584            new DefaultContainerConnection();
585    class DefaultContainerConnection implements ServiceConnection {
586        public void onServiceConnected(ComponentName name, IBinder service) {
587            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
588            IMediaContainerService imcs =
589                IMediaContainerService.Stub.asInterface(service);
590            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
591        }
592
593        public void onServiceDisconnected(ComponentName name) {
594            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
595        }
596    };
597
598    // Recordkeeping of restore-after-install operations that are currently in flight
599    // between the Package Manager and the Backup Manager
600    class PostInstallData {
601        public InstallArgs args;
602        public PackageInstalledInfo res;
603
604        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
605            args = _a;
606            res = _r;
607        }
608    };
609    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
610    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
611
612    private final String mRequiredVerifierPackage;
613
614    private final PackageUsage mPackageUsage = new PackageUsage();
615
616    private class PackageUsage {
617        private static final int WRITE_INTERVAL
618            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
619
620        private final Object mFileLock = new Object();
621        private final AtomicLong mLastWritten = new AtomicLong(0);
622        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
623
624        private boolean mIsHistoricalPackageUsageAvailable = true;
625
626        boolean isHistoricalPackageUsageAvailable() {
627            return mIsHistoricalPackageUsageAvailable;
628        }
629
630        void write(boolean force) {
631            if (force) {
632                writeInternal();
633                return;
634            }
635            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
636                && !DEBUG_DEXOPT) {
637                return;
638            }
639            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
640                new Thread("PackageUsage_DiskWriter") {
641                    @Override
642                    public void run() {
643                        try {
644                            writeInternal();
645                        } finally {
646                            mBackgroundWriteRunning.set(false);
647                        }
648                    }
649                }.start();
650            }
651        }
652
653        private void writeInternal() {
654            synchronized (mPackages) {
655                synchronized (mFileLock) {
656                    AtomicFile file = getFile();
657                    FileOutputStream f = null;
658                    try {
659                        f = file.startWrite();
660                        BufferedOutputStream out = new BufferedOutputStream(f);
661                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
662                        StringBuilder sb = new StringBuilder();
663                        for (PackageParser.Package pkg : mPackages.values()) {
664                            if (pkg.mLastPackageUsageTimeInMills == 0) {
665                                continue;
666                            }
667                            sb.setLength(0);
668                            sb.append(pkg.packageName);
669                            sb.append(' ');
670                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
671                            sb.append('\n');
672                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
673                        }
674                        out.flush();
675                        file.finishWrite(f);
676                    } catch (IOException e) {
677                        if (f != null) {
678                            file.failWrite(f);
679                        }
680                        Log.e(TAG, "Failed to write package usage times", e);
681                    }
682                }
683            }
684            mLastWritten.set(SystemClock.elapsedRealtime());
685        }
686
687        void readLP() {
688            synchronized (mFileLock) {
689                AtomicFile file = getFile();
690                BufferedInputStream in = null;
691                try {
692                    in = new BufferedInputStream(file.openRead());
693                    StringBuffer sb = new StringBuffer();
694                    while (true) {
695                        String packageName = readToken(in, sb, ' ');
696                        if (packageName == null) {
697                            break;
698                        }
699                        String timeInMillisString = readToken(in, sb, '\n');
700                        if (timeInMillisString == null) {
701                            throw new IOException("Failed to find last usage time for package "
702                                                  + packageName);
703                        }
704                        PackageParser.Package pkg = mPackages.get(packageName);
705                        if (pkg == null) {
706                            continue;
707                        }
708                        long timeInMillis;
709                        try {
710                            timeInMillis = Long.parseLong(timeInMillisString.toString());
711                        } catch (NumberFormatException e) {
712                            throw new IOException("Failed to parse " + timeInMillisString
713                                                  + " as a long.", e);
714                        }
715                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
716                    }
717                } catch (FileNotFoundException expected) {
718                    mIsHistoricalPackageUsageAvailable = false;
719                } catch (IOException e) {
720                    Log.w(TAG, "Failed to read package usage times", e);
721                } finally {
722                    IoUtils.closeQuietly(in);
723                }
724            }
725            mLastWritten.set(SystemClock.elapsedRealtime());
726        }
727
728        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
729                throws IOException {
730            sb.setLength(0);
731            while (true) {
732                int ch = in.read();
733                if (ch == -1) {
734                    if (sb.length() == 0) {
735                        return null;
736                    }
737                    throw new IOException("Unexpected EOF");
738                }
739                if (ch == endOfToken) {
740                    return sb.toString();
741                }
742                sb.append((char)ch);
743            }
744        }
745
746        private AtomicFile getFile() {
747            File dataDir = Environment.getDataDirectory();
748            File systemDir = new File(dataDir, "system");
749            File fname = new File(systemDir, "package-usage.list");
750            return new AtomicFile(fname);
751        }
752    }
753
754    class PackageHandler extends Handler {
755        private boolean mBound = false;
756        final ArrayList<HandlerParams> mPendingInstalls =
757            new ArrayList<HandlerParams>();
758
759        private boolean connectToService() {
760            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
761                    " DefaultContainerService");
762            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
763            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
764            if (mContext.bindServiceAsUser(service, mDefContainerConn,
765                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
766                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
767                mBound = true;
768                return true;
769            }
770            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
771            return false;
772        }
773
774        private void disconnectService() {
775            mContainerService = null;
776            mBound = false;
777            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
778            mContext.unbindService(mDefContainerConn);
779            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
780        }
781
782        PackageHandler(Looper looper) {
783            super(looper);
784        }
785
786        public void handleMessage(Message msg) {
787            try {
788                doHandleMessage(msg);
789            } finally {
790                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
791            }
792        }
793
794        void doHandleMessage(Message msg) {
795            switch (msg.what) {
796                case INIT_COPY: {
797                    HandlerParams params = (HandlerParams) msg.obj;
798                    int idx = mPendingInstalls.size();
799                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
800                    // If a bind was already initiated we dont really
801                    // need to do anything. The pending install
802                    // will be processed later on.
803                    if (!mBound) {
804                        // If this is the only one pending we might
805                        // have to bind to the service again.
806                        if (!connectToService()) {
807                            Slog.e(TAG, "Failed to bind to media container service");
808                            params.serviceError();
809                            return;
810                        } else {
811                            // Once we bind to the service, the first
812                            // pending request will be processed.
813                            mPendingInstalls.add(idx, params);
814                        }
815                    } else {
816                        mPendingInstalls.add(idx, params);
817                        // Already bound to the service. Just make
818                        // sure we trigger off processing the first request.
819                        if (idx == 0) {
820                            mHandler.sendEmptyMessage(MCS_BOUND);
821                        }
822                    }
823                    break;
824                }
825                case MCS_BOUND: {
826                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
827                    if (msg.obj != null) {
828                        mContainerService = (IMediaContainerService) msg.obj;
829                    }
830                    if (mContainerService == null) {
831                        // Something seriously wrong. Bail out
832                        Slog.e(TAG, "Cannot bind to media container service");
833                        for (HandlerParams params : mPendingInstalls) {
834                            // Indicate service bind error
835                            params.serviceError();
836                        }
837                        mPendingInstalls.clear();
838                    } else if (mPendingInstalls.size() > 0) {
839                        HandlerParams params = mPendingInstalls.get(0);
840                        if (params != null) {
841                            if (params.startCopy()) {
842                                // We are done...  look for more work or to
843                                // go idle.
844                                if (DEBUG_SD_INSTALL) Log.i(TAG,
845                                        "Checking for more work or unbind...");
846                                // Delete pending install
847                                if (mPendingInstalls.size() > 0) {
848                                    mPendingInstalls.remove(0);
849                                }
850                                if (mPendingInstalls.size() == 0) {
851                                    if (mBound) {
852                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
853                                                "Posting delayed MCS_UNBIND");
854                                        removeMessages(MCS_UNBIND);
855                                        Message ubmsg = obtainMessage(MCS_UNBIND);
856                                        // Unbind after a little delay, to avoid
857                                        // continual thrashing.
858                                        sendMessageDelayed(ubmsg, 10000);
859                                    }
860                                } else {
861                                    // There are more pending requests in queue.
862                                    // Just post MCS_BOUND message to trigger processing
863                                    // of next pending install.
864                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
865                                            "Posting MCS_BOUND for next work");
866                                    mHandler.sendEmptyMessage(MCS_BOUND);
867                                }
868                            }
869                        }
870                    } else {
871                        // Should never happen ideally.
872                        Slog.w(TAG, "Empty queue");
873                    }
874                    break;
875                }
876                case MCS_RECONNECT: {
877                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
878                    if (mPendingInstalls.size() > 0) {
879                        if (mBound) {
880                            disconnectService();
881                        }
882                        if (!connectToService()) {
883                            Slog.e(TAG, "Failed to bind to media container service");
884                            for (HandlerParams params : mPendingInstalls) {
885                                // Indicate service bind error
886                                params.serviceError();
887                            }
888                            mPendingInstalls.clear();
889                        }
890                    }
891                    break;
892                }
893                case MCS_UNBIND: {
894                    // If there is no actual work left, then time to unbind.
895                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
896
897                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
898                        if (mBound) {
899                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
900
901                            disconnectService();
902                        }
903                    } else if (mPendingInstalls.size() > 0) {
904                        // There are more pending requests in queue.
905                        // Just post MCS_BOUND message to trigger processing
906                        // of next pending install.
907                        mHandler.sendEmptyMessage(MCS_BOUND);
908                    }
909
910                    break;
911                }
912                case MCS_GIVE_UP: {
913                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
914                    mPendingInstalls.remove(0);
915                    break;
916                }
917                case SEND_PENDING_BROADCAST: {
918                    String packages[];
919                    ArrayList<String> components[];
920                    int size = 0;
921                    int uids[];
922                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
923                    synchronized (mPackages) {
924                        if (mPendingBroadcasts == null) {
925                            return;
926                        }
927                        size = mPendingBroadcasts.size();
928                        if (size <= 0) {
929                            // Nothing to be done. Just return
930                            return;
931                        }
932                        packages = new String[size];
933                        components = new ArrayList[size];
934                        uids = new int[size];
935                        int i = 0;  // filling out the above arrays
936
937                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
938                            int packageUserId = mPendingBroadcasts.userIdAt(n);
939                            Iterator<Map.Entry<String, ArrayList<String>>> it
940                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
941                                            .entrySet().iterator();
942                            while (it.hasNext() && i < size) {
943                                Map.Entry<String, ArrayList<String>> ent = it.next();
944                                packages[i] = ent.getKey();
945                                components[i] = ent.getValue();
946                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
947                                uids[i] = (ps != null)
948                                        ? UserHandle.getUid(packageUserId, ps.appId)
949                                        : -1;
950                                i++;
951                            }
952                        }
953                        size = i;
954                        mPendingBroadcasts.clear();
955                    }
956                    // Send broadcasts
957                    for (int i = 0; i < size; i++) {
958                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
959                    }
960                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
961                    break;
962                }
963                case START_CLEANING_PACKAGE: {
964                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
965                    final String packageName = (String)msg.obj;
966                    final int userId = msg.arg1;
967                    final boolean andCode = msg.arg2 != 0;
968                    synchronized (mPackages) {
969                        if (userId == UserHandle.USER_ALL) {
970                            int[] users = sUserManager.getUserIds();
971                            for (int user : users) {
972                                mSettings.addPackageToCleanLPw(
973                                        new PackageCleanItem(user, packageName, andCode));
974                            }
975                        } else {
976                            mSettings.addPackageToCleanLPw(
977                                    new PackageCleanItem(userId, packageName, andCode));
978                        }
979                    }
980                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
981                    startCleaningPackages();
982                } break;
983                case POST_INSTALL: {
984                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
985                    PostInstallData data = mRunningInstalls.get(msg.arg1);
986                    mRunningInstalls.delete(msg.arg1);
987                    boolean deleteOld = false;
988
989                    if (data != null) {
990                        InstallArgs args = data.args;
991                        PackageInstalledInfo res = data.res;
992
993                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
994                            res.removedInfo.sendBroadcast(false, true, false);
995                            Bundle extras = new Bundle(1);
996                            extras.putInt(Intent.EXTRA_UID, res.uid);
997                            // Determine the set of users who are adding this
998                            // package for the first time vs. those who are seeing
999                            // an update.
1000                            int[] firstUsers;
1001                            int[] updateUsers = new int[0];
1002                            if (res.origUsers == null || res.origUsers.length == 0) {
1003                                firstUsers = res.newUsers;
1004                            } else {
1005                                firstUsers = new int[0];
1006                                for (int i=0; i<res.newUsers.length; i++) {
1007                                    int user = res.newUsers[i];
1008                                    boolean isNew = true;
1009                                    for (int j=0; j<res.origUsers.length; j++) {
1010                                        if (res.origUsers[j] == user) {
1011                                            isNew = false;
1012                                            break;
1013                                        }
1014                                    }
1015                                    if (isNew) {
1016                                        int[] newFirst = new int[firstUsers.length+1];
1017                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1018                                                firstUsers.length);
1019                                        newFirst[firstUsers.length] = user;
1020                                        firstUsers = newFirst;
1021                                    } else {
1022                                        int[] newUpdate = new int[updateUsers.length+1];
1023                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1024                                                updateUsers.length);
1025                                        newUpdate[updateUsers.length] = user;
1026                                        updateUsers = newUpdate;
1027                                    }
1028                                }
1029                            }
1030                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1031                                    res.pkg.applicationInfo.packageName,
1032                                    extras, null, null, firstUsers);
1033                            final boolean update = res.removedInfo.removedPackage != null;
1034                            if (update) {
1035                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1036                            }
1037                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1038                                    res.pkg.applicationInfo.packageName,
1039                                    extras, null, null, updateUsers);
1040                            if (update) {
1041                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1042                                        res.pkg.applicationInfo.packageName,
1043                                        extras, null, null, updateUsers);
1044                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1045                                        null, null,
1046                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1047
1048                                // treat asec-hosted packages like removable media on upgrade
1049                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1050                                    if (DEBUG_INSTALL) {
1051                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1052                                                + " is ASEC-hosted -> AVAILABLE");
1053                                    }
1054                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1055                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1056                                    pkgList.add(res.pkg.applicationInfo.packageName);
1057                                    sendResourcesChangedBroadcast(true, true,
1058                                            pkgList,uidArray, null);
1059                                }
1060                            }
1061                            if (res.removedInfo.args != null) {
1062                                // Remove the replaced package's older resources safely now
1063                                deleteOld = true;
1064                            }
1065
1066                            // Log current value of "unknown sources" setting
1067                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1068                                getUnknownSourcesSettings());
1069                        }
1070                        // Force a gc to clear up things
1071                        Runtime.getRuntime().gc();
1072                        // We delete after a gc for applications  on sdcard.
1073                        if (deleteOld) {
1074                            synchronized (mInstallLock) {
1075                                res.removedInfo.args.doPostDeleteLI(true);
1076                            }
1077                        }
1078                        if (args.observer != null) {
1079                            try {
1080                                Bundle extras = extrasForInstallResult(res);
1081                                args.observer.onPackageInstalled(res.name, res.returnCode,
1082                                        res.returnMsg, extras);
1083                            } catch (RemoteException e) {
1084                                Slog.i(TAG, "Observer no longer exists.");
1085                            }
1086                        }
1087                    } else {
1088                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1089                    }
1090                } break;
1091                case UPDATED_MEDIA_STATUS: {
1092                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1093                    boolean reportStatus = msg.arg1 == 1;
1094                    boolean doGc = msg.arg2 == 1;
1095                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1096                    if (doGc) {
1097                        // Force a gc to clear up stale containers.
1098                        Runtime.getRuntime().gc();
1099                    }
1100                    if (msg.obj != null) {
1101                        @SuppressWarnings("unchecked")
1102                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1103                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1104                        // Unload containers
1105                        unloadAllContainers(args);
1106                    }
1107                    if (reportStatus) {
1108                        try {
1109                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1110                            PackageHelper.getMountService().finishMediaUpdate();
1111                        } catch (RemoteException e) {
1112                            Log.e(TAG, "MountService not running?");
1113                        }
1114                    }
1115                } break;
1116                case WRITE_SETTINGS: {
1117                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1118                    synchronized (mPackages) {
1119                        removeMessages(WRITE_SETTINGS);
1120                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1121                        mSettings.writeLPr();
1122                        mDirtyUsers.clear();
1123                    }
1124                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1125                } break;
1126                case WRITE_PACKAGE_RESTRICTIONS: {
1127                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1128                    synchronized (mPackages) {
1129                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1130                        for (int userId : mDirtyUsers) {
1131                            mSettings.writePackageRestrictionsLPr(userId);
1132                        }
1133                        mDirtyUsers.clear();
1134                    }
1135                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1136                } break;
1137                case CHECK_PENDING_VERIFICATION: {
1138                    final int verificationId = msg.arg1;
1139                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1140
1141                    if ((state != null) && !state.timeoutExtended()) {
1142                        final InstallArgs args = state.getInstallArgs();
1143                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1144
1145                        Slog.i(TAG, "Verification timed out for " + originUri);
1146                        mPendingVerification.remove(verificationId);
1147
1148                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1149
1150                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1151                            Slog.i(TAG, "Continuing with installation of " + originUri);
1152                            state.setVerifierResponse(Binder.getCallingUid(),
1153                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1154                            broadcastPackageVerified(verificationId, originUri,
1155                                    PackageManager.VERIFICATION_ALLOW,
1156                                    state.getInstallArgs().getUser());
1157                            try {
1158                                ret = args.copyApk(mContainerService, true);
1159                            } catch (RemoteException e) {
1160                                Slog.e(TAG, "Could not contact the ContainerService");
1161                            }
1162                        } else {
1163                            broadcastPackageVerified(verificationId, originUri,
1164                                    PackageManager.VERIFICATION_REJECT,
1165                                    state.getInstallArgs().getUser());
1166                        }
1167
1168                        processPendingInstall(args, ret);
1169                        mHandler.sendEmptyMessage(MCS_UNBIND);
1170                    }
1171                    break;
1172                }
1173                case PACKAGE_VERIFIED: {
1174                    final int verificationId = msg.arg1;
1175
1176                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1177                    if (state == null) {
1178                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1179                        break;
1180                    }
1181
1182                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1183
1184                    state.setVerifierResponse(response.callerUid, response.code);
1185
1186                    if (state.isVerificationComplete()) {
1187                        mPendingVerification.remove(verificationId);
1188
1189                        final InstallArgs args = state.getInstallArgs();
1190                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1191
1192                        int ret;
1193                        if (state.isInstallAllowed()) {
1194                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1195                            broadcastPackageVerified(verificationId, originUri,
1196                                    response.code, state.getInstallArgs().getUser());
1197                            try {
1198                                ret = args.copyApk(mContainerService, true);
1199                            } catch (RemoteException e) {
1200                                Slog.e(TAG, "Could not contact the ContainerService");
1201                            }
1202                        } else {
1203                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1204                        }
1205
1206                        processPendingInstall(args, ret);
1207
1208                        mHandler.sendEmptyMessage(MCS_UNBIND);
1209                    }
1210
1211                    break;
1212                }
1213            }
1214        }
1215    }
1216
1217    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1218        Bundle extras = null;
1219        switch (res.returnCode) {
1220            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1221                extras = new Bundle();
1222                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1223                        res.origPermission);
1224                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1225                        res.origPackage);
1226                break;
1227            }
1228        }
1229        return extras;
1230    }
1231
1232    void scheduleWriteSettingsLocked() {
1233        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1234            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1235        }
1236    }
1237
1238    void scheduleWritePackageRestrictionsLocked(int userId) {
1239        if (!sUserManager.exists(userId)) return;
1240        mDirtyUsers.add(userId);
1241        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1242            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1243        }
1244    }
1245
1246    public static final PackageManagerService main(Context context, Installer installer,
1247            boolean factoryTest, boolean onlyCore) {
1248        PackageManagerService m = new PackageManagerService(context, installer,
1249                factoryTest, onlyCore);
1250        ServiceManager.addService("package", m);
1251        return m;
1252    }
1253
1254    static String[] splitString(String str, char sep) {
1255        int count = 1;
1256        int i = 0;
1257        while ((i=str.indexOf(sep, i)) >= 0) {
1258            count++;
1259            i++;
1260        }
1261
1262        String[] res = new String[count];
1263        i=0;
1264        count = 0;
1265        int lastI=0;
1266        while ((i=str.indexOf(sep, i)) >= 0) {
1267            res[count] = str.substring(lastI, i);
1268            count++;
1269            i++;
1270            lastI = i;
1271        }
1272        res[count] = str.substring(lastI, str.length());
1273        return res;
1274    }
1275
1276    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1277        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1278                Context.DISPLAY_SERVICE);
1279        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1280    }
1281
1282    public PackageManagerService(Context context, Installer installer,
1283            boolean factoryTest, boolean onlyCore) {
1284        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1285                SystemClock.uptimeMillis());
1286
1287        if (mSdkVersion <= 0) {
1288            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1289        }
1290
1291        mContext = context;
1292        mFactoryTest = factoryTest;
1293        mOnlyCore = onlyCore;
1294        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1295        mMetrics = new DisplayMetrics();
1296        mSettings = new Settings(context);
1297        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1298                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1299        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1300                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1301        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1302                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1303        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1304                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1305        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1306                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1307        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1308                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1309
1310        // TODO: add a property to control this?
1311        long dexOptLRUThresholdInMinutes;
1312        if (mLazyDexOpt) {
1313            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1314        } else {
1315            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1316        }
1317        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1318
1319        String separateProcesses = SystemProperties.get("debug.separate_processes");
1320        if (separateProcesses != null && separateProcesses.length() > 0) {
1321            if ("*".equals(separateProcesses)) {
1322                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1323                mSeparateProcesses = null;
1324                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1325            } else {
1326                mDefParseFlags = 0;
1327                mSeparateProcesses = separateProcesses.split(",");
1328                Slog.w(TAG, "Running with debug.separate_processes: "
1329                        + separateProcesses);
1330            }
1331        } else {
1332            mDefParseFlags = 0;
1333            mSeparateProcesses = null;
1334        }
1335
1336        mInstaller = installer;
1337        mPackageDexOptimizer = new PackageDexOptimizer(this);
1338
1339        getDefaultDisplayMetrics(context, mMetrics);
1340
1341        SystemConfig systemConfig = SystemConfig.getInstance();
1342        mGlobalGids = systemConfig.getGlobalGids();
1343        mSystemPermissions = systemConfig.getSystemPermissions();
1344        mAvailableFeatures = systemConfig.getAvailableFeatures();
1345
1346        synchronized (mInstallLock) {
1347        // writer
1348        synchronized (mPackages) {
1349            mHandlerThread = new ServiceThread(TAG,
1350                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1351            mHandlerThread.start();
1352            mHandler = new PackageHandler(mHandlerThread.getLooper());
1353            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1354
1355            File dataDir = Environment.getDataDirectory();
1356            mAppDataDir = new File(dataDir, "data");
1357            mAppInstallDir = new File(dataDir, "app");
1358            mAppLib32InstallDir = new File(dataDir, "app-lib");
1359            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1360            mUserAppDataDir = new File(dataDir, "user");
1361            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1362
1363            sUserManager = new UserManagerService(context, this,
1364                    mInstallLock, mPackages);
1365
1366            // Propagate permission configuration in to package manager.
1367            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1368                    = systemConfig.getPermissions();
1369            for (int i=0; i<permConfig.size(); i++) {
1370                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1371                BasePermission bp = mSettings.mPermissions.get(perm.name);
1372                if (bp == null) {
1373                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1374                    mSettings.mPermissions.put(perm.name, bp);
1375                }
1376                if (perm.gids != null) {
1377                    bp.gids = appendInts(bp.gids, perm.gids);
1378                }
1379            }
1380
1381            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1382            for (int i=0; i<libConfig.size(); i++) {
1383                mSharedLibraries.put(libConfig.keyAt(i),
1384                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1385            }
1386
1387            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1388
1389            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1390                    mSdkVersion, mOnlyCore);
1391
1392            String customResolverActivity = Resources.getSystem().getString(
1393                    R.string.config_customResolverActivity);
1394            if (TextUtils.isEmpty(customResolverActivity)) {
1395                customResolverActivity = null;
1396            } else {
1397                mCustomResolverComponentName = ComponentName.unflattenFromString(
1398                        customResolverActivity);
1399            }
1400
1401            long startTime = SystemClock.uptimeMillis();
1402
1403            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1404                    startTime);
1405
1406            // Set flag to monitor and not change apk file paths when
1407            // scanning install directories.
1408            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1409
1410            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1411
1412            /**
1413             * Add everything in the in the boot class path to the
1414             * list of process files because dexopt will have been run
1415             * if necessary during zygote startup.
1416             */
1417            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1418            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1419
1420            if (bootClassPath != null) {
1421                String[] bootClassPathElements = splitString(bootClassPath, ':');
1422                for (String element : bootClassPathElements) {
1423                    alreadyDexOpted.add(element);
1424                }
1425            } else {
1426                Slog.w(TAG, "No BOOTCLASSPATH found!");
1427            }
1428
1429            if (systemServerClassPath != null) {
1430                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1431                for (String element : systemServerClassPathElements) {
1432                    alreadyDexOpted.add(element);
1433                }
1434            } else {
1435                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1436            }
1437
1438            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1439            final String[] dexCodeInstructionSets =
1440                    getDexCodeInstructionSets(
1441                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1442
1443            /**
1444             * Ensure all external libraries have had dexopt run on them.
1445             */
1446            if (mSharedLibraries.size() > 0) {
1447                // NOTE: For now, we're compiling these system "shared libraries"
1448                // (and framework jars) into all available architectures. It's possible
1449                // to compile them only when we come across an app that uses them (there's
1450                // already logic for that in scanPackageLI) but that adds some complexity.
1451                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1452                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1453                        final String lib = libEntry.path;
1454                        if (lib == null) {
1455                            continue;
1456                        }
1457
1458                        try {
1459                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1460                                                                                 dexCodeInstructionSet,
1461                                                                                 false);
1462                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1463                                alreadyDexOpted.add(lib);
1464
1465                                // The list of "shared libraries" we have at this point is
1466                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1467                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1468                                } else {
1469                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1470                                }
1471                            }
1472                        } catch (FileNotFoundException e) {
1473                            Slog.w(TAG, "Library not found: " + lib);
1474                        } catch (IOException e) {
1475                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1476                                    + e.getMessage());
1477                        }
1478                    }
1479                }
1480            }
1481
1482            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1483
1484            // Gross hack for now: we know this file doesn't contain any
1485            // code, so don't dexopt it to avoid the resulting log spew.
1486            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1487
1488            // Gross hack for now: we know this file is only part of
1489            // the boot class path for art, so don't dexopt it to
1490            // avoid the resulting log spew.
1491            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1492
1493            /**
1494             * And there are a number of commands implemented in Java, which
1495             * we currently need to do the dexopt on so that they can be
1496             * run from a non-root shell.
1497             */
1498            String[] frameworkFiles = frameworkDir.list();
1499            if (frameworkFiles != null) {
1500                // TODO: We could compile these only for the most preferred ABI. We should
1501                // first double check that the dex files for these commands are not referenced
1502                // by other system apps.
1503                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1504                    for (int i=0; i<frameworkFiles.length; i++) {
1505                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1506                        String path = libPath.getPath();
1507                        // Skip the file if we already did it.
1508                        if (alreadyDexOpted.contains(path)) {
1509                            continue;
1510                        }
1511                        // Skip the file if it is not a type we want to dexopt.
1512                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1513                            continue;
1514                        }
1515                        try {
1516                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1517                                                                                 dexCodeInstructionSet,
1518                                                                                 false);
1519                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1520                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1521                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1522                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1523                            }
1524                        } catch (FileNotFoundException e) {
1525                            Slog.w(TAG, "Jar not found: " + path);
1526                        } catch (IOException e) {
1527                            Slog.w(TAG, "Exception reading jar: " + path, e);
1528                        }
1529                    }
1530                }
1531            }
1532
1533            // Collect vendor overlay packages.
1534            // (Do this before scanning any apps.)
1535            // For security and version matching reason, only consider
1536            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1537            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1538            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1539                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1540
1541            // Find base frameworks (resource packages without code).
1542            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1543                    | PackageParser.PARSE_IS_SYSTEM_DIR
1544                    | PackageParser.PARSE_IS_PRIVILEGED,
1545                    scanFlags | SCAN_NO_DEX, 0);
1546
1547            // Collected privileged system packages.
1548            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1549            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1550                    | PackageParser.PARSE_IS_SYSTEM_DIR
1551                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1552
1553            // Collect ordinary system packages.
1554            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1555            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1556                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1557
1558            // Collect all vendor packages.
1559            File vendorAppDir = new File("/vendor/app");
1560            try {
1561                vendorAppDir = vendorAppDir.getCanonicalFile();
1562            } catch (IOException e) {
1563                // failed to look up canonical path, continue with original one
1564            }
1565            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1566                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1567
1568            // Collect all OEM packages.
1569            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1570            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1571                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1572
1573            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1574            mInstaller.moveFiles();
1575
1576            // Prune any system packages that no longer exist.
1577            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1578            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1579            if (!mOnlyCore) {
1580                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1581                while (psit.hasNext()) {
1582                    PackageSetting ps = psit.next();
1583
1584                    /*
1585                     * If this is not a system app, it can't be a
1586                     * disable system app.
1587                     */
1588                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1589                        continue;
1590                    }
1591
1592                    /*
1593                     * If the package is scanned, it's not erased.
1594                     */
1595                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1596                    if (scannedPkg != null) {
1597                        /*
1598                         * If the system app is both scanned and in the
1599                         * disabled packages list, then it must have been
1600                         * added via OTA. Remove it from the currently
1601                         * scanned package so the previously user-installed
1602                         * application can be scanned.
1603                         */
1604                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1605                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1606                                    + ps.name + "; removing system app.  Last known codePath="
1607                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1608                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1609                                    + scannedPkg.mVersionCode);
1610                            removePackageLI(ps, true);
1611                            expectingBetter.put(ps.name, ps.codePath);
1612                        }
1613
1614                        continue;
1615                    }
1616
1617                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1618                        psit.remove();
1619                        logCriticalInfo(Log.WARN, "System package " + ps.name
1620                                + " no longer exists; wiping its data");
1621                        removeDataDirsLI(ps.name);
1622                    } else {
1623                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1624                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1625                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1626                        }
1627                    }
1628                }
1629            }
1630
1631            //look for any incomplete package installations
1632            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1633            //clean up list
1634            for(int i = 0; i < deletePkgsList.size(); i++) {
1635                //clean up here
1636                cleanupInstallFailedPackage(deletePkgsList.get(i));
1637            }
1638            //delete tmp files
1639            deleteTempPackageFiles();
1640
1641            // Remove any shared userIDs that have no associated packages
1642            mSettings.pruneSharedUsersLPw();
1643
1644            if (!mOnlyCore) {
1645                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1646                        SystemClock.uptimeMillis());
1647                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1648
1649                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1650                        scanFlags, 0);
1651
1652                /**
1653                 * Remove disable package settings for any updated system
1654                 * apps that were removed via an OTA. If they're not a
1655                 * previously-updated app, remove them completely.
1656                 * Otherwise, just revoke their system-level permissions.
1657                 */
1658                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1659                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1660                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1661
1662                    String msg;
1663                    if (deletedPkg == null) {
1664                        msg = "Updated system package " + deletedAppName
1665                                + " no longer exists; wiping its data";
1666                        removeDataDirsLI(deletedAppName);
1667                    } else {
1668                        msg = "Updated system app + " + deletedAppName
1669                                + " no longer present; removing system privileges for "
1670                                + deletedAppName;
1671
1672                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1673
1674                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1675                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1676                    }
1677                    logCriticalInfo(Log.WARN, msg);
1678                }
1679
1680                /**
1681                 * Make sure all system apps that we expected to appear on
1682                 * the userdata partition actually showed up. If they never
1683                 * appeared, crawl back and revive the system version.
1684                 */
1685                for (int i = 0; i < expectingBetter.size(); i++) {
1686                    final String packageName = expectingBetter.keyAt(i);
1687                    if (!mPackages.containsKey(packageName)) {
1688                        final File scanFile = expectingBetter.valueAt(i);
1689
1690                        logCriticalInfo(Log.WARN, "Expected better " + packageName
1691                                + " but never showed up; reverting to system");
1692
1693                        final int reparseFlags;
1694                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
1695                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1696                                    | PackageParser.PARSE_IS_SYSTEM_DIR
1697                                    | PackageParser.PARSE_IS_PRIVILEGED;
1698                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
1699                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1700                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1701                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
1702                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1703                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1704                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
1705                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1706                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1707                        } else {
1708                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
1709                            continue;
1710                        }
1711
1712                        mSettings.enableSystemPackageLPw(packageName);
1713
1714                        try {
1715                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
1716                        } catch (PackageManagerException e) {
1717                            Slog.e(TAG, "Failed to parse original system package: "
1718                                    + e.getMessage());
1719                        }
1720                    }
1721                }
1722            }
1723
1724            // Now that we know all of the shared libraries, update all clients to have
1725            // the correct library paths.
1726            updateAllSharedLibrariesLPw();
1727
1728            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1729                // NOTE: We ignore potential failures here during a system scan (like
1730                // the rest of the commands above) because there's precious little we
1731                // can do about it. A settings error is reported, though.
1732                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1733                        false /* force dexopt */, false /* defer dexopt */);
1734            }
1735
1736            // Now that we know all the packages we are keeping,
1737            // read and update their last usage times.
1738            mPackageUsage.readLP();
1739
1740            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1741                    SystemClock.uptimeMillis());
1742            Slog.i(TAG, "Time to scan packages: "
1743                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1744                    + " seconds");
1745
1746            // If the platform SDK has changed since the last time we booted,
1747            // we need to re-grant app permission to catch any new ones that
1748            // appear.  This is really a hack, and means that apps can in some
1749            // cases get permissions that the user didn't initially explicitly
1750            // allow...  it would be nice to have some better way to handle
1751            // this situation.
1752            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1753                    != mSdkVersion;
1754            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1755                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1756                    + "; regranting permissions for internal storage");
1757            mSettings.mInternalSdkPlatform = mSdkVersion;
1758
1759            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1760                    | (regrantPermissions
1761                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1762                            : 0));
1763
1764            // If this is the first boot, and it is a normal boot, then
1765            // we need to initialize the default preferred apps.
1766            if (!mRestoredSettings && !onlyCore) {
1767                mSettings.readDefaultPreferredAppsLPw(this, 0);
1768            }
1769
1770            // If this is first boot after an OTA, and a normal boot, then
1771            // we need to clear code cache directories.
1772            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
1773            if (mIsUpgrade && !onlyCore) {
1774                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1775                for (String pkgName : mSettings.mPackages.keySet()) {
1776                    deleteCodeCacheDirsLI(pkgName);
1777                }
1778                mSettings.mFingerprint = Build.FINGERPRINT;
1779            }
1780
1781            // All the changes are done during package scanning.
1782            mSettings.updateInternalDatabaseVersion();
1783
1784            // can downgrade to reader
1785            mSettings.writeLPr();
1786
1787            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1788                    SystemClock.uptimeMillis());
1789
1790
1791            mRequiredVerifierPackage = getRequiredVerifierLPr();
1792        } // synchronized (mPackages)
1793        } // synchronized (mInstallLock)
1794
1795        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1796
1797        // Now after opening every single application zip, make sure they
1798        // are all flushed.  Not really needed, but keeps things nice and
1799        // tidy.
1800        Runtime.getRuntime().gc();
1801    }
1802
1803    @Override
1804    public boolean isFirstBoot() {
1805        return !mRestoredSettings;
1806    }
1807
1808    @Override
1809    public boolean isOnlyCoreApps() {
1810        return mOnlyCore;
1811    }
1812
1813    @Override
1814    public boolean isUpgrade() {
1815        return mIsUpgrade;
1816    }
1817
1818    private String getRequiredVerifierLPr() {
1819        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1820        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1821                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1822
1823        String requiredVerifier = null;
1824
1825        final int N = receivers.size();
1826        for (int i = 0; i < N; i++) {
1827            final ResolveInfo info = receivers.get(i);
1828
1829            if (info.activityInfo == null) {
1830                continue;
1831            }
1832
1833            final String packageName = info.activityInfo.packageName;
1834
1835            final PackageSetting ps = mSettings.mPackages.get(packageName);
1836            if (ps == null) {
1837                continue;
1838            }
1839
1840            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1841            if (!gp.grantedPermissions
1842                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1843                continue;
1844            }
1845
1846            if (requiredVerifier != null) {
1847                throw new RuntimeException("There can be only one required verifier");
1848            }
1849
1850            requiredVerifier = packageName;
1851        }
1852
1853        return requiredVerifier;
1854    }
1855
1856    @Override
1857    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1858            throws RemoteException {
1859        try {
1860            return super.onTransact(code, data, reply, flags);
1861        } catch (RuntimeException e) {
1862            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1863                Slog.wtf(TAG, "Package Manager Crash", e);
1864            }
1865            throw e;
1866        }
1867    }
1868
1869    void cleanupInstallFailedPackage(PackageSetting ps) {
1870        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
1871
1872        removeDataDirsLI(ps.name);
1873        if (ps.codePath != null) {
1874            if (ps.codePath.isDirectory()) {
1875                FileUtils.deleteContents(ps.codePath);
1876            }
1877            ps.codePath.delete();
1878        }
1879        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1880            if (ps.resourcePath.isDirectory()) {
1881                FileUtils.deleteContents(ps.resourcePath);
1882            }
1883            ps.resourcePath.delete();
1884        }
1885        mSettings.removePackageLPw(ps.name);
1886    }
1887
1888    static int[] appendInts(int[] cur, int[] add) {
1889        if (add == null) return cur;
1890        if (cur == null) return add;
1891        final int N = add.length;
1892        for (int i=0; i<N; i++) {
1893            cur = appendInt(cur, add[i]);
1894        }
1895        return cur;
1896    }
1897
1898    static int[] removeInts(int[] cur, int[] rem) {
1899        if (rem == null) return cur;
1900        if (cur == null) return cur;
1901        final int N = rem.length;
1902        for (int i=0; i<N; i++) {
1903            cur = removeInt(cur, rem[i]);
1904        }
1905        return cur;
1906    }
1907
1908    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1909        if (!sUserManager.exists(userId)) return null;
1910        final PackageSetting ps = (PackageSetting) p.mExtras;
1911        if (ps == null) {
1912            return null;
1913        }
1914        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1915        final PackageUserState state = ps.readUserState(userId);
1916        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1917                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1918                state, userId);
1919    }
1920
1921    @Override
1922    public boolean isPackageAvailable(String packageName, int userId) {
1923        if (!sUserManager.exists(userId)) return false;
1924        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
1925        synchronized (mPackages) {
1926            PackageParser.Package p = mPackages.get(packageName);
1927            if (p != null) {
1928                final PackageSetting ps = (PackageSetting) p.mExtras;
1929                if (ps != null) {
1930                    final PackageUserState state = ps.readUserState(userId);
1931                    if (state != null) {
1932                        return PackageParser.isAvailable(state);
1933                    }
1934                }
1935            }
1936        }
1937        return false;
1938    }
1939
1940    @Override
1941    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1942        if (!sUserManager.exists(userId)) return null;
1943        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
1944        // reader
1945        synchronized (mPackages) {
1946            PackageParser.Package p = mPackages.get(packageName);
1947            if (DEBUG_PACKAGE_INFO)
1948                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1949            if (p != null) {
1950                return generatePackageInfo(p, flags, userId);
1951            }
1952            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1953                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1954            }
1955        }
1956        return null;
1957    }
1958
1959    @Override
1960    public String[] currentToCanonicalPackageNames(String[] names) {
1961        String[] out = new String[names.length];
1962        // reader
1963        synchronized (mPackages) {
1964            for (int i=names.length-1; i>=0; i--) {
1965                PackageSetting ps = mSettings.mPackages.get(names[i]);
1966                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1967            }
1968        }
1969        return out;
1970    }
1971
1972    @Override
1973    public String[] canonicalToCurrentPackageNames(String[] names) {
1974        String[] out = new String[names.length];
1975        // reader
1976        synchronized (mPackages) {
1977            for (int i=names.length-1; i>=0; i--) {
1978                String cur = mSettings.mRenamedPackages.get(names[i]);
1979                out[i] = cur != null ? cur : names[i];
1980            }
1981        }
1982        return out;
1983    }
1984
1985    @Override
1986    public int getPackageUid(String packageName, int userId) {
1987        if (!sUserManager.exists(userId)) return -1;
1988        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
1989        // reader
1990        synchronized (mPackages) {
1991            PackageParser.Package p = mPackages.get(packageName);
1992            if(p != null) {
1993                return UserHandle.getUid(userId, p.applicationInfo.uid);
1994            }
1995            PackageSetting ps = mSettings.mPackages.get(packageName);
1996            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1997                return -1;
1998            }
1999            p = ps.pkg;
2000            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2001        }
2002    }
2003
2004    @Override
2005    public int[] getPackageGids(String packageName) {
2006        // reader
2007        synchronized (mPackages) {
2008            PackageParser.Package p = mPackages.get(packageName);
2009            if (DEBUG_PACKAGE_INFO)
2010                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2011            if (p != null) {
2012                final PackageSetting ps = (PackageSetting)p.mExtras;
2013                return ps.getGids();
2014            }
2015        }
2016        // stupid thing to indicate an error.
2017        return new int[0];
2018    }
2019
2020    static final PermissionInfo generatePermissionInfo(
2021            BasePermission bp, int flags) {
2022        if (bp.perm != null) {
2023            return PackageParser.generatePermissionInfo(bp.perm, flags);
2024        }
2025        PermissionInfo pi = new PermissionInfo();
2026        pi.name = bp.name;
2027        pi.packageName = bp.sourcePackage;
2028        pi.nonLocalizedLabel = bp.name;
2029        pi.protectionLevel = bp.protectionLevel;
2030        return pi;
2031    }
2032
2033    @Override
2034    public PermissionInfo getPermissionInfo(String name, int flags) {
2035        // reader
2036        synchronized (mPackages) {
2037            final BasePermission p = mSettings.mPermissions.get(name);
2038            if (p != null) {
2039                return generatePermissionInfo(p, flags);
2040            }
2041            return null;
2042        }
2043    }
2044
2045    @Override
2046    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2047        // reader
2048        synchronized (mPackages) {
2049            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2050            for (BasePermission p : mSettings.mPermissions.values()) {
2051                if (group == null) {
2052                    if (p.perm == null || p.perm.info.group == null) {
2053                        out.add(generatePermissionInfo(p, flags));
2054                    }
2055                } else {
2056                    if (p.perm != null && group.equals(p.perm.info.group)) {
2057                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2058                    }
2059                }
2060            }
2061
2062            if (out.size() > 0) {
2063                return out;
2064            }
2065            return mPermissionGroups.containsKey(group) ? out : null;
2066        }
2067    }
2068
2069    @Override
2070    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2071        // reader
2072        synchronized (mPackages) {
2073            return PackageParser.generatePermissionGroupInfo(
2074                    mPermissionGroups.get(name), flags);
2075        }
2076    }
2077
2078    @Override
2079    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2080        // reader
2081        synchronized (mPackages) {
2082            final int N = mPermissionGroups.size();
2083            ArrayList<PermissionGroupInfo> out
2084                    = new ArrayList<PermissionGroupInfo>(N);
2085            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2086                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2087            }
2088            return out;
2089        }
2090    }
2091
2092    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2093            int userId) {
2094        if (!sUserManager.exists(userId)) return null;
2095        PackageSetting ps = mSettings.mPackages.get(packageName);
2096        if (ps != null) {
2097            if (ps.pkg == null) {
2098                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2099                        flags, userId);
2100                if (pInfo != null) {
2101                    return pInfo.applicationInfo;
2102                }
2103                return null;
2104            }
2105            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2106                    ps.readUserState(userId), userId);
2107        }
2108        return null;
2109    }
2110
2111    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2112            int userId) {
2113        if (!sUserManager.exists(userId)) return null;
2114        PackageSetting ps = mSettings.mPackages.get(packageName);
2115        if (ps != null) {
2116            PackageParser.Package pkg = ps.pkg;
2117            if (pkg == null) {
2118                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2119                    return null;
2120                }
2121                // Only data remains, so we aren't worried about code paths
2122                pkg = new PackageParser.Package(packageName);
2123                pkg.applicationInfo.packageName = packageName;
2124                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2125                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2126                pkg.applicationInfo.dataDir =
2127                        getDataPathForPackage(packageName, 0).getPath();
2128                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2129                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2130            }
2131            return generatePackageInfo(pkg, flags, userId);
2132        }
2133        return null;
2134    }
2135
2136    @Override
2137    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2138        if (!sUserManager.exists(userId)) return null;
2139        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2140        // writer
2141        synchronized (mPackages) {
2142            PackageParser.Package p = mPackages.get(packageName);
2143            if (DEBUG_PACKAGE_INFO) Log.v(
2144                    TAG, "getApplicationInfo " + packageName
2145                    + ": " + p);
2146            if (p != null) {
2147                PackageSetting ps = mSettings.mPackages.get(packageName);
2148                if (ps == null) return null;
2149                // Note: isEnabledLP() does not apply here - always return info
2150                return PackageParser.generateApplicationInfo(
2151                        p, flags, ps.readUserState(userId), userId);
2152            }
2153            if ("android".equals(packageName)||"system".equals(packageName)) {
2154                return mAndroidApplication;
2155            }
2156            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2157                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2158            }
2159        }
2160        return null;
2161    }
2162
2163
2164    @Override
2165    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2166        mContext.enforceCallingOrSelfPermission(
2167                android.Manifest.permission.CLEAR_APP_CACHE, null);
2168        // Queue up an async operation since clearing cache may take a little while.
2169        mHandler.post(new Runnable() {
2170            public void run() {
2171                mHandler.removeCallbacks(this);
2172                int retCode = -1;
2173                synchronized (mInstallLock) {
2174                    retCode = mInstaller.freeCache(freeStorageSize);
2175                    if (retCode < 0) {
2176                        Slog.w(TAG, "Couldn't clear application caches");
2177                    }
2178                }
2179                if (observer != null) {
2180                    try {
2181                        observer.onRemoveCompleted(null, (retCode >= 0));
2182                    } catch (RemoteException e) {
2183                        Slog.w(TAG, "RemoveException when invoking call back");
2184                    }
2185                }
2186            }
2187        });
2188    }
2189
2190    @Override
2191    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2192        mContext.enforceCallingOrSelfPermission(
2193                android.Manifest.permission.CLEAR_APP_CACHE, null);
2194        // Queue up an async operation since clearing cache may take a little while.
2195        mHandler.post(new Runnable() {
2196            public void run() {
2197                mHandler.removeCallbacks(this);
2198                int retCode = -1;
2199                synchronized (mInstallLock) {
2200                    retCode = mInstaller.freeCache(freeStorageSize);
2201                    if (retCode < 0) {
2202                        Slog.w(TAG, "Couldn't clear application caches");
2203                    }
2204                }
2205                if(pi != null) {
2206                    try {
2207                        // Callback via pending intent
2208                        int code = (retCode >= 0) ? 1 : 0;
2209                        pi.sendIntent(null, code, null,
2210                                null, null);
2211                    } catch (SendIntentException e1) {
2212                        Slog.i(TAG, "Failed to send pending intent");
2213                    }
2214                }
2215            }
2216        });
2217    }
2218
2219    void freeStorage(long freeStorageSize) throws IOException {
2220        synchronized (mInstallLock) {
2221            if (mInstaller.freeCache(freeStorageSize) < 0) {
2222                throw new IOException("Failed to free enough space");
2223            }
2224        }
2225    }
2226
2227    @Override
2228    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2229        if (!sUserManager.exists(userId)) return null;
2230        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2231        synchronized (mPackages) {
2232            PackageParser.Activity a = mActivities.mActivities.get(component);
2233
2234            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2235            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2236                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2237                if (ps == null) return null;
2238                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2239                        userId);
2240            }
2241            if (mResolveComponentName.equals(component)) {
2242                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2243                        new PackageUserState(), userId);
2244            }
2245        }
2246        return null;
2247    }
2248
2249    @Override
2250    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2251            String resolvedType) {
2252        synchronized (mPackages) {
2253            PackageParser.Activity a = mActivities.mActivities.get(component);
2254            if (a == null) {
2255                return false;
2256            }
2257            for (int i=0; i<a.intents.size(); i++) {
2258                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2259                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2260                    return true;
2261                }
2262            }
2263            return false;
2264        }
2265    }
2266
2267    @Override
2268    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2269        if (!sUserManager.exists(userId)) return null;
2270        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2271        synchronized (mPackages) {
2272            PackageParser.Activity a = mReceivers.mActivities.get(component);
2273            if (DEBUG_PACKAGE_INFO) Log.v(
2274                TAG, "getReceiverInfo " + component + ": " + a);
2275            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2276                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2277                if (ps == null) return null;
2278                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2279                        userId);
2280            }
2281        }
2282        return null;
2283    }
2284
2285    @Override
2286    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2287        if (!sUserManager.exists(userId)) return null;
2288        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2289        synchronized (mPackages) {
2290            PackageParser.Service s = mServices.mServices.get(component);
2291            if (DEBUG_PACKAGE_INFO) Log.v(
2292                TAG, "getServiceInfo " + component + ": " + s);
2293            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2294                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2295                if (ps == null) return null;
2296                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2297                        userId);
2298            }
2299        }
2300        return null;
2301    }
2302
2303    @Override
2304    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2305        if (!sUserManager.exists(userId)) return null;
2306        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2307        synchronized (mPackages) {
2308            PackageParser.Provider p = mProviders.mProviders.get(component);
2309            if (DEBUG_PACKAGE_INFO) Log.v(
2310                TAG, "getProviderInfo " + component + ": " + p);
2311            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2312                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2313                if (ps == null) return null;
2314                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2315                        userId);
2316            }
2317        }
2318        return null;
2319    }
2320
2321    @Override
2322    public String[] getSystemSharedLibraryNames() {
2323        Set<String> libSet;
2324        synchronized (mPackages) {
2325            libSet = mSharedLibraries.keySet();
2326            int size = libSet.size();
2327            if (size > 0) {
2328                String[] libs = new String[size];
2329                libSet.toArray(libs);
2330                return libs;
2331            }
2332        }
2333        return null;
2334    }
2335
2336    /**
2337     * @hide
2338     */
2339    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2340        synchronized (mPackages) {
2341            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2342            if (lib != null && lib.apk != null) {
2343                return mPackages.get(lib.apk);
2344            }
2345        }
2346        return null;
2347    }
2348
2349    @Override
2350    public FeatureInfo[] getSystemAvailableFeatures() {
2351        Collection<FeatureInfo> featSet;
2352        synchronized (mPackages) {
2353            featSet = mAvailableFeatures.values();
2354            int size = featSet.size();
2355            if (size > 0) {
2356                FeatureInfo[] features = new FeatureInfo[size+1];
2357                featSet.toArray(features);
2358                FeatureInfo fi = new FeatureInfo();
2359                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2360                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2361                features[size] = fi;
2362                return features;
2363            }
2364        }
2365        return null;
2366    }
2367
2368    @Override
2369    public boolean hasSystemFeature(String name) {
2370        synchronized (mPackages) {
2371            return mAvailableFeatures.containsKey(name);
2372        }
2373    }
2374
2375    private void checkValidCaller(int uid, int userId) {
2376        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2377            return;
2378
2379        throw new SecurityException("Caller uid=" + uid
2380                + " is not privileged to communicate with user=" + userId);
2381    }
2382
2383    @Override
2384    public int checkPermission(String permName, String pkgName) {
2385        synchronized (mPackages) {
2386            PackageParser.Package p = mPackages.get(pkgName);
2387            if (p != null && p.mExtras != null) {
2388                PackageSetting ps = (PackageSetting)p.mExtras;
2389                if (ps.sharedUser != null) {
2390                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2391                        return PackageManager.PERMISSION_GRANTED;
2392                    }
2393                } else if (ps.grantedPermissions.contains(permName)) {
2394                    return PackageManager.PERMISSION_GRANTED;
2395                }
2396            }
2397        }
2398        return PackageManager.PERMISSION_DENIED;
2399    }
2400
2401    @Override
2402    public int checkUidPermission(String permName, int uid) {
2403        synchronized (mPackages) {
2404            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2405            if (obj != null) {
2406                GrantedPermissions gp = (GrantedPermissions)obj;
2407                if (gp.grantedPermissions.contains(permName)) {
2408                    return PackageManager.PERMISSION_GRANTED;
2409                }
2410            } else {
2411                ArraySet<String> perms = mSystemPermissions.get(uid);
2412                if (perms != null && perms.contains(permName)) {
2413                    return PackageManager.PERMISSION_GRANTED;
2414                }
2415            }
2416        }
2417        return PackageManager.PERMISSION_DENIED;
2418    }
2419
2420    /**
2421     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2422     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2423     * @param checkShell TODO(yamasani):
2424     * @param message the message to log on security exception
2425     */
2426    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2427            boolean checkShell, String message) {
2428        if (userId < 0) {
2429            throw new IllegalArgumentException("Invalid userId " + userId);
2430        }
2431        if (checkShell) {
2432            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2433        }
2434        if (userId == UserHandle.getUserId(callingUid)) return;
2435        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2436            if (requireFullPermission) {
2437                mContext.enforceCallingOrSelfPermission(
2438                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2439            } else {
2440                try {
2441                    mContext.enforceCallingOrSelfPermission(
2442                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2443                } catch (SecurityException se) {
2444                    mContext.enforceCallingOrSelfPermission(
2445                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2446                }
2447            }
2448        }
2449    }
2450
2451    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2452        if (callingUid == Process.SHELL_UID) {
2453            if (userHandle >= 0
2454                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2455                throw new SecurityException("Shell does not have permission to access user "
2456                        + userHandle);
2457            } else if (userHandle < 0) {
2458                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2459                        + Debug.getCallers(3));
2460            }
2461        }
2462    }
2463
2464    private BasePermission findPermissionTreeLP(String permName) {
2465        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2466            if (permName.startsWith(bp.name) &&
2467                    permName.length() > bp.name.length() &&
2468                    permName.charAt(bp.name.length()) == '.') {
2469                return bp;
2470            }
2471        }
2472        return null;
2473    }
2474
2475    private BasePermission checkPermissionTreeLP(String permName) {
2476        if (permName != null) {
2477            BasePermission bp = findPermissionTreeLP(permName);
2478            if (bp != null) {
2479                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2480                    return bp;
2481                }
2482                throw new SecurityException("Calling uid "
2483                        + Binder.getCallingUid()
2484                        + " is not allowed to add to permission tree "
2485                        + bp.name + " owned by uid " + bp.uid);
2486            }
2487        }
2488        throw new SecurityException("No permission tree found for " + permName);
2489    }
2490
2491    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2492        if (s1 == null) {
2493            return s2 == null;
2494        }
2495        if (s2 == null) {
2496            return false;
2497        }
2498        if (s1.getClass() != s2.getClass()) {
2499            return false;
2500        }
2501        return s1.equals(s2);
2502    }
2503
2504    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2505        if (pi1.icon != pi2.icon) return false;
2506        if (pi1.logo != pi2.logo) return false;
2507        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2508        if (!compareStrings(pi1.name, pi2.name)) return false;
2509        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2510        // We'll take care of setting this one.
2511        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2512        // These are not currently stored in settings.
2513        //if (!compareStrings(pi1.group, pi2.group)) return false;
2514        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2515        //if (pi1.labelRes != pi2.labelRes) return false;
2516        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2517        return true;
2518    }
2519
2520    int permissionInfoFootprint(PermissionInfo info) {
2521        int size = info.name.length();
2522        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2523        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2524        return size;
2525    }
2526
2527    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2528        int size = 0;
2529        for (BasePermission perm : mSettings.mPermissions.values()) {
2530            if (perm.uid == tree.uid) {
2531                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2532            }
2533        }
2534        return size;
2535    }
2536
2537    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2538        // We calculate the max size of permissions defined by this uid and throw
2539        // if that plus the size of 'info' would exceed our stated maximum.
2540        if (tree.uid != Process.SYSTEM_UID) {
2541            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2542            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2543                throw new SecurityException("Permission tree size cap exceeded");
2544            }
2545        }
2546    }
2547
2548    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2549        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2550            throw new SecurityException("Label must be specified in permission");
2551        }
2552        BasePermission tree = checkPermissionTreeLP(info.name);
2553        BasePermission bp = mSettings.mPermissions.get(info.name);
2554        boolean added = bp == null;
2555        boolean changed = true;
2556        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2557        if (added) {
2558            enforcePermissionCapLocked(info, tree);
2559            bp = new BasePermission(info.name, tree.sourcePackage,
2560                    BasePermission.TYPE_DYNAMIC);
2561        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2562            throw new SecurityException(
2563                    "Not allowed to modify non-dynamic permission "
2564                    + info.name);
2565        } else {
2566            if (bp.protectionLevel == fixedLevel
2567                    && bp.perm.owner.equals(tree.perm.owner)
2568                    && bp.uid == tree.uid
2569                    && comparePermissionInfos(bp.perm.info, info)) {
2570                changed = false;
2571            }
2572        }
2573        bp.protectionLevel = fixedLevel;
2574        info = new PermissionInfo(info);
2575        info.protectionLevel = fixedLevel;
2576        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2577        bp.perm.info.packageName = tree.perm.info.packageName;
2578        bp.uid = tree.uid;
2579        if (added) {
2580            mSettings.mPermissions.put(info.name, bp);
2581        }
2582        if (changed) {
2583            if (!async) {
2584                mSettings.writeLPr();
2585            } else {
2586                scheduleWriteSettingsLocked();
2587            }
2588        }
2589        return added;
2590    }
2591
2592    @Override
2593    public boolean addPermission(PermissionInfo info) {
2594        synchronized (mPackages) {
2595            return addPermissionLocked(info, false);
2596        }
2597    }
2598
2599    @Override
2600    public boolean addPermissionAsync(PermissionInfo info) {
2601        synchronized (mPackages) {
2602            return addPermissionLocked(info, true);
2603        }
2604    }
2605
2606    @Override
2607    public void removePermission(String name) {
2608        synchronized (mPackages) {
2609            checkPermissionTreeLP(name);
2610            BasePermission bp = mSettings.mPermissions.get(name);
2611            if (bp != null) {
2612                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2613                    throw new SecurityException(
2614                            "Not allowed to modify non-dynamic permission "
2615                            + name);
2616                }
2617                mSettings.mPermissions.remove(name);
2618                mSettings.writeLPr();
2619            }
2620        }
2621    }
2622
2623    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2624        int index = pkg.requestedPermissions.indexOf(bp.name);
2625        if (index == -1) {
2626            throw new SecurityException("Package " + pkg.packageName
2627                    + " has not requested permission " + bp.name);
2628        }
2629        boolean isNormal =
2630                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2631                        == PermissionInfo.PROTECTION_NORMAL);
2632        boolean isDangerous =
2633                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2634                        == PermissionInfo.PROTECTION_DANGEROUS);
2635        boolean isDevelopment =
2636                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2637
2638        if (!isNormal && !isDangerous && !isDevelopment) {
2639            throw new SecurityException("Permission " + bp.name
2640                    + " is not a changeable permission type");
2641        }
2642
2643        if (isNormal || isDangerous) {
2644            if (pkg.requestedPermissionsRequired.get(index)) {
2645                throw new SecurityException("Can't change " + bp.name
2646                        + ". It is required by the application");
2647            }
2648        }
2649    }
2650
2651    @Override
2652    public void grantPermission(String packageName, String permissionName) {
2653        mContext.enforceCallingOrSelfPermission(
2654                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2655        synchronized (mPackages) {
2656            final PackageParser.Package pkg = mPackages.get(packageName);
2657            if (pkg == null) {
2658                throw new IllegalArgumentException("Unknown package: " + packageName);
2659            }
2660            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2661            if (bp == null) {
2662                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2663            }
2664
2665            checkGrantRevokePermissions(pkg, bp);
2666
2667            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2668            if (ps == null) {
2669                return;
2670            }
2671            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2672            if (gp.grantedPermissions.add(permissionName)) {
2673                if (ps.haveGids) {
2674                    gp.gids = appendInts(gp.gids, bp.gids);
2675                }
2676                mSettings.writeLPr();
2677            }
2678        }
2679    }
2680
2681    @Override
2682    public void revokePermission(String packageName, String permissionName) {
2683        int changedAppId = -1;
2684
2685        synchronized (mPackages) {
2686            final PackageParser.Package pkg = mPackages.get(packageName);
2687            if (pkg == null) {
2688                throw new IllegalArgumentException("Unknown package: " + packageName);
2689            }
2690            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2691                mContext.enforceCallingOrSelfPermission(
2692                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2693            }
2694            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2695            if (bp == null) {
2696                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2697            }
2698
2699            checkGrantRevokePermissions(pkg, bp);
2700
2701            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2702            if (ps == null) {
2703                return;
2704            }
2705            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2706            if (gp.grantedPermissions.remove(permissionName)) {
2707                gp.grantedPermissions.remove(permissionName);
2708                if (ps.haveGids) {
2709                    gp.gids = removeInts(gp.gids, bp.gids);
2710                }
2711                mSettings.writeLPr();
2712                changedAppId = ps.appId;
2713            }
2714        }
2715
2716        if (changedAppId >= 0) {
2717            // We changed the perm on someone, kill its processes.
2718            IActivityManager am = ActivityManagerNative.getDefault();
2719            if (am != null) {
2720                final int callingUserId = UserHandle.getCallingUserId();
2721                final long ident = Binder.clearCallingIdentity();
2722                try {
2723                    //XXX we should only revoke for the calling user's app permissions,
2724                    // but for now we impact all users.
2725                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2726                    //        "revoke " + permissionName);
2727                    int[] users = sUserManager.getUserIds();
2728                    for (int user : users) {
2729                        am.killUid(UserHandle.getUid(user, changedAppId),
2730                                "revoke " + permissionName);
2731                    }
2732                } catch (RemoteException e) {
2733                } finally {
2734                    Binder.restoreCallingIdentity(ident);
2735                }
2736            }
2737        }
2738    }
2739
2740    @Override
2741    public boolean isProtectedBroadcast(String actionName) {
2742        synchronized (mPackages) {
2743            return mProtectedBroadcasts.contains(actionName);
2744        }
2745    }
2746
2747    @Override
2748    public int checkSignatures(String pkg1, String pkg2) {
2749        synchronized (mPackages) {
2750            final PackageParser.Package p1 = mPackages.get(pkg1);
2751            final PackageParser.Package p2 = mPackages.get(pkg2);
2752            if (p1 == null || p1.mExtras == null
2753                    || p2 == null || p2.mExtras == null) {
2754                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2755            }
2756            return compareSignatures(p1.mSignatures, p2.mSignatures);
2757        }
2758    }
2759
2760    @Override
2761    public int checkUidSignatures(int uid1, int uid2) {
2762        // Map to base uids.
2763        uid1 = UserHandle.getAppId(uid1);
2764        uid2 = UserHandle.getAppId(uid2);
2765        // reader
2766        synchronized (mPackages) {
2767            Signature[] s1;
2768            Signature[] s2;
2769            Object obj = mSettings.getUserIdLPr(uid1);
2770            if (obj != null) {
2771                if (obj instanceof SharedUserSetting) {
2772                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2773                } else if (obj instanceof PackageSetting) {
2774                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2775                } else {
2776                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2777                }
2778            } else {
2779                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2780            }
2781            obj = mSettings.getUserIdLPr(uid2);
2782            if (obj != null) {
2783                if (obj instanceof SharedUserSetting) {
2784                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2785                } else if (obj instanceof PackageSetting) {
2786                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2787                } else {
2788                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2789                }
2790            } else {
2791                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2792            }
2793            return compareSignatures(s1, s2);
2794        }
2795    }
2796
2797    /**
2798     * Compares two sets of signatures. Returns:
2799     * <br />
2800     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2801     * <br />
2802     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2803     * <br />
2804     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2805     * <br />
2806     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2807     * <br />
2808     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2809     */
2810    static int compareSignatures(Signature[] s1, Signature[] s2) {
2811        if (s1 == null) {
2812            return s2 == null
2813                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2814                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2815        }
2816
2817        if (s2 == null) {
2818            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2819        }
2820
2821        if (s1.length != s2.length) {
2822            return PackageManager.SIGNATURE_NO_MATCH;
2823        }
2824
2825        // Since both signature sets are of size 1, we can compare without HashSets.
2826        if (s1.length == 1) {
2827            return s1[0].equals(s2[0]) ?
2828                    PackageManager.SIGNATURE_MATCH :
2829                    PackageManager.SIGNATURE_NO_MATCH;
2830        }
2831
2832        ArraySet<Signature> set1 = new ArraySet<Signature>();
2833        for (Signature sig : s1) {
2834            set1.add(sig);
2835        }
2836        ArraySet<Signature> set2 = new ArraySet<Signature>();
2837        for (Signature sig : s2) {
2838            set2.add(sig);
2839        }
2840        // Make sure s2 contains all signatures in s1.
2841        if (set1.equals(set2)) {
2842            return PackageManager.SIGNATURE_MATCH;
2843        }
2844        return PackageManager.SIGNATURE_NO_MATCH;
2845    }
2846
2847    /**
2848     * If the database version for this type of package (internal storage or
2849     * external storage) is less than the version where package signatures
2850     * were updated, return true.
2851     */
2852    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2853        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2854                DatabaseVersion.SIGNATURE_END_ENTITY))
2855                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2856                        DatabaseVersion.SIGNATURE_END_ENTITY));
2857    }
2858
2859    /**
2860     * Used for backward compatibility to make sure any packages with
2861     * certificate chains get upgraded to the new style. {@code existingSigs}
2862     * will be in the old format (since they were stored on disk from before the
2863     * system upgrade) and {@code scannedSigs} will be in the newer format.
2864     */
2865    private int compareSignaturesCompat(PackageSignatures existingSigs,
2866            PackageParser.Package scannedPkg) {
2867        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2868            return PackageManager.SIGNATURE_NO_MATCH;
2869        }
2870
2871        ArraySet<Signature> existingSet = new ArraySet<Signature>();
2872        for (Signature sig : existingSigs.mSignatures) {
2873            existingSet.add(sig);
2874        }
2875        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
2876        for (Signature sig : scannedPkg.mSignatures) {
2877            try {
2878                Signature[] chainSignatures = sig.getChainSignatures();
2879                for (Signature chainSig : chainSignatures) {
2880                    scannedCompatSet.add(chainSig);
2881                }
2882            } catch (CertificateEncodingException e) {
2883                scannedCompatSet.add(sig);
2884            }
2885        }
2886        /*
2887         * Make sure the expanded scanned set contains all signatures in the
2888         * existing one.
2889         */
2890        if (scannedCompatSet.equals(existingSet)) {
2891            // Migrate the old signatures to the new scheme.
2892            existingSigs.assignSignatures(scannedPkg.mSignatures);
2893            // The new KeySets will be re-added later in the scanning process.
2894            synchronized (mPackages) {
2895                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2896            }
2897            return PackageManager.SIGNATURE_MATCH;
2898        }
2899        return PackageManager.SIGNATURE_NO_MATCH;
2900    }
2901
2902    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2903        if (isExternal(scannedPkg)) {
2904            return mSettings.isExternalDatabaseVersionOlderThan(
2905                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
2906        } else {
2907            return mSettings.isInternalDatabaseVersionOlderThan(
2908                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
2909        }
2910    }
2911
2912    private int compareSignaturesRecover(PackageSignatures existingSigs,
2913            PackageParser.Package scannedPkg) {
2914        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
2915            return PackageManager.SIGNATURE_NO_MATCH;
2916        }
2917
2918        String msg = null;
2919        try {
2920            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
2921                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
2922                        + scannedPkg.packageName);
2923                return PackageManager.SIGNATURE_MATCH;
2924            }
2925        } catch (CertificateException e) {
2926            msg = e.getMessage();
2927        }
2928
2929        logCriticalInfo(Log.INFO,
2930                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
2931        return PackageManager.SIGNATURE_NO_MATCH;
2932    }
2933
2934    @Override
2935    public String[] getPackagesForUid(int uid) {
2936        uid = UserHandle.getAppId(uid);
2937        // reader
2938        synchronized (mPackages) {
2939            Object obj = mSettings.getUserIdLPr(uid);
2940            if (obj instanceof SharedUserSetting) {
2941                final SharedUserSetting sus = (SharedUserSetting) obj;
2942                final int N = sus.packages.size();
2943                final String[] res = new String[N];
2944                final Iterator<PackageSetting> it = sus.packages.iterator();
2945                int i = 0;
2946                while (it.hasNext()) {
2947                    res[i++] = it.next().name;
2948                }
2949                return res;
2950            } else if (obj instanceof PackageSetting) {
2951                final PackageSetting ps = (PackageSetting) obj;
2952                return new String[] { ps.name };
2953            }
2954        }
2955        return null;
2956    }
2957
2958    @Override
2959    public String getNameForUid(int uid) {
2960        // reader
2961        synchronized (mPackages) {
2962            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2963            if (obj instanceof SharedUserSetting) {
2964                final SharedUserSetting sus = (SharedUserSetting) obj;
2965                return sus.name + ":" + sus.userId;
2966            } else if (obj instanceof PackageSetting) {
2967                final PackageSetting ps = (PackageSetting) obj;
2968                return ps.name;
2969            }
2970        }
2971        return null;
2972    }
2973
2974    @Override
2975    public int getUidForSharedUser(String sharedUserName) {
2976        if(sharedUserName == null) {
2977            return -1;
2978        }
2979        // reader
2980        synchronized (mPackages) {
2981            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
2982            if (suid == null) {
2983                return -1;
2984            }
2985            return suid.userId;
2986        }
2987    }
2988
2989    @Override
2990    public int getFlagsForUid(int uid) {
2991        synchronized (mPackages) {
2992            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2993            if (obj instanceof SharedUserSetting) {
2994                final SharedUserSetting sus = (SharedUserSetting) obj;
2995                return sus.pkgFlags;
2996            } else if (obj instanceof PackageSetting) {
2997                final PackageSetting ps = (PackageSetting) obj;
2998                return ps.pkgFlags;
2999            }
3000        }
3001        return 0;
3002    }
3003
3004    @Override
3005    public int getPrivateFlagsForUid(int uid) {
3006        synchronized (mPackages) {
3007            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3008            if (obj instanceof SharedUserSetting) {
3009                final SharedUserSetting sus = (SharedUserSetting) obj;
3010                return sus.pkgPrivateFlags;
3011            } else if (obj instanceof PackageSetting) {
3012                final PackageSetting ps = (PackageSetting) obj;
3013                return ps.pkgPrivateFlags;
3014            }
3015        }
3016        return 0;
3017    }
3018
3019    @Override
3020    public boolean isUidPrivileged(int uid) {
3021        uid = UserHandle.getAppId(uid);
3022        // reader
3023        synchronized (mPackages) {
3024            Object obj = mSettings.getUserIdLPr(uid);
3025            if (obj instanceof SharedUserSetting) {
3026                final SharedUserSetting sus = (SharedUserSetting) obj;
3027                final Iterator<PackageSetting> it = sus.packages.iterator();
3028                while (it.hasNext()) {
3029                    if (it.next().isPrivileged()) {
3030                        return true;
3031                    }
3032                }
3033            } else if (obj instanceof PackageSetting) {
3034                final PackageSetting ps = (PackageSetting) obj;
3035                return ps.isPrivileged();
3036            }
3037        }
3038        return false;
3039    }
3040
3041    @Override
3042    public String[] getAppOpPermissionPackages(String permissionName) {
3043        synchronized (mPackages) {
3044            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3045            if (pkgs == null) {
3046                return null;
3047            }
3048            return pkgs.toArray(new String[pkgs.size()]);
3049        }
3050    }
3051
3052    @Override
3053    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3054            int flags, int userId) {
3055        if (!sUserManager.exists(userId)) return null;
3056        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3057        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3058        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3059    }
3060
3061    @Override
3062    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3063            IntentFilter filter, int match, ComponentName activity) {
3064        final int userId = UserHandle.getCallingUserId();
3065        if (DEBUG_PREFERRED) {
3066            Log.v(TAG, "setLastChosenActivity intent=" + intent
3067                + " resolvedType=" + resolvedType
3068                + " flags=" + flags
3069                + " filter=" + filter
3070                + " match=" + match
3071                + " activity=" + activity);
3072            filter.dump(new PrintStreamPrinter(System.out), "    ");
3073        }
3074        intent.setComponent(null);
3075        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3076        // Find any earlier preferred or last chosen entries and nuke them
3077        findPreferredActivity(intent, resolvedType,
3078                flags, query, 0, false, true, false, userId);
3079        // Add the new activity as the last chosen for this filter
3080        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3081                "Setting last chosen");
3082    }
3083
3084    @Override
3085    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3086        final int userId = UserHandle.getCallingUserId();
3087        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3088        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3089        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3090                false, false, false, userId);
3091    }
3092
3093    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3094            int flags, List<ResolveInfo> query, int userId) {
3095        if (query != null) {
3096            final int N = query.size();
3097            if (N == 1) {
3098                return query.get(0);
3099            } else if (N > 1) {
3100                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3101                // If there is more than one activity with the same priority,
3102                // then let the user decide between them.
3103                ResolveInfo r0 = query.get(0);
3104                ResolveInfo r1 = query.get(1);
3105                if (DEBUG_INTENT_MATCHING || debug) {
3106                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3107                            + r1.activityInfo.name + "=" + r1.priority);
3108                }
3109                // If the first activity has a higher priority, or a different
3110                // default, then it is always desireable to pick it.
3111                if (r0.priority != r1.priority
3112                        || r0.preferredOrder != r1.preferredOrder
3113                        || r0.isDefault != r1.isDefault) {
3114                    return query.get(0);
3115                }
3116                // If we have saved a preference for a preferred activity for
3117                // this Intent, use that.
3118                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3119                        flags, query, r0.priority, true, false, debug, userId);
3120                if (ri != null) {
3121                    return ri;
3122                }
3123                if (userId != 0) {
3124                    ri = new ResolveInfo(mResolveInfo);
3125                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3126                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3127                            ri.activityInfo.applicationInfo);
3128                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3129                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3130                    return ri;
3131                }
3132                return mResolveInfo;
3133            }
3134        }
3135        return null;
3136    }
3137
3138    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3139            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3140        final int N = query.size();
3141        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3142                .get(userId);
3143        // Get the list of persistent preferred activities that handle the intent
3144        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3145        List<PersistentPreferredActivity> pprefs = ppir != null
3146                ? ppir.queryIntent(intent, resolvedType,
3147                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3148                : null;
3149        if (pprefs != null && pprefs.size() > 0) {
3150            final int M = pprefs.size();
3151            for (int i=0; i<M; i++) {
3152                final PersistentPreferredActivity ppa = pprefs.get(i);
3153                if (DEBUG_PREFERRED || debug) {
3154                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3155                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3156                            + "\n  component=" + ppa.mComponent);
3157                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3158                }
3159                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3160                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3161                if (DEBUG_PREFERRED || debug) {
3162                    Slog.v(TAG, "Found persistent preferred activity:");
3163                    if (ai != null) {
3164                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3165                    } else {
3166                        Slog.v(TAG, "  null");
3167                    }
3168                }
3169                if (ai == null) {
3170                    // This previously registered persistent preferred activity
3171                    // component is no longer known. Ignore it and do NOT remove it.
3172                    continue;
3173                }
3174                for (int j=0; j<N; j++) {
3175                    final ResolveInfo ri = query.get(j);
3176                    if (!ri.activityInfo.applicationInfo.packageName
3177                            .equals(ai.applicationInfo.packageName)) {
3178                        continue;
3179                    }
3180                    if (!ri.activityInfo.name.equals(ai.name)) {
3181                        continue;
3182                    }
3183                    //  Found a persistent preference that can handle the intent.
3184                    if (DEBUG_PREFERRED || debug) {
3185                        Slog.v(TAG, "Returning persistent preferred activity: " +
3186                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3187                    }
3188                    return ri;
3189                }
3190            }
3191        }
3192        return null;
3193    }
3194
3195    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3196            List<ResolveInfo> query, int priority, boolean always,
3197            boolean removeMatches, boolean debug, int userId) {
3198        if (!sUserManager.exists(userId)) return null;
3199        // writer
3200        synchronized (mPackages) {
3201            if (intent.getSelector() != null) {
3202                intent = intent.getSelector();
3203            }
3204            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3205
3206            // Try to find a matching persistent preferred activity.
3207            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3208                    debug, userId);
3209
3210            // If a persistent preferred activity matched, use it.
3211            if (pri != null) {
3212                return pri;
3213            }
3214
3215            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3216            // Get the list of preferred activities that handle the intent
3217            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3218            List<PreferredActivity> prefs = pir != null
3219                    ? pir.queryIntent(intent, resolvedType,
3220                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3221                    : null;
3222            if (prefs != null && prefs.size() > 0) {
3223                boolean changed = false;
3224                try {
3225                    // First figure out how good the original match set is.
3226                    // We will only allow preferred activities that came
3227                    // from the same match quality.
3228                    int match = 0;
3229
3230                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3231
3232                    final int N = query.size();
3233                    for (int j=0; j<N; j++) {
3234                        final ResolveInfo ri = query.get(j);
3235                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3236                                + ": 0x" + Integer.toHexString(match));
3237                        if (ri.match > match) {
3238                            match = ri.match;
3239                        }
3240                    }
3241
3242                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3243                            + Integer.toHexString(match));
3244
3245                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3246                    final int M = prefs.size();
3247                    for (int i=0; i<M; i++) {
3248                        final PreferredActivity pa = prefs.get(i);
3249                        if (DEBUG_PREFERRED || debug) {
3250                            Slog.v(TAG, "Checking PreferredActivity ds="
3251                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3252                                    + "\n  component=" + pa.mPref.mComponent);
3253                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3254                        }
3255                        if (pa.mPref.mMatch != match) {
3256                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3257                                    + Integer.toHexString(pa.mPref.mMatch));
3258                            continue;
3259                        }
3260                        // If it's not an "always" type preferred activity and that's what we're
3261                        // looking for, skip it.
3262                        if (always && !pa.mPref.mAlways) {
3263                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3264                            continue;
3265                        }
3266                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3267                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3268                        if (DEBUG_PREFERRED || debug) {
3269                            Slog.v(TAG, "Found preferred activity:");
3270                            if (ai != null) {
3271                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3272                            } else {
3273                                Slog.v(TAG, "  null");
3274                            }
3275                        }
3276                        if (ai == null) {
3277                            // This previously registered preferred activity
3278                            // component is no longer known.  Most likely an update
3279                            // to the app was installed and in the new version this
3280                            // component no longer exists.  Clean it up by removing
3281                            // it from the preferred activities list, and skip it.
3282                            Slog.w(TAG, "Removing dangling preferred activity: "
3283                                    + pa.mPref.mComponent);
3284                            pir.removeFilter(pa);
3285                            changed = true;
3286                            continue;
3287                        }
3288                        for (int j=0; j<N; j++) {
3289                            final ResolveInfo ri = query.get(j);
3290                            if (!ri.activityInfo.applicationInfo.packageName
3291                                    .equals(ai.applicationInfo.packageName)) {
3292                                continue;
3293                            }
3294                            if (!ri.activityInfo.name.equals(ai.name)) {
3295                                continue;
3296                            }
3297
3298                            if (removeMatches) {
3299                                pir.removeFilter(pa);
3300                                changed = true;
3301                                if (DEBUG_PREFERRED) {
3302                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3303                                }
3304                                break;
3305                            }
3306
3307                            // Okay we found a previously set preferred or last chosen app.
3308                            // If the result set is different from when this
3309                            // was created, we need to clear it and re-ask the
3310                            // user their preference, if we're looking for an "always" type entry.
3311                            if (always && !pa.mPref.sameSet(query)) {
3312                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3313                                        + intent + " type " + resolvedType);
3314                                if (DEBUG_PREFERRED) {
3315                                    Slog.v(TAG, "Removing preferred activity since set changed "
3316                                            + pa.mPref.mComponent);
3317                                }
3318                                pir.removeFilter(pa);
3319                                // Re-add the filter as a "last chosen" entry (!always)
3320                                PreferredActivity lastChosen = new PreferredActivity(
3321                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3322                                pir.addFilter(lastChosen);
3323                                changed = true;
3324                                return null;
3325                            }
3326
3327                            // Yay! Either the set matched or we're looking for the last chosen
3328                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3329                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3330                            return ri;
3331                        }
3332                    }
3333                } finally {
3334                    if (changed) {
3335                        if (DEBUG_PREFERRED) {
3336                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3337                        }
3338                        scheduleWritePackageRestrictionsLocked(userId);
3339                    }
3340                }
3341            }
3342        }
3343        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3344        return null;
3345    }
3346
3347    /*
3348     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3349     */
3350    @Override
3351    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3352            int targetUserId) {
3353        mContext.enforceCallingOrSelfPermission(
3354                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3355        List<CrossProfileIntentFilter> matches =
3356                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3357        if (matches != null) {
3358            int size = matches.size();
3359            for (int i = 0; i < size; i++) {
3360                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3361            }
3362        }
3363        return false;
3364    }
3365
3366    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3367            String resolvedType, int userId) {
3368        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3369        if (resolver != null) {
3370            return resolver.queryIntent(intent, resolvedType, false, userId);
3371        }
3372        return null;
3373    }
3374
3375    @Override
3376    public List<ResolveInfo> queryIntentActivities(Intent intent,
3377            String resolvedType, int flags, int userId) {
3378        if (!sUserManager.exists(userId)) return Collections.emptyList();
3379        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3380        ComponentName comp = intent.getComponent();
3381        if (comp == null) {
3382            if (intent.getSelector() != null) {
3383                intent = intent.getSelector();
3384                comp = intent.getComponent();
3385            }
3386        }
3387
3388        if (comp != null) {
3389            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3390            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3391            if (ai != null) {
3392                final ResolveInfo ri = new ResolveInfo();
3393                ri.activityInfo = ai;
3394                list.add(ri);
3395            }
3396            return list;
3397        }
3398
3399        // reader
3400        synchronized (mPackages) {
3401            final String pkgName = intent.getPackage();
3402            if (pkgName == null) {
3403                List<CrossProfileIntentFilter> matchingFilters =
3404                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3405                // Check for results that need to skip the current profile.
3406                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3407                        resolvedType, flags, userId);
3408                if (resolveInfo != null) {
3409                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3410                    result.add(resolveInfo);
3411                    return result;
3412                }
3413                // Check for cross profile results.
3414                resolveInfo = queryCrossProfileIntents(
3415                        matchingFilters, intent, resolvedType, flags, userId);
3416
3417                // Check for results in the current profile.
3418                List<ResolveInfo> result = mActivities.queryIntent(
3419                        intent, resolvedType, flags, userId);
3420                if (resolveInfo != null) {
3421                    result.add(resolveInfo);
3422                    Collections.sort(result, mResolvePrioritySorter);
3423                }
3424                return result;
3425            }
3426            final PackageParser.Package pkg = mPackages.get(pkgName);
3427            if (pkg != null) {
3428                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3429                        pkg.activities, userId);
3430            }
3431            return new ArrayList<ResolveInfo>();
3432        }
3433    }
3434
3435    private ResolveInfo querySkipCurrentProfileIntents(
3436            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3437            int flags, int sourceUserId) {
3438        if (matchingFilters != null) {
3439            int size = matchingFilters.size();
3440            for (int i = 0; i < size; i ++) {
3441                CrossProfileIntentFilter filter = matchingFilters.get(i);
3442                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3443                    // Checking if there are activities in the target user that can handle the
3444                    // intent.
3445                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3446                            flags, sourceUserId);
3447                    if (resolveInfo != null) {
3448                        return resolveInfo;
3449                    }
3450                }
3451            }
3452        }
3453        return null;
3454    }
3455
3456    // Return matching ResolveInfo if any for skip current profile intent filters.
3457    private ResolveInfo queryCrossProfileIntents(
3458            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3459            int flags, int sourceUserId) {
3460        if (matchingFilters != null) {
3461            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3462            // match the same intent. For performance reasons, it is better not to
3463            // run queryIntent twice for the same userId
3464            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3465            int size = matchingFilters.size();
3466            for (int i = 0; i < size; i++) {
3467                CrossProfileIntentFilter filter = matchingFilters.get(i);
3468                int targetUserId = filter.getTargetUserId();
3469                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3470                        && !alreadyTriedUserIds.get(targetUserId)) {
3471                    // Checking if there are activities in the target user that can handle the
3472                    // intent.
3473                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3474                            flags, sourceUserId);
3475                    if (resolveInfo != null) return resolveInfo;
3476                    alreadyTriedUserIds.put(targetUserId, true);
3477                }
3478            }
3479        }
3480        return null;
3481    }
3482
3483    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3484            String resolvedType, int flags, int sourceUserId) {
3485        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3486                resolvedType, flags, filter.getTargetUserId());
3487        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3488            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3489        }
3490        return null;
3491    }
3492
3493    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3494            int sourceUserId, int targetUserId) {
3495        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3496        String className;
3497        if (targetUserId == UserHandle.USER_OWNER) {
3498            className = FORWARD_INTENT_TO_USER_OWNER;
3499        } else {
3500            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3501        }
3502        ComponentName forwardingActivityComponentName = new ComponentName(
3503                mAndroidApplication.packageName, className);
3504        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3505                sourceUserId);
3506        if (targetUserId == UserHandle.USER_OWNER) {
3507            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3508            forwardingResolveInfo.noResourceId = true;
3509        }
3510        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3511        forwardingResolveInfo.priority = 0;
3512        forwardingResolveInfo.preferredOrder = 0;
3513        forwardingResolveInfo.match = 0;
3514        forwardingResolveInfo.isDefault = true;
3515        forwardingResolveInfo.filter = filter;
3516        forwardingResolveInfo.targetUserId = targetUserId;
3517        return forwardingResolveInfo;
3518    }
3519
3520    @Override
3521    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3522            Intent[] specifics, String[] specificTypes, Intent intent,
3523            String resolvedType, int flags, int userId) {
3524        if (!sUserManager.exists(userId)) return Collections.emptyList();
3525        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3526                false, "query intent activity options");
3527        final String resultsAction = intent.getAction();
3528
3529        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3530                | PackageManager.GET_RESOLVED_FILTER, userId);
3531
3532        if (DEBUG_INTENT_MATCHING) {
3533            Log.v(TAG, "Query " + intent + ": " + results);
3534        }
3535
3536        int specificsPos = 0;
3537        int N;
3538
3539        // todo: note that the algorithm used here is O(N^2).  This
3540        // isn't a problem in our current environment, but if we start running
3541        // into situations where we have more than 5 or 10 matches then this
3542        // should probably be changed to something smarter...
3543
3544        // First we go through and resolve each of the specific items
3545        // that were supplied, taking care of removing any corresponding
3546        // duplicate items in the generic resolve list.
3547        if (specifics != null) {
3548            for (int i=0; i<specifics.length; i++) {
3549                final Intent sintent = specifics[i];
3550                if (sintent == null) {
3551                    continue;
3552                }
3553
3554                if (DEBUG_INTENT_MATCHING) {
3555                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3556                }
3557
3558                String action = sintent.getAction();
3559                if (resultsAction != null && resultsAction.equals(action)) {
3560                    // If this action was explicitly requested, then don't
3561                    // remove things that have it.
3562                    action = null;
3563                }
3564
3565                ResolveInfo ri = null;
3566                ActivityInfo ai = null;
3567
3568                ComponentName comp = sintent.getComponent();
3569                if (comp == null) {
3570                    ri = resolveIntent(
3571                        sintent,
3572                        specificTypes != null ? specificTypes[i] : null,
3573                            flags, userId);
3574                    if (ri == null) {
3575                        continue;
3576                    }
3577                    if (ri == mResolveInfo) {
3578                        // ACK!  Must do something better with this.
3579                    }
3580                    ai = ri.activityInfo;
3581                    comp = new ComponentName(ai.applicationInfo.packageName,
3582                            ai.name);
3583                } else {
3584                    ai = getActivityInfo(comp, flags, userId);
3585                    if (ai == null) {
3586                        continue;
3587                    }
3588                }
3589
3590                // Look for any generic query activities that are duplicates
3591                // of this specific one, and remove them from the results.
3592                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3593                N = results.size();
3594                int j;
3595                for (j=specificsPos; j<N; j++) {
3596                    ResolveInfo sri = results.get(j);
3597                    if ((sri.activityInfo.name.equals(comp.getClassName())
3598                            && sri.activityInfo.applicationInfo.packageName.equals(
3599                                    comp.getPackageName()))
3600                        || (action != null && sri.filter.matchAction(action))) {
3601                        results.remove(j);
3602                        if (DEBUG_INTENT_MATCHING) Log.v(
3603                            TAG, "Removing duplicate item from " + j
3604                            + " due to specific " + specificsPos);
3605                        if (ri == null) {
3606                            ri = sri;
3607                        }
3608                        j--;
3609                        N--;
3610                    }
3611                }
3612
3613                // Add this specific item to its proper place.
3614                if (ri == null) {
3615                    ri = new ResolveInfo();
3616                    ri.activityInfo = ai;
3617                }
3618                results.add(specificsPos, ri);
3619                ri.specificIndex = i;
3620                specificsPos++;
3621            }
3622        }
3623
3624        // Now we go through the remaining generic results and remove any
3625        // duplicate actions that are found here.
3626        N = results.size();
3627        for (int i=specificsPos; i<N-1; i++) {
3628            final ResolveInfo rii = results.get(i);
3629            if (rii.filter == null) {
3630                continue;
3631            }
3632
3633            // Iterate over all of the actions of this result's intent
3634            // filter...  typically this should be just one.
3635            final Iterator<String> it = rii.filter.actionsIterator();
3636            if (it == null) {
3637                continue;
3638            }
3639            while (it.hasNext()) {
3640                final String action = it.next();
3641                if (resultsAction != null && resultsAction.equals(action)) {
3642                    // If this action was explicitly requested, then don't
3643                    // remove things that have it.
3644                    continue;
3645                }
3646                for (int j=i+1; j<N; j++) {
3647                    final ResolveInfo rij = results.get(j);
3648                    if (rij.filter != null && rij.filter.hasAction(action)) {
3649                        results.remove(j);
3650                        if (DEBUG_INTENT_MATCHING) Log.v(
3651                            TAG, "Removing duplicate item from " + j
3652                            + " due to action " + action + " at " + i);
3653                        j--;
3654                        N--;
3655                    }
3656                }
3657            }
3658
3659            // If the caller didn't request filter information, drop it now
3660            // so we don't have to marshall/unmarshall it.
3661            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3662                rii.filter = null;
3663            }
3664        }
3665
3666        // Filter out the caller activity if so requested.
3667        if (caller != null) {
3668            N = results.size();
3669            for (int i=0; i<N; i++) {
3670                ActivityInfo ainfo = results.get(i).activityInfo;
3671                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3672                        && caller.getClassName().equals(ainfo.name)) {
3673                    results.remove(i);
3674                    break;
3675                }
3676            }
3677        }
3678
3679        // If the caller didn't request filter information,
3680        // drop them now so we don't have to
3681        // marshall/unmarshall it.
3682        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3683            N = results.size();
3684            for (int i=0; i<N; i++) {
3685                results.get(i).filter = null;
3686            }
3687        }
3688
3689        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3690        return results;
3691    }
3692
3693    @Override
3694    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3695            int userId) {
3696        if (!sUserManager.exists(userId)) return Collections.emptyList();
3697        ComponentName comp = intent.getComponent();
3698        if (comp == null) {
3699            if (intent.getSelector() != null) {
3700                intent = intent.getSelector();
3701                comp = intent.getComponent();
3702            }
3703        }
3704        if (comp != null) {
3705            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3706            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3707            if (ai != null) {
3708                ResolveInfo ri = new ResolveInfo();
3709                ri.activityInfo = ai;
3710                list.add(ri);
3711            }
3712            return list;
3713        }
3714
3715        // reader
3716        synchronized (mPackages) {
3717            String pkgName = intent.getPackage();
3718            if (pkgName == null) {
3719                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3720            }
3721            final PackageParser.Package pkg = mPackages.get(pkgName);
3722            if (pkg != null) {
3723                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3724                        userId);
3725            }
3726            return null;
3727        }
3728    }
3729
3730    @Override
3731    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3732        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3733        if (!sUserManager.exists(userId)) return null;
3734        if (query != null) {
3735            if (query.size() >= 1) {
3736                // If there is more than one service with the same priority,
3737                // just arbitrarily pick the first one.
3738                return query.get(0);
3739            }
3740        }
3741        return null;
3742    }
3743
3744    @Override
3745    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3746            int userId) {
3747        if (!sUserManager.exists(userId)) return Collections.emptyList();
3748        ComponentName comp = intent.getComponent();
3749        if (comp == null) {
3750            if (intent.getSelector() != null) {
3751                intent = intent.getSelector();
3752                comp = intent.getComponent();
3753            }
3754        }
3755        if (comp != null) {
3756            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3757            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3758            if (si != null) {
3759                final ResolveInfo ri = new ResolveInfo();
3760                ri.serviceInfo = si;
3761                list.add(ri);
3762            }
3763            return list;
3764        }
3765
3766        // reader
3767        synchronized (mPackages) {
3768            String pkgName = intent.getPackage();
3769            if (pkgName == null) {
3770                return mServices.queryIntent(intent, resolvedType, flags, userId);
3771            }
3772            final PackageParser.Package pkg = mPackages.get(pkgName);
3773            if (pkg != null) {
3774                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3775                        userId);
3776            }
3777            return null;
3778        }
3779    }
3780
3781    @Override
3782    public List<ResolveInfo> queryIntentContentProviders(
3783            Intent intent, String resolvedType, int flags, int userId) {
3784        if (!sUserManager.exists(userId)) return Collections.emptyList();
3785        ComponentName comp = intent.getComponent();
3786        if (comp == null) {
3787            if (intent.getSelector() != null) {
3788                intent = intent.getSelector();
3789                comp = intent.getComponent();
3790            }
3791        }
3792        if (comp != null) {
3793            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3794            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3795            if (pi != null) {
3796                final ResolveInfo ri = new ResolveInfo();
3797                ri.providerInfo = pi;
3798                list.add(ri);
3799            }
3800            return list;
3801        }
3802
3803        // reader
3804        synchronized (mPackages) {
3805            String pkgName = intent.getPackage();
3806            if (pkgName == null) {
3807                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3808            }
3809            final PackageParser.Package pkg = mPackages.get(pkgName);
3810            if (pkg != null) {
3811                return mProviders.queryIntentForPackage(
3812                        intent, resolvedType, flags, pkg.providers, userId);
3813            }
3814            return null;
3815        }
3816    }
3817
3818    @Override
3819    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3820        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3821
3822        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3823
3824        // writer
3825        synchronized (mPackages) {
3826            ArrayList<PackageInfo> list;
3827            if (listUninstalled) {
3828                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3829                for (PackageSetting ps : mSettings.mPackages.values()) {
3830                    PackageInfo pi;
3831                    if (ps.pkg != null) {
3832                        pi = generatePackageInfo(ps.pkg, flags, userId);
3833                    } else {
3834                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3835                    }
3836                    if (pi != null) {
3837                        list.add(pi);
3838                    }
3839                }
3840            } else {
3841                list = new ArrayList<PackageInfo>(mPackages.size());
3842                for (PackageParser.Package p : mPackages.values()) {
3843                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3844                    if (pi != null) {
3845                        list.add(pi);
3846                    }
3847                }
3848            }
3849
3850            return new ParceledListSlice<PackageInfo>(list);
3851        }
3852    }
3853
3854    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3855            String[] permissions, boolean[] tmp, int flags, int userId) {
3856        int numMatch = 0;
3857        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3858        for (int i=0; i<permissions.length; i++) {
3859            if (gp.grantedPermissions.contains(permissions[i])) {
3860                tmp[i] = true;
3861                numMatch++;
3862            } else {
3863                tmp[i] = false;
3864            }
3865        }
3866        if (numMatch == 0) {
3867            return;
3868        }
3869        PackageInfo pi;
3870        if (ps.pkg != null) {
3871            pi = generatePackageInfo(ps.pkg, flags, userId);
3872        } else {
3873            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3874        }
3875        // The above might return null in cases of uninstalled apps or install-state
3876        // skew across users/profiles.
3877        if (pi != null) {
3878            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3879                if (numMatch == permissions.length) {
3880                    pi.requestedPermissions = permissions;
3881                } else {
3882                    pi.requestedPermissions = new String[numMatch];
3883                    numMatch = 0;
3884                    for (int i=0; i<permissions.length; i++) {
3885                        if (tmp[i]) {
3886                            pi.requestedPermissions[numMatch] = permissions[i];
3887                            numMatch++;
3888                        }
3889                    }
3890                }
3891            }
3892            list.add(pi);
3893        }
3894    }
3895
3896    @Override
3897    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3898            String[] permissions, 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<PackageInfo> list = new ArrayList<PackageInfo>();
3905            boolean[] tmpBools = new boolean[permissions.length];
3906            if (listUninstalled) {
3907                for (PackageSetting ps : mSettings.mPackages.values()) {
3908                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3909                }
3910            } else {
3911                for (PackageParser.Package pkg : mPackages.values()) {
3912                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3913                    if (ps != null) {
3914                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3915                                userId);
3916                    }
3917                }
3918            }
3919
3920            return new ParceledListSlice<PackageInfo>(list);
3921        }
3922    }
3923
3924    @Override
3925    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3926        if (!sUserManager.exists(userId)) return null;
3927        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3928
3929        // writer
3930        synchronized (mPackages) {
3931            ArrayList<ApplicationInfo> list;
3932            if (listUninstalled) {
3933                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3934                for (PackageSetting ps : mSettings.mPackages.values()) {
3935                    ApplicationInfo ai;
3936                    if (ps.pkg != null) {
3937                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3938                                ps.readUserState(userId), userId);
3939                    } else {
3940                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3941                    }
3942                    if (ai != null) {
3943                        list.add(ai);
3944                    }
3945                }
3946            } else {
3947                list = new ArrayList<ApplicationInfo>(mPackages.size());
3948                for (PackageParser.Package p : mPackages.values()) {
3949                    if (p.mExtras != null) {
3950                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3951                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3952                        if (ai != null) {
3953                            list.add(ai);
3954                        }
3955                    }
3956                }
3957            }
3958
3959            return new ParceledListSlice<ApplicationInfo>(list);
3960        }
3961    }
3962
3963    public List<ApplicationInfo> getPersistentApplications(int flags) {
3964        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3965
3966        // reader
3967        synchronized (mPackages) {
3968            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3969            final int userId = UserHandle.getCallingUserId();
3970            while (i.hasNext()) {
3971                final PackageParser.Package p = i.next();
3972                if (p.applicationInfo != null
3973                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3974                        && (!mSafeMode || isSystemApp(p))) {
3975                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3976                    if (ps != null) {
3977                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3978                                ps.readUserState(userId), userId);
3979                        if (ai != null) {
3980                            finalList.add(ai);
3981                        }
3982                    }
3983                }
3984            }
3985        }
3986
3987        return finalList;
3988    }
3989
3990    @Override
3991    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3992        if (!sUserManager.exists(userId)) return null;
3993        // reader
3994        synchronized (mPackages) {
3995            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3996            PackageSetting ps = provider != null
3997                    ? mSettings.mPackages.get(provider.owner.packageName)
3998                    : null;
3999            return ps != null
4000                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4001                    && (!mSafeMode || (provider.info.applicationInfo.flags
4002                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4003                    ? PackageParser.generateProviderInfo(provider, flags,
4004                            ps.readUserState(userId), userId)
4005                    : null;
4006        }
4007    }
4008
4009    /**
4010     * @deprecated
4011     */
4012    @Deprecated
4013    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4014        // reader
4015        synchronized (mPackages) {
4016            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4017                    .entrySet().iterator();
4018            final int userId = UserHandle.getCallingUserId();
4019            while (i.hasNext()) {
4020                Map.Entry<String, PackageParser.Provider> entry = i.next();
4021                PackageParser.Provider p = entry.getValue();
4022                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4023
4024                if (ps != null && p.syncable
4025                        && (!mSafeMode || (p.info.applicationInfo.flags
4026                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4027                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4028                            ps.readUserState(userId), userId);
4029                    if (info != null) {
4030                        outNames.add(entry.getKey());
4031                        outInfo.add(info);
4032                    }
4033                }
4034            }
4035        }
4036    }
4037
4038    @Override
4039    public List<ProviderInfo> queryContentProviders(String processName,
4040            int uid, int flags) {
4041        ArrayList<ProviderInfo> finalList = null;
4042        // reader
4043        synchronized (mPackages) {
4044            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4045            final int userId = processName != null ?
4046                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4047            while (i.hasNext()) {
4048                final PackageParser.Provider p = i.next();
4049                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4050                if (ps != null && p.info.authority != null
4051                        && (processName == null
4052                                || (p.info.processName.equals(processName)
4053                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4054                        && mSettings.isEnabledLPr(p.info, flags, userId)
4055                        && (!mSafeMode
4056                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4057                    if (finalList == null) {
4058                        finalList = new ArrayList<ProviderInfo>(3);
4059                    }
4060                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4061                            ps.readUserState(userId), userId);
4062                    if (info != null) {
4063                        finalList.add(info);
4064                    }
4065                }
4066            }
4067        }
4068
4069        if (finalList != null) {
4070            Collections.sort(finalList, mProviderInitOrderSorter);
4071        }
4072
4073        return finalList;
4074    }
4075
4076    @Override
4077    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4078            int flags) {
4079        // reader
4080        synchronized (mPackages) {
4081            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4082            return PackageParser.generateInstrumentationInfo(i, flags);
4083        }
4084    }
4085
4086    @Override
4087    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4088            int flags) {
4089        ArrayList<InstrumentationInfo> finalList =
4090            new ArrayList<InstrumentationInfo>();
4091
4092        // reader
4093        synchronized (mPackages) {
4094            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4095            while (i.hasNext()) {
4096                final PackageParser.Instrumentation p = i.next();
4097                if (targetPackage == null
4098                        || targetPackage.equals(p.info.targetPackage)) {
4099                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4100                            flags);
4101                    if (ii != null) {
4102                        finalList.add(ii);
4103                    }
4104                }
4105            }
4106        }
4107
4108        return finalList;
4109    }
4110
4111    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4112        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4113        if (overlays == null) {
4114            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4115            return;
4116        }
4117        for (PackageParser.Package opkg : overlays.values()) {
4118            // Not much to do if idmap fails: we already logged the error
4119            // and we certainly don't want to abort installation of pkg simply
4120            // because an overlay didn't fit properly. For these reasons,
4121            // ignore the return value of createIdmapForPackagePairLI.
4122            createIdmapForPackagePairLI(pkg, opkg);
4123        }
4124    }
4125
4126    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4127            PackageParser.Package opkg) {
4128        if (!opkg.mTrustedOverlay) {
4129            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4130                    opkg.baseCodePath + ": overlay not trusted");
4131            return false;
4132        }
4133        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4134        if (overlaySet == null) {
4135            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4136                    opkg.baseCodePath + " but target package has no known overlays");
4137            return false;
4138        }
4139        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4140        // TODO: generate idmap for split APKs
4141        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4142            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4143                    + opkg.baseCodePath);
4144            return false;
4145        }
4146        PackageParser.Package[] overlayArray =
4147            overlaySet.values().toArray(new PackageParser.Package[0]);
4148        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4149            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4150                return p1.mOverlayPriority - p2.mOverlayPriority;
4151            }
4152        };
4153        Arrays.sort(overlayArray, cmp);
4154
4155        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4156        int i = 0;
4157        for (PackageParser.Package p : overlayArray) {
4158            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4159        }
4160        return true;
4161    }
4162
4163    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4164        final File[] files = dir.listFiles();
4165        if (ArrayUtils.isEmpty(files)) {
4166            Log.d(TAG, "No files in app dir " + dir);
4167            return;
4168        }
4169
4170        if (DEBUG_PACKAGE_SCANNING) {
4171            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4172                    + " flags=0x" + Integer.toHexString(parseFlags));
4173        }
4174
4175        for (File file : files) {
4176            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4177                    && !PackageInstallerService.isStageName(file.getName());
4178            if (!isPackage) {
4179                // Ignore entries which are not packages
4180                continue;
4181            }
4182            try {
4183                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4184                        scanFlags, currentTime, null);
4185            } catch (PackageManagerException e) {
4186                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4187
4188                // Delete invalid userdata apps
4189                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4190                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4191                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4192                    if (file.isDirectory()) {
4193                        FileUtils.deleteContents(file);
4194                    }
4195                    file.delete();
4196                }
4197            }
4198        }
4199    }
4200
4201    private static File getSettingsProblemFile() {
4202        File dataDir = Environment.getDataDirectory();
4203        File systemDir = new File(dataDir, "system");
4204        File fname = new File(systemDir, "uiderrors.txt");
4205        return fname;
4206    }
4207
4208    static void reportSettingsProblem(int priority, String msg) {
4209        logCriticalInfo(priority, msg);
4210    }
4211
4212    static void logCriticalInfo(int priority, String msg) {
4213        Slog.println(priority, TAG, msg);
4214        EventLogTags.writePmCriticalInfo(msg);
4215        try {
4216            File fname = getSettingsProblemFile();
4217            FileOutputStream out = new FileOutputStream(fname, true);
4218            PrintWriter pw = new FastPrintWriter(out);
4219            SimpleDateFormat formatter = new SimpleDateFormat();
4220            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4221            pw.println(dateString + ": " + msg);
4222            pw.close();
4223            FileUtils.setPermissions(
4224                    fname.toString(),
4225                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4226                    -1, -1);
4227        } catch (java.io.IOException e) {
4228        }
4229    }
4230
4231    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4232            PackageParser.Package pkg, File srcFile, int parseFlags)
4233            throws PackageManagerException {
4234        if (ps != null
4235                && ps.codePath.equals(srcFile)
4236                && ps.timeStamp == srcFile.lastModified()
4237                && !isCompatSignatureUpdateNeeded(pkg)
4238                && !isRecoverSignatureUpdateNeeded(pkg)) {
4239            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4240            if (ps.signatures.mSignatures != null
4241                    && ps.signatures.mSignatures.length != 0
4242                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4243                // Optimization: reuse the existing cached certificates
4244                // if the package appears to be unchanged.
4245                pkg.mSignatures = ps.signatures.mSignatures;
4246                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4247                synchronized (mPackages) {
4248                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4249                }
4250                return;
4251            }
4252
4253            Slog.w(TAG, "PackageSetting for " + ps.name
4254                    + " is missing signatures.  Collecting certs again to recover them.");
4255        } else {
4256            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4257        }
4258
4259        try {
4260            pp.collectCertificates(pkg, parseFlags);
4261            pp.collectManifestDigest(pkg);
4262        } catch (PackageParserException e) {
4263            throw PackageManagerException.from(e);
4264        }
4265    }
4266
4267    /*
4268     *  Scan a package and return the newly parsed package.
4269     *  Returns null in case of errors and the error code is stored in mLastScanError
4270     */
4271    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4272            long currentTime, UserHandle user) throws PackageManagerException {
4273        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4274        parseFlags |= mDefParseFlags;
4275        PackageParser pp = new PackageParser();
4276        pp.setSeparateProcesses(mSeparateProcesses);
4277        pp.setOnlyCoreApps(mOnlyCore);
4278        pp.setDisplayMetrics(mMetrics);
4279
4280        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4281            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4282        }
4283
4284        final PackageParser.Package pkg;
4285        try {
4286            pkg = pp.parsePackage(scanFile, parseFlags);
4287        } catch (PackageParserException e) {
4288            throw PackageManagerException.from(e);
4289        }
4290
4291        PackageSetting ps = null;
4292        PackageSetting updatedPkg;
4293        // reader
4294        synchronized (mPackages) {
4295            // Look to see if we already know about this package.
4296            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4297            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4298                // This package has been renamed to its original name.  Let's
4299                // use that.
4300                ps = mSettings.peekPackageLPr(oldName);
4301            }
4302            // If there was no original package, see one for the real package name.
4303            if (ps == null) {
4304                ps = mSettings.peekPackageLPr(pkg.packageName);
4305            }
4306            // Check to see if this package could be hiding/updating a system
4307            // package.  Must look for it either under the original or real
4308            // package name depending on our state.
4309            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4310            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4311        }
4312        boolean updatedPkgBetter = false;
4313        // First check if this is a system package that may involve an update
4314        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4315            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
4316            // it needs to drop FLAG_PRIVILEGED.
4317            if (locationIsPrivileged(scanFile)) {
4318                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4319            } else {
4320                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4321            }
4322
4323            if (ps != null && !ps.codePath.equals(scanFile)) {
4324                // The path has changed from what was last scanned...  check the
4325                // version of the new path against what we have stored to determine
4326                // what to do.
4327                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4328                if (pkg.mVersionCode <= ps.versionCode) {
4329                    // The system package has been updated and the code path does not match
4330                    // Ignore entry. Skip it.
4331                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
4332                            + " ignored: updated version " + ps.versionCode
4333                            + " better than this " + pkg.mVersionCode);
4334                    if (!updatedPkg.codePath.equals(scanFile)) {
4335                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4336                                + ps.name + " changing from " + updatedPkg.codePathString
4337                                + " to " + scanFile);
4338                        updatedPkg.codePath = scanFile;
4339                        updatedPkg.codePathString = scanFile.toString();
4340                        updatedPkg.resourcePath = scanFile;
4341                        updatedPkg.resourcePathString = scanFile.toString();
4342                    }
4343                    updatedPkg.pkg = pkg;
4344                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4345                } else {
4346                    // The current app on the system partition is better than
4347                    // what we have updated to on the data partition; switch
4348                    // back to the system partition version.
4349                    // At this point, its safely assumed that package installation for
4350                    // apps in system partition will go through. If not there won't be a working
4351                    // version of the app
4352                    // writer
4353                    synchronized (mPackages) {
4354                        // Just remove the loaded entries from package lists.
4355                        mPackages.remove(ps.name);
4356                    }
4357
4358                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4359                            + " reverting from " + ps.codePathString
4360                            + ": new version " + pkg.mVersionCode
4361                            + " better than installed " + ps.versionCode);
4362
4363                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4364                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4365                            getAppDexInstructionSets(ps));
4366                    synchronized (mInstallLock) {
4367                        args.cleanUpResourcesLI();
4368                    }
4369                    synchronized (mPackages) {
4370                        mSettings.enableSystemPackageLPw(ps.name);
4371                    }
4372                    updatedPkgBetter = true;
4373                }
4374            }
4375        }
4376
4377        if (updatedPkg != null) {
4378            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4379            // initially
4380            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4381
4382            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4383            // flag set initially
4384            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
4385                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4386            }
4387        }
4388
4389        // Verify certificates against what was last scanned
4390        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4391
4392        /*
4393         * A new system app appeared, but we already had a non-system one of the
4394         * same name installed earlier.
4395         */
4396        boolean shouldHideSystemApp = false;
4397        if (updatedPkg == null && ps != null
4398                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4399            /*
4400             * Check to make sure the signatures match first. If they don't,
4401             * wipe the installed application and its data.
4402             */
4403            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4404                    != PackageManager.SIGNATURE_MATCH) {
4405                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
4406                        + " signatures don't match existing userdata copy; removing");
4407                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4408                ps = null;
4409            } else {
4410                /*
4411                 * If the newly-added system app is an older version than the
4412                 * already installed version, hide it. It will be scanned later
4413                 * and re-added like an update.
4414                 */
4415                if (pkg.mVersionCode <= ps.versionCode) {
4416                    shouldHideSystemApp = true;
4417                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
4418                            + " but new version " + pkg.mVersionCode + " better than installed "
4419                            + ps.versionCode + "; hiding system");
4420                } else {
4421                    /*
4422                     * The newly found system app is a newer version that the
4423                     * one previously installed. Simply remove the
4424                     * already-installed application and replace it with our own
4425                     * while keeping the application data.
4426                     */
4427                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4428                            + " reverting from " + ps.codePathString + ": new version "
4429                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
4430                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4431                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4432                            getAppDexInstructionSets(ps));
4433                    synchronized (mInstallLock) {
4434                        args.cleanUpResourcesLI();
4435                    }
4436                }
4437            }
4438        }
4439
4440        // The apk is forward locked (not public) if its code and resources
4441        // are kept in different files. (except for app in either system or
4442        // vendor path).
4443        // TODO grab this value from PackageSettings
4444        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4445            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4446                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4447            }
4448        }
4449
4450        // TODO: extend to support forward-locked splits
4451        String resourcePath = null;
4452        String baseResourcePath = null;
4453        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4454            if (ps != null && ps.resourcePathString != null) {
4455                resourcePath = ps.resourcePathString;
4456                baseResourcePath = ps.resourcePathString;
4457            } else {
4458                // Should not happen at all. Just log an error.
4459                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4460            }
4461        } else {
4462            resourcePath = pkg.codePath;
4463            baseResourcePath = pkg.baseCodePath;
4464        }
4465
4466        // Set application objects path explicitly.
4467        pkg.applicationInfo.setCodePath(pkg.codePath);
4468        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4469        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4470        pkg.applicationInfo.setResourcePath(resourcePath);
4471        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4472        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4473
4474        // Note that we invoke the following method only if we are about to unpack an application
4475        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4476                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4477
4478        /*
4479         * If the system app should be overridden by a previously installed
4480         * data, hide the system app now and let the /data/app scan pick it up
4481         * again.
4482         */
4483        if (shouldHideSystemApp) {
4484            synchronized (mPackages) {
4485                /*
4486                 * We have to grant systems permissions before we hide, because
4487                 * grantPermissions will assume the package update is trying to
4488                 * expand its permissions.
4489                 */
4490                grantPermissionsLPw(pkg, true, pkg.packageName);
4491                mSettings.disableSystemPackageLPw(pkg.packageName);
4492            }
4493        }
4494
4495        return scannedPkg;
4496    }
4497
4498    private static String fixProcessName(String defProcessName,
4499            String processName, int uid) {
4500        if (processName == null) {
4501            return defProcessName;
4502        }
4503        return processName;
4504    }
4505
4506    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4507            throws PackageManagerException {
4508        if (pkgSetting.signatures.mSignatures != null) {
4509            // Already existing package. Make sure signatures match
4510            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4511                    == PackageManager.SIGNATURE_MATCH;
4512            if (!match) {
4513                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4514                        == PackageManager.SIGNATURE_MATCH;
4515            }
4516            if (!match) {
4517                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
4518                        == PackageManager.SIGNATURE_MATCH;
4519            }
4520            if (!match) {
4521                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4522                        + pkg.packageName + " signatures do not match the "
4523                        + "previously installed version; ignoring!");
4524            }
4525        }
4526
4527        // Check for shared user signatures
4528        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4529            // Already existing package. Make sure signatures match
4530            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4531                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4532            if (!match) {
4533                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4534                        == PackageManager.SIGNATURE_MATCH;
4535            }
4536            if (!match) {
4537                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
4538                        == PackageManager.SIGNATURE_MATCH;
4539            }
4540            if (!match) {
4541                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4542                        "Package " + pkg.packageName
4543                        + " has no signatures that match those in shared user "
4544                        + pkgSetting.sharedUser.name + "; ignoring!");
4545            }
4546        }
4547    }
4548
4549    /**
4550     * Enforces that only the system UID or root's UID can call a method exposed
4551     * via Binder.
4552     *
4553     * @param message used as message if SecurityException is thrown
4554     * @throws SecurityException if the caller is not system or root
4555     */
4556    private static final void enforceSystemOrRoot(String message) {
4557        final int uid = Binder.getCallingUid();
4558        if (uid != Process.SYSTEM_UID && uid != 0) {
4559            throw new SecurityException(message);
4560        }
4561    }
4562
4563    @Override
4564    public void performBootDexOpt() {
4565        enforceSystemOrRoot("Only the system can request dexopt be performed");
4566
4567        // Before everything else, see whether we need to fstrim.
4568        try {
4569            IMountService ms = PackageHelper.getMountService();
4570            if (ms != null) {
4571                final boolean isUpgrade = isUpgrade();
4572                boolean doTrim = isUpgrade;
4573                if (doTrim) {
4574                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
4575                } else {
4576                    final long interval = android.provider.Settings.Global.getLong(
4577                            mContext.getContentResolver(),
4578                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
4579                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
4580                    if (interval > 0) {
4581                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
4582                        if (timeSinceLast > interval) {
4583                            doTrim = true;
4584                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
4585                                    + "; running immediately");
4586                        }
4587                    }
4588                }
4589                if (doTrim) {
4590                    if (!isFirstBoot()) {
4591                        try {
4592                            ActivityManagerNative.getDefault().showBootMessage(
4593                                    mContext.getResources().getString(
4594                                            R.string.android_upgrading_fstrim), true);
4595                        } catch (RemoteException e) {
4596                        }
4597                    }
4598                    ms.runMaintenance();
4599                }
4600            } else {
4601                Slog.e(TAG, "Mount service unavailable!");
4602            }
4603        } catch (RemoteException e) {
4604            // Can't happen; MountService is local
4605        }
4606
4607        final ArraySet<PackageParser.Package> pkgs;
4608        synchronized (mPackages) {
4609            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
4610        }
4611
4612        if (pkgs != null) {
4613            // Sort apps by importance for dexopt ordering. Important apps are given more priority
4614            // in case the device runs out of space.
4615            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
4616            // Give priority to core apps.
4617            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4618                PackageParser.Package pkg = it.next();
4619                if (pkg.coreApp) {
4620                    if (DEBUG_DEXOPT) {
4621                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
4622                    }
4623                    sortedPkgs.add(pkg);
4624                    it.remove();
4625                }
4626            }
4627            // Give priority to system apps that listen for pre boot complete.
4628            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
4629            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
4630            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4631                PackageParser.Package pkg = it.next();
4632                if (pkgNames.contains(pkg.packageName)) {
4633                    if (DEBUG_DEXOPT) {
4634                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
4635                    }
4636                    sortedPkgs.add(pkg);
4637                    it.remove();
4638                }
4639            }
4640            // Give priority to system apps.
4641            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4642                PackageParser.Package pkg = it.next();
4643                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4644                    if (DEBUG_DEXOPT) {
4645                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
4646                    }
4647                    sortedPkgs.add(pkg);
4648                    it.remove();
4649                }
4650            }
4651            // Give priority to updated system apps.
4652            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4653                PackageParser.Package pkg = it.next();
4654                if (isUpdatedSystemApp(pkg)) {
4655                    if (DEBUG_DEXOPT) {
4656                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
4657                    }
4658                    sortedPkgs.add(pkg);
4659                    it.remove();
4660                }
4661            }
4662            // Give priority to apps that listen for boot complete.
4663            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
4664            pkgNames = getPackageNamesForIntent(intent);
4665            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4666                PackageParser.Package pkg = it.next();
4667                if (pkgNames.contains(pkg.packageName)) {
4668                    if (DEBUG_DEXOPT) {
4669                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
4670                    }
4671                    sortedPkgs.add(pkg);
4672                    it.remove();
4673                }
4674            }
4675            // Filter out packages that aren't recently used.
4676            filterRecentlyUsedApps(pkgs);
4677            // Add all remaining apps.
4678            for (PackageParser.Package pkg : pkgs) {
4679                if (DEBUG_DEXOPT) {
4680                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
4681                }
4682                sortedPkgs.add(pkg);
4683            }
4684
4685            // If we want to be lazy, filter everything that wasn't recently used.
4686            if (mLazyDexOpt) {
4687                filterRecentlyUsedApps(sortedPkgs);
4688            }
4689
4690            int i = 0;
4691            int total = sortedPkgs.size();
4692            File dataDir = Environment.getDataDirectory();
4693            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
4694            if (lowThreshold == 0) {
4695                throw new IllegalStateException("Invalid low memory threshold");
4696            }
4697            for (PackageParser.Package pkg : sortedPkgs) {
4698                long usableSpace = dataDir.getUsableSpace();
4699                if (usableSpace < lowThreshold) {
4700                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
4701                    break;
4702                }
4703                performBootDexOpt(pkg, ++i, total);
4704            }
4705        }
4706    }
4707
4708    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
4709        // Filter out packages that aren't recently used.
4710        //
4711        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4712        // should do a full dexopt.
4713        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4714            int total = pkgs.size();
4715            int skipped = 0;
4716            long now = System.currentTimeMillis();
4717            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4718                PackageParser.Package pkg = i.next();
4719                long then = pkg.mLastPackageUsageTimeInMills;
4720                if (then + mDexOptLRUThresholdInMills < now) {
4721                    if (DEBUG_DEXOPT) {
4722                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4723                              ((then == 0) ? "never" : new Date(then)));
4724                    }
4725                    i.remove();
4726                    skipped++;
4727                }
4728            }
4729            if (DEBUG_DEXOPT) {
4730                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4731            }
4732        }
4733    }
4734
4735    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
4736        List<ResolveInfo> ris = null;
4737        try {
4738            ris = AppGlobals.getPackageManager().queryIntentReceivers(
4739                    intent, null, 0, UserHandle.USER_OWNER);
4740        } catch (RemoteException e) {
4741        }
4742        ArraySet<String> pkgNames = new ArraySet<String>();
4743        if (ris != null) {
4744            for (ResolveInfo ri : ris) {
4745                pkgNames.add(ri.activityInfo.packageName);
4746            }
4747        }
4748        return pkgNames;
4749    }
4750
4751    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
4752        if (DEBUG_DEXOPT) {
4753            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
4754        }
4755        if (!isFirstBoot()) {
4756            try {
4757                ActivityManagerNative.getDefault().showBootMessage(
4758                        mContext.getResources().getString(R.string.android_upgrading_apk,
4759                                curr, total), true);
4760            } catch (RemoteException e) {
4761            }
4762        }
4763        PackageParser.Package p = pkg;
4764        synchronized (mInstallLock) {
4765            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
4766                    false /* force dex */, false /* defer */, true /* include dependencies */);
4767        }
4768    }
4769
4770    @Override
4771    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4772        return performDexOpt(packageName, instructionSet, false);
4773    }
4774
4775    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4776        if (info.primaryCpuAbi == null) {
4777            return getPreferredInstructionSet();
4778        }
4779
4780        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4781    }
4782
4783    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4784        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4785        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4786        if (!dexopt && !updateUsage) {
4787            // We aren't going to dexopt or update usage, so bail early.
4788            return false;
4789        }
4790        PackageParser.Package p;
4791        final String targetInstructionSet;
4792        synchronized (mPackages) {
4793            p = mPackages.get(packageName);
4794            if (p == null) {
4795                return false;
4796            }
4797            if (updateUsage) {
4798                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4799            }
4800            mPackageUsage.write(false);
4801            if (!dexopt) {
4802                // We aren't going to dexopt, so bail early.
4803                return false;
4804            }
4805
4806            targetInstructionSet = instructionSet != null ? instructionSet :
4807                    getPrimaryInstructionSet(p.applicationInfo);
4808            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4809                return false;
4810            }
4811        }
4812
4813        synchronized (mInstallLock) {
4814            final String[] instructionSets = new String[] { targetInstructionSet };
4815            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
4816                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
4817            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
4818        }
4819    }
4820
4821    public ArraySet<String> getPackagesThatNeedDexOpt() {
4822        ArraySet<String> pkgs = null;
4823        synchronized (mPackages) {
4824            for (PackageParser.Package p : mPackages.values()) {
4825                if (DEBUG_DEXOPT) {
4826                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4827                }
4828                if (!p.mDexOptPerformed.isEmpty()) {
4829                    continue;
4830                }
4831                if (pkgs == null) {
4832                    pkgs = new ArraySet<String>();
4833                }
4834                pkgs.add(p.packageName);
4835            }
4836        }
4837        return pkgs;
4838    }
4839
4840    public void shutdown() {
4841        mPackageUsage.write(true);
4842    }
4843
4844    @Override
4845    public void forceDexOpt(String packageName) {
4846        enforceSystemOrRoot("forceDexOpt");
4847
4848        PackageParser.Package pkg;
4849        synchronized (mPackages) {
4850            pkg = mPackages.get(packageName);
4851            if (pkg == null) {
4852                throw new IllegalArgumentException("Missing package: " + packageName);
4853            }
4854        }
4855
4856        synchronized (mInstallLock) {
4857            final String[] instructionSets = new String[] {
4858                    getPrimaryInstructionSet(pkg.applicationInfo) };
4859            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
4860                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
4861            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
4862                throw new IllegalStateException("Failed to dexopt: " + res);
4863            }
4864        }
4865    }
4866
4867    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4868        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4869            Slog.w(TAG, "Unable to update from " + oldPkg.name
4870                    + " to " + newPkg.packageName
4871                    + ": old package not in system partition");
4872            return false;
4873        } else if (mPackages.get(oldPkg.name) != null) {
4874            Slog.w(TAG, "Unable to update from " + oldPkg.name
4875                    + " to " + newPkg.packageName
4876                    + ": old package still exists");
4877            return false;
4878        }
4879        return true;
4880    }
4881
4882    private File getDataPathForPackage(String packageName, int userId) {
4883        /*
4884         * Until we fully support multiple users, return the directory we
4885         * previously would have. The PackageManagerTests will need to be
4886         * revised when this is changed back..
4887         */
4888        if (userId == 0) {
4889            return new File(mAppDataDir, packageName);
4890        } else {
4891            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4892                + File.separator + packageName);
4893        }
4894    }
4895
4896    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4897        int[] users = sUserManager.getUserIds();
4898        int res = mInstaller.install(packageName, uid, uid, seinfo);
4899        if (res < 0) {
4900            return res;
4901        }
4902        for (int user : users) {
4903            if (user != 0) {
4904                res = mInstaller.createUserData(packageName,
4905                        UserHandle.getUid(user, uid), user, seinfo);
4906                if (res < 0) {
4907                    return res;
4908                }
4909            }
4910        }
4911        return res;
4912    }
4913
4914    private int removeDataDirsLI(String packageName) {
4915        int[] users = sUserManager.getUserIds();
4916        int res = 0;
4917        for (int user : users) {
4918            int resInner = mInstaller.remove(packageName, user);
4919            if (resInner < 0) {
4920                res = resInner;
4921            }
4922        }
4923
4924        return res;
4925    }
4926
4927    private int deleteCodeCacheDirsLI(String packageName) {
4928        int[] users = sUserManager.getUserIds();
4929        int res = 0;
4930        for (int user : users) {
4931            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4932            if (resInner < 0) {
4933                res = resInner;
4934            }
4935        }
4936        return res;
4937    }
4938
4939    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4940            PackageParser.Package changingLib) {
4941        if (file.path != null) {
4942            usesLibraryFiles.add(file.path);
4943            return;
4944        }
4945        PackageParser.Package p = mPackages.get(file.apk);
4946        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4947            // If we are doing this while in the middle of updating a library apk,
4948            // then we need to make sure to use that new apk for determining the
4949            // dependencies here.  (We haven't yet finished committing the new apk
4950            // to the package manager state.)
4951            if (p == null || p.packageName.equals(changingLib.packageName)) {
4952                p = changingLib;
4953            }
4954        }
4955        if (p != null) {
4956            usesLibraryFiles.addAll(p.getAllCodePaths());
4957        }
4958    }
4959
4960    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4961            PackageParser.Package changingLib) throws PackageManagerException {
4962        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4963            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4964            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4965            for (int i=0; i<N; i++) {
4966                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4967                if (file == null) {
4968                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4969                            "Package " + pkg.packageName + " requires unavailable shared library "
4970                            + pkg.usesLibraries.get(i) + "; failing!");
4971                }
4972                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4973            }
4974            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4975            for (int i=0; i<N; i++) {
4976                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4977                if (file == null) {
4978                    Slog.w(TAG, "Package " + pkg.packageName
4979                            + " desires unavailable shared library "
4980                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4981                } else {
4982                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4983                }
4984            }
4985            N = usesLibraryFiles.size();
4986            if (N > 0) {
4987                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4988            } else {
4989                pkg.usesLibraryFiles = null;
4990            }
4991        }
4992    }
4993
4994    private static boolean hasString(List<String> list, List<String> which) {
4995        if (list == null) {
4996            return false;
4997        }
4998        for (int i=list.size()-1; i>=0; i--) {
4999            for (int j=which.size()-1; j>=0; j--) {
5000                if (which.get(j).equals(list.get(i))) {
5001                    return true;
5002                }
5003            }
5004        }
5005        return false;
5006    }
5007
5008    private void updateAllSharedLibrariesLPw() {
5009        for (PackageParser.Package pkg : mPackages.values()) {
5010            try {
5011                updateSharedLibrariesLPw(pkg, null);
5012            } catch (PackageManagerException e) {
5013                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5014            }
5015        }
5016    }
5017
5018    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5019            PackageParser.Package changingPkg) {
5020        ArrayList<PackageParser.Package> res = null;
5021        for (PackageParser.Package pkg : mPackages.values()) {
5022            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5023                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5024                if (res == null) {
5025                    res = new ArrayList<PackageParser.Package>();
5026                }
5027                res.add(pkg);
5028                try {
5029                    updateSharedLibrariesLPw(pkg, changingPkg);
5030                } catch (PackageManagerException e) {
5031                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5032                }
5033            }
5034        }
5035        return res;
5036    }
5037
5038    /**
5039     * Derive the value of the {@code cpuAbiOverride} based on the provided
5040     * value and an optional stored value from the package settings.
5041     */
5042    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5043        String cpuAbiOverride = null;
5044
5045        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5046            cpuAbiOverride = null;
5047        } else if (abiOverride != null) {
5048            cpuAbiOverride = abiOverride;
5049        } else if (settings != null) {
5050            cpuAbiOverride = settings.cpuAbiOverrideString;
5051        }
5052
5053        return cpuAbiOverride;
5054    }
5055
5056    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5057            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5058        boolean success = false;
5059        try {
5060            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5061                    currentTime, user);
5062            success = true;
5063            return res;
5064        } finally {
5065            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5066                removeDataDirsLI(pkg.packageName);
5067            }
5068        }
5069    }
5070
5071    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5072            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5073        final File scanFile = new File(pkg.codePath);
5074        if (pkg.applicationInfo.getCodePath() == null ||
5075                pkg.applicationInfo.getResourcePath() == null) {
5076            // Bail out. The resource and code paths haven't been set.
5077            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5078                    "Code and resource paths haven't been set correctly");
5079        }
5080
5081        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5082            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5083        } else {
5084            // Only allow system apps to be flagged as core apps.
5085            pkg.coreApp = false;
5086        }
5087
5088        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5089            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5090        }
5091
5092        if (mCustomResolverComponentName != null &&
5093                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5094            setUpCustomResolverActivity(pkg);
5095        }
5096
5097        if (pkg.packageName.equals("android")) {
5098            synchronized (mPackages) {
5099                if (mAndroidApplication != null) {
5100                    Slog.w(TAG, "*************************************************");
5101                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5102                    Slog.w(TAG, " file=" + scanFile);
5103                    Slog.w(TAG, "*************************************************");
5104                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5105                            "Core android package being redefined.  Skipping.");
5106                }
5107
5108                // Set up information for our fall-back user intent resolution activity.
5109                mPlatformPackage = pkg;
5110                pkg.mVersionCode = mSdkVersion;
5111                mAndroidApplication = pkg.applicationInfo;
5112
5113                if (!mResolverReplaced) {
5114                    mResolveActivity.applicationInfo = mAndroidApplication;
5115                    mResolveActivity.name = ResolverActivity.class.getName();
5116                    mResolveActivity.packageName = mAndroidApplication.packageName;
5117                    mResolveActivity.processName = "system:ui";
5118                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5119                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5120                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5121                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5122                    mResolveActivity.exported = true;
5123                    mResolveActivity.enabled = true;
5124                    mResolveInfo.activityInfo = mResolveActivity;
5125                    mResolveInfo.priority = 0;
5126                    mResolveInfo.preferredOrder = 0;
5127                    mResolveInfo.match = 0;
5128                    mResolveComponentName = new ComponentName(
5129                            mAndroidApplication.packageName, mResolveActivity.name);
5130                }
5131            }
5132        }
5133
5134        if (DEBUG_PACKAGE_SCANNING) {
5135            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5136                Log.d(TAG, "Scanning package " + pkg.packageName);
5137        }
5138
5139        if (mPackages.containsKey(pkg.packageName)
5140                || mSharedLibraries.containsKey(pkg.packageName)) {
5141            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5142                    "Application package " + pkg.packageName
5143                    + " already installed.  Skipping duplicate.");
5144        }
5145
5146        // Initialize package source and resource directories
5147        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5148        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5149
5150        SharedUserSetting suid = null;
5151        PackageSetting pkgSetting = null;
5152
5153        if (!isSystemApp(pkg)) {
5154            // Only system apps can use these features.
5155            pkg.mOriginalPackages = null;
5156            pkg.mRealPackage = null;
5157            pkg.mAdoptPermissions = null;
5158        }
5159
5160        // writer
5161        synchronized (mPackages) {
5162            if (pkg.mSharedUserId != null) {
5163                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5164                if (suid == null) {
5165                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5166                            "Creating application package " + pkg.packageName
5167                            + " for shared user failed");
5168                }
5169                if (DEBUG_PACKAGE_SCANNING) {
5170                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5171                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5172                                + "): packages=" + suid.packages);
5173                }
5174            }
5175
5176            // Check if we are renaming from an original package name.
5177            PackageSetting origPackage = null;
5178            String realName = null;
5179            if (pkg.mOriginalPackages != null) {
5180                // This package may need to be renamed to a previously
5181                // installed name.  Let's check on that...
5182                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5183                if (pkg.mOriginalPackages.contains(renamed)) {
5184                    // This package had originally been installed as the
5185                    // original name, and we have already taken care of
5186                    // transitioning to the new one.  Just update the new
5187                    // one to continue using the old name.
5188                    realName = pkg.mRealPackage;
5189                    if (!pkg.packageName.equals(renamed)) {
5190                        // Callers into this function may have already taken
5191                        // care of renaming the package; only do it here if
5192                        // it is not already done.
5193                        pkg.setPackageName(renamed);
5194                    }
5195
5196                } else {
5197                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5198                        if ((origPackage = mSettings.peekPackageLPr(
5199                                pkg.mOriginalPackages.get(i))) != null) {
5200                            // We do have the package already installed under its
5201                            // original name...  should we use it?
5202                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5203                                // New package is not compatible with original.
5204                                origPackage = null;
5205                                continue;
5206                            } else if (origPackage.sharedUser != null) {
5207                                // Make sure uid is compatible between packages.
5208                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5209                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5210                                            + " to " + pkg.packageName + ": old uid "
5211                                            + origPackage.sharedUser.name
5212                                            + " differs from " + pkg.mSharedUserId);
5213                                    origPackage = null;
5214                                    continue;
5215                                }
5216                            } else {
5217                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5218                                        + pkg.packageName + " to old name " + origPackage.name);
5219                            }
5220                            break;
5221                        }
5222                    }
5223                }
5224            }
5225
5226            if (mTransferedPackages.contains(pkg.packageName)) {
5227                Slog.w(TAG, "Package " + pkg.packageName
5228                        + " was transferred to another, but its .apk remains");
5229            }
5230
5231            // Just create the setting, don't add it yet. For already existing packages
5232            // the PkgSetting exists already and doesn't have to be created.
5233            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5234                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5235                    pkg.applicationInfo.primaryCpuAbi,
5236                    pkg.applicationInfo.secondaryCpuAbi,
5237                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
5238                    user, false);
5239            if (pkgSetting == null) {
5240                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5241                        "Creating application package " + pkg.packageName + " failed");
5242            }
5243
5244            if (pkgSetting.origPackage != null) {
5245                // If we are first transitioning from an original package,
5246                // fix up the new package's name now.  We need to do this after
5247                // looking up the package under its new name, so getPackageLP
5248                // can take care of fiddling things correctly.
5249                pkg.setPackageName(origPackage.name);
5250
5251                // File a report about this.
5252                String msg = "New package " + pkgSetting.realName
5253                        + " renamed to replace old package " + pkgSetting.name;
5254                reportSettingsProblem(Log.WARN, msg);
5255
5256                // Make a note of it.
5257                mTransferedPackages.add(origPackage.name);
5258
5259                // No longer need to retain this.
5260                pkgSetting.origPackage = null;
5261            }
5262
5263            if (realName != null) {
5264                // Make a note of it.
5265                mTransferedPackages.add(pkg.packageName);
5266            }
5267
5268            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5269                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5270            }
5271
5272            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5273                // Check all shared libraries and map to their actual file path.
5274                // We only do this here for apps not on a system dir, because those
5275                // are the only ones that can fail an install due to this.  We
5276                // will take care of the system apps by updating all of their
5277                // library paths after the scan is done.
5278                updateSharedLibrariesLPw(pkg, null);
5279            }
5280
5281            if (mFoundPolicyFile) {
5282                SELinuxMMAC.assignSeinfoValue(pkg);
5283            }
5284
5285            pkg.applicationInfo.uid = pkgSetting.appId;
5286            pkg.mExtras = pkgSetting;
5287            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5288                try {
5289                    verifySignaturesLP(pkgSetting, pkg);
5290                    // We just determined the app is signed correctly, so bring
5291                    // over the latest parsed certs.
5292                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5293                } catch (PackageManagerException e) {
5294                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5295                        throw e;
5296                    }
5297                    // The signature has changed, but this package is in the system
5298                    // image...  let's recover!
5299                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5300                    // However...  if this package is part of a shared user, but it
5301                    // doesn't match the signature of the shared user, let's fail.
5302                    // What this means is that you can't change the signatures
5303                    // associated with an overall shared user, which doesn't seem all
5304                    // that unreasonable.
5305                    if (pkgSetting.sharedUser != null) {
5306                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5307                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5308                            throw new PackageManagerException(
5309                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5310                                            "Signature mismatch for shared user : "
5311                                            + pkgSetting.sharedUser);
5312                        }
5313                    }
5314                    // File a report about this.
5315                    String msg = "System package " + pkg.packageName
5316                        + " signature changed; retaining data.";
5317                    reportSettingsProblem(Log.WARN, msg);
5318                }
5319            } else {
5320                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5321                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5322                            + pkg.packageName + " upgrade keys do not match the "
5323                            + "previously installed version");
5324                } else {
5325                    // We just determined the app is signed correctly, so bring
5326                    // over the latest parsed certs.
5327                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5328                }
5329            }
5330            // Verify that this new package doesn't have any content providers
5331            // that conflict with existing packages.  Only do this if the
5332            // package isn't already installed, since we don't want to break
5333            // things that are installed.
5334            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5335                final int N = pkg.providers.size();
5336                int i;
5337                for (i=0; i<N; i++) {
5338                    PackageParser.Provider p = pkg.providers.get(i);
5339                    if (p.info.authority != null) {
5340                        String names[] = p.info.authority.split(";");
5341                        for (int j = 0; j < names.length; j++) {
5342                            if (mProvidersByAuthority.containsKey(names[j])) {
5343                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5344                                final String otherPackageName =
5345                                        ((other != null && other.getComponentName() != null) ?
5346                                                other.getComponentName().getPackageName() : "?");
5347                                throw new PackageManagerException(
5348                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5349                                                "Can't install because provider name " + names[j]
5350                                                + " (in package " + pkg.applicationInfo.packageName
5351                                                + ") is already used by " + otherPackageName);
5352                            }
5353                        }
5354                    }
5355                }
5356            }
5357
5358            if (pkg.mAdoptPermissions != null) {
5359                // This package wants to adopt ownership of permissions from
5360                // another package.
5361                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5362                    final String origName = pkg.mAdoptPermissions.get(i);
5363                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5364                    if (orig != null) {
5365                        if (verifyPackageUpdateLPr(orig, pkg)) {
5366                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5367                                    + pkg.packageName);
5368                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5369                        }
5370                    }
5371                }
5372            }
5373        }
5374
5375        final String pkgName = pkg.packageName;
5376
5377        final long scanFileTime = scanFile.lastModified();
5378        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5379        pkg.applicationInfo.processName = fixProcessName(
5380                pkg.applicationInfo.packageName,
5381                pkg.applicationInfo.processName,
5382                pkg.applicationInfo.uid);
5383
5384        File dataPath;
5385        if (mPlatformPackage == pkg) {
5386            // The system package is special.
5387            dataPath = new File(Environment.getDataDirectory(), "system");
5388
5389            pkg.applicationInfo.dataDir = dataPath.getPath();
5390
5391        } else {
5392            // This is a normal package, need to make its data directory.
5393            dataPath = getDataPathForPackage(pkg.packageName, 0);
5394
5395            boolean uidError = false;
5396            if (dataPath.exists()) {
5397                int currentUid = 0;
5398                try {
5399                    StructStat stat = Os.stat(dataPath.getPath());
5400                    currentUid = stat.st_uid;
5401                } catch (ErrnoException e) {
5402                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5403                }
5404
5405                // If we have mismatched owners for the data path, we have a problem.
5406                if (currentUid != pkg.applicationInfo.uid) {
5407                    boolean recovered = false;
5408                    if (currentUid == 0) {
5409                        // The directory somehow became owned by root.  Wow.
5410                        // This is probably because the system was stopped while
5411                        // installd was in the middle of messing with its libs
5412                        // directory.  Ask installd to fix that.
5413                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5414                                pkg.applicationInfo.uid);
5415                        if (ret >= 0) {
5416                            recovered = true;
5417                            String msg = "Package " + pkg.packageName
5418                                    + " unexpectedly changed to uid 0; recovered to " +
5419                                    + pkg.applicationInfo.uid;
5420                            reportSettingsProblem(Log.WARN, msg);
5421                        }
5422                    }
5423                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5424                            || (scanFlags&SCAN_BOOTING) != 0)) {
5425                        // If this is a system app, we can at least delete its
5426                        // current data so the application will still work.
5427                        int ret = removeDataDirsLI(pkgName);
5428                        if (ret >= 0) {
5429                            // TODO: Kill the processes first
5430                            // Old data gone!
5431                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5432                                    ? "System package " : "Third party package ";
5433                            String msg = prefix + pkg.packageName
5434                                    + " has changed from uid: "
5435                                    + currentUid + " to "
5436                                    + pkg.applicationInfo.uid + "; old data erased";
5437                            reportSettingsProblem(Log.WARN, msg);
5438                            recovered = true;
5439
5440                            // And now re-install the app.
5441                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5442                                                   pkg.applicationInfo.seinfo);
5443                            if (ret == -1) {
5444                                // Ack should not happen!
5445                                msg = prefix + pkg.packageName
5446                                        + " could not have data directory re-created after delete.";
5447                                reportSettingsProblem(Log.WARN, msg);
5448                                throw new PackageManagerException(
5449                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5450                            }
5451                        }
5452                        if (!recovered) {
5453                            mHasSystemUidErrors = true;
5454                        }
5455                    } else if (!recovered) {
5456                        // If we allow this install to proceed, we will be broken.
5457                        // Abort, abort!
5458                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5459                                "scanPackageLI");
5460                    }
5461                    if (!recovered) {
5462                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5463                            + pkg.applicationInfo.uid + "/fs_"
5464                            + currentUid;
5465                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5466                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5467                        String msg = "Package " + pkg.packageName
5468                                + " has mismatched uid: "
5469                                + currentUid + " on disk, "
5470                                + pkg.applicationInfo.uid + " in settings";
5471                        // writer
5472                        synchronized (mPackages) {
5473                            mSettings.mReadMessages.append(msg);
5474                            mSettings.mReadMessages.append('\n');
5475                            uidError = true;
5476                            if (!pkgSetting.uidError) {
5477                                reportSettingsProblem(Log.ERROR, msg);
5478                            }
5479                        }
5480                    }
5481                }
5482                pkg.applicationInfo.dataDir = dataPath.getPath();
5483                if (mShouldRestoreconData) {
5484                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5485                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5486                                pkg.applicationInfo.uid);
5487                }
5488            } else {
5489                if (DEBUG_PACKAGE_SCANNING) {
5490                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5491                        Log.v(TAG, "Want this data dir: " + dataPath);
5492                }
5493                //invoke installer to do the actual installation
5494                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5495                                           pkg.applicationInfo.seinfo);
5496                if (ret < 0) {
5497                    // Error from installer
5498                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5499                            "Unable to create data dirs [errorCode=" + ret + "]");
5500                }
5501
5502                if (dataPath.exists()) {
5503                    pkg.applicationInfo.dataDir = dataPath.getPath();
5504                } else {
5505                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5506                    pkg.applicationInfo.dataDir = null;
5507                }
5508            }
5509
5510            pkgSetting.uidError = uidError;
5511        }
5512
5513        final String path = scanFile.getPath();
5514        final String codePath = pkg.applicationInfo.getCodePath();
5515        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5516        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5517            setBundledAppAbisAndRoots(pkg, pkgSetting);
5518
5519            // If we haven't found any native libraries for the app, check if it has
5520            // renderscript code. We'll need to force the app to 32 bit if it has
5521            // renderscript bitcode.
5522            if (pkg.applicationInfo.primaryCpuAbi == null
5523                    && pkg.applicationInfo.secondaryCpuAbi == null
5524                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5525                NativeLibraryHelper.Handle handle = null;
5526                try {
5527                    handle = NativeLibraryHelper.Handle.create(scanFile);
5528                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5529                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5530                    }
5531                } catch (IOException ioe) {
5532                    Slog.w(TAG, "Error scanning system app : " + ioe);
5533                } finally {
5534                    IoUtils.closeQuietly(handle);
5535                }
5536            }
5537
5538            setNativeLibraryPaths(pkg);
5539        } else {
5540            // TODO: We can probably be smarter about this stuff. For installed apps,
5541            // we can calculate this information at install time once and for all. For
5542            // system apps, we can probably assume that this information doesn't change
5543            // after the first boot scan. As things stand, we do lots of unnecessary work.
5544
5545            // Give ourselves some initial paths; we'll come back for another
5546            // pass once we've determined ABI below.
5547            setNativeLibraryPaths(pkg);
5548
5549            final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg);
5550            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5551            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5552
5553            NativeLibraryHelper.Handle handle = null;
5554            try {
5555                handle = NativeLibraryHelper.Handle.create(scanFile);
5556                // TODO(multiArch): This can be null for apps that didn't go through the
5557                // usual installation process. We can calculate it again, like we
5558                // do during install time.
5559                //
5560                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5561                // unnecessary.
5562                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5563
5564                // Null out the abis so that they can be recalculated.
5565                pkg.applicationInfo.primaryCpuAbi = null;
5566                pkg.applicationInfo.secondaryCpuAbi = null;
5567                if (isMultiArch(pkg.applicationInfo)) {
5568                    // Warn if we've set an abiOverride for multi-lib packages..
5569                    // By definition, we need to copy both 32 and 64 bit libraries for
5570                    // such packages.
5571                    if (pkg.cpuAbiOverride != null
5572                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5573                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5574                    }
5575
5576                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5577                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5578                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5579                        if (isAsec) {
5580                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5581                        } else {
5582                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5583                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5584                                    useIsaSpecificSubdirs);
5585                        }
5586                    }
5587
5588                    maybeThrowExceptionForMultiArchCopy(
5589                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5590
5591                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5592                        if (isAsec) {
5593                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5594                        } else {
5595                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5596                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5597                                    useIsaSpecificSubdirs);
5598                        }
5599                    }
5600
5601                    maybeThrowExceptionForMultiArchCopy(
5602                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5603
5604                    if (abi64 >= 0) {
5605                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5606                    }
5607
5608                    if (abi32 >= 0) {
5609                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5610                        if (abi64 >= 0) {
5611                            pkg.applicationInfo.secondaryCpuAbi = abi;
5612                        } else {
5613                            pkg.applicationInfo.primaryCpuAbi = abi;
5614                        }
5615                    }
5616                } else {
5617                    String[] abiList = (cpuAbiOverride != null) ?
5618                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5619
5620                    // Enable gross and lame hacks for apps that are built with old
5621                    // SDK tools. We must scan their APKs for renderscript bitcode and
5622                    // not launch them if it's present. Don't bother checking on devices
5623                    // that don't have 64 bit support.
5624                    boolean needsRenderScriptOverride = false;
5625                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5626                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5627                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5628                        needsRenderScriptOverride = true;
5629                    }
5630
5631                    final int copyRet;
5632                    if (isAsec) {
5633                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5634                    } else {
5635                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5636                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5637                    }
5638
5639                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5640                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5641                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5642                    }
5643
5644                    if (copyRet >= 0) {
5645                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5646                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5647                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5648                    } else if (needsRenderScriptOverride) {
5649                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5650                    }
5651                }
5652            } catch (IOException ioe) {
5653                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5654            } finally {
5655                IoUtils.closeQuietly(handle);
5656            }
5657
5658            // Now that we've calculated the ABIs and determined if it's an internal app,
5659            // we will go ahead and populate the nativeLibraryPath.
5660            setNativeLibraryPaths(pkg);
5661
5662            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5663            final int[] userIds = sUserManager.getUserIds();
5664            synchronized (mInstallLock) {
5665                // Create a native library symlink only if we have native libraries
5666                // and if the native libraries are 32 bit libraries. We do not provide
5667                // this symlink for 64 bit libraries.
5668                if (pkg.applicationInfo.primaryCpuAbi != null &&
5669                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5670                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5671                    for (int userId : userIds) {
5672                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5673                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5674                                    "Failed linking native library dir (user=" + userId + ")");
5675                        }
5676                    }
5677                }
5678            }
5679        }
5680
5681        // This is a special case for the "system" package, where the ABI is
5682        // dictated by the zygote configuration (and init.rc). We should keep track
5683        // of this ABI so that we can deal with "normal" applications that run under
5684        // the same UID correctly.
5685        if (mPlatformPackage == pkg) {
5686            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5687                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5688        }
5689
5690        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5691        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5692        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5693        // Copy the derived override back to the parsed package, so that we can
5694        // update the package settings accordingly.
5695        pkg.cpuAbiOverride = cpuAbiOverride;
5696
5697        if (DEBUG_ABI_SELECTION) {
5698            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5699                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5700                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5701        }
5702
5703        // Push the derived path down into PackageSettings so we know what to
5704        // clean up at uninstall time.
5705        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5706
5707        if (DEBUG_ABI_SELECTION) {
5708            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5709                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5710                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5711        }
5712
5713        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5714            // We don't do this here during boot because we can do it all
5715            // at once after scanning all existing packages.
5716            //
5717            // We also do this *before* we perform dexopt on this package, so that
5718            // we can avoid redundant dexopts, and also to make sure we've got the
5719            // code and package path correct.
5720            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5721                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5722        }
5723
5724        if ((scanFlags & SCAN_NO_DEX) == 0) {
5725            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
5726                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
5727            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
5728                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5729            }
5730        }
5731
5732        if (mFactoryTest && pkg.requestedPermissions.contains(
5733                android.Manifest.permission.FACTORY_TEST)) {
5734            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5735        }
5736
5737        ArrayList<PackageParser.Package> clientLibPkgs = null;
5738
5739        // writer
5740        synchronized (mPackages) {
5741            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5742                // Only system apps can add new shared libraries.
5743                if (pkg.libraryNames != null) {
5744                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5745                        String name = pkg.libraryNames.get(i);
5746                        boolean allowed = false;
5747                        if (isUpdatedSystemApp(pkg)) {
5748                            // New library entries can only be added through the
5749                            // system image.  This is important to get rid of a lot
5750                            // of nasty edge cases: for example if we allowed a non-
5751                            // system update of the app to add a library, then uninstalling
5752                            // the update would make the library go away, and assumptions
5753                            // we made such as through app install filtering would now
5754                            // have allowed apps on the device which aren't compatible
5755                            // with it.  Better to just have the restriction here, be
5756                            // conservative, and create many fewer cases that can negatively
5757                            // impact the user experience.
5758                            final PackageSetting sysPs = mSettings
5759                                    .getDisabledSystemPkgLPr(pkg.packageName);
5760                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5761                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5762                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5763                                        allowed = true;
5764                                        allowed = true;
5765                                        break;
5766                                    }
5767                                }
5768                            }
5769                        } else {
5770                            allowed = true;
5771                        }
5772                        if (allowed) {
5773                            if (!mSharedLibraries.containsKey(name)) {
5774                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5775                            } else if (!name.equals(pkg.packageName)) {
5776                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5777                                        + name + " already exists; skipping");
5778                            }
5779                        } else {
5780                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5781                                    + name + " that is not declared on system image; skipping");
5782                        }
5783                    }
5784                    if ((scanFlags&SCAN_BOOTING) == 0) {
5785                        // If we are not booting, we need to update any applications
5786                        // that are clients of our shared library.  If we are booting,
5787                        // this will all be done once the scan is complete.
5788                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5789                    }
5790                }
5791            }
5792        }
5793
5794        // We also need to dexopt any apps that are dependent on this library.  Note that
5795        // if these fail, we should abort the install since installing the library will
5796        // result in some apps being broken.
5797        if (clientLibPkgs != null) {
5798            if ((scanFlags & SCAN_NO_DEX) == 0) {
5799                for (int i = 0; i < clientLibPkgs.size(); i++) {
5800                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5801                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
5802                            null /* instruction sets */, forceDex,
5803                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
5804                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
5805                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5806                                "scanPackageLI failed to dexopt clientLibPkgs");
5807                    }
5808                }
5809            }
5810        }
5811
5812        // Request the ActivityManager to kill the process(only for existing packages)
5813        // so that we do not end up in a confused state while the user is still using the older
5814        // version of the application while the new one gets installed.
5815        if ((scanFlags & SCAN_REPLACING) != 0) {
5816            killApplication(pkg.applicationInfo.packageName,
5817                        pkg.applicationInfo.uid, "update pkg");
5818        }
5819
5820        // Also need to kill any apps that are dependent on the library.
5821        if (clientLibPkgs != null) {
5822            for (int i=0; i<clientLibPkgs.size(); i++) {
5823                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5824                killApplication(clientPkg.applicationInfo.packageName,
5825                        clientPkg.applicationInfo.uid, "update lib");
5826            }
5827        }
5828
5829        // writer
5830        synchronized (mPackages) {
5831            // We don't expect installation to fail beyond this point
5832
5833            // Add the new setting to mSettings
5834            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5835            // Add the new setting to mPackages
5836            mPackages.put(pkg.applicationInfo.packageName, pkg);
5837            // Make sure we don't accidentally delete its data.
5838            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5839            while (iter.hasNext()) {
5840                PackageCleanItem item = iter.next();
5841                if (pkgName.equals(item.packageName)) {
5842                    iter.remove();
5843                }
5844            }
5845
5846            // Take care of first install / last update times.
5847            if (currentTime != 0) {
5848                if (pkgSetting.firstInstallTime == 0) {
5849                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5850                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5851                    pkgSetting.lastUpdateTime = currentTime;
5852                }
5853            } else if (pkgSetting.firstInstallTime == 0) {
5854                // We need *something*.  Take time time stamp of the file.
5855                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5856            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5857                if (scanFileTime != pkgSetting.timeStamp) {
5858                    // A package on the system image has changed; consider this
5859                    // to be an update.
5860                    pkgSetting.lastUpdateTime = scanFileTime;
5861                }
5862            }
5863
5864            // Add the package's KeySets to the global KeySetManagerService
5865            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5866            try {
5867                // Old KeySetData no longer valid.
5868                ksms.removeAppKeySetDataLPw(pkg.packageName);
5869                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5870                if (pkg.mKeySetMapping != null) {
5871                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5872                            pkg.mKeySetMapping.entrySet()) {
5873                        if (entry.getValue() != null) {
5874                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5875                                                          entry.getValue(), entry.getKey());
5876                        }
5877                    }
5878                    if (pkg.mUpgradeKeySets != null) {
5879                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5880                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5881                        }
5882                    }
5883                }
5884            } catch (NullPointerException e) {
5885                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5886            } catch (IllegalArgumentException e) {
5887                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5888            }
5889
5890            int N = pkg.providers.size();
5891            StringBuilder r = null;
5892            int i;
5893            for (i=0; i<N; i++) {
5894                PackageParser.Provider p = pkg.providers.get(i);
5895                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5896                        p.info.processName, pkg.applicationInfo.uid);
5897                mProviders.addProvider(p);
5898                p.syncable = p.info.isSyncable;
5899                if (p.info.authority != null) {
5900                    String names[] = p.info.authority.split(";");
5901                    p.info.authority = null;
5902                    for (int j = 0; j < names.length; j++) {
5903                        if (j == 1 && p.syncable) {
5904                            // We only want the first authority for a provider to possibly be
5905                            // syncable, so if we already added this provider using a different
5906                            // authority clear the syncable flag. We copy the provider before
5907                            // changing it because the mProviders object contains a reference
5908                            // to a provider that we don't want to change.
5909                            // Only do this for the second authority since the resulting provider
5910                            // object can be the same for all future authorities for this provider.
5911                            p = new PackageParser.Provider(p);
5912                            p.syncable = false;
5913                        }
5914                        if (!mProvidersByAuthority.containsKey(names[j])) {
5915                            mProvidersByAuthority.put(names[j], p);
5916                            if (p.info.authority == null) {
5917                                p.info.authority = names[j];
5918                            } else {
5919                                p.info.authority = p.info.authority + ";" + names[j];
5920                            }
5921                            if (DEBUG_PACKAGE_SCANNING) {
5922                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5923                                    Log.d(TAG, "Registered content provider: " + names[j]
5924                                            + ", className = " + p.info.name + ", isSyncable = "
5925                                            + p.info.isSyncable);
5926                            }
5927                        } else {
5928                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5929                            Slog.w(TAG, "Skipping provider name " + names[j] +
5930                                    " (in package " + pkg.applicationInfo.packageName +
5931                                    "): name already used by "
5932                                    + ((other != null && other.getComponentName() != null)
5933                                            ? other.getComponentName().getPackageName() : "?"));
5934                        }
5935                    }
5936                }
5937                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5938                    if (r == null) {
5939                        r = new StringBuilder(256);
5940                    } else {
5941                        r.append(' ');
5942                    }
5943                    r.append(p.info.name);
5944                }
5945            }
5946            if (r != null) {
5947                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5948            }
5949
5950            N = pkg.services.size();
5951            r = null;
5952            for (i=0; i<N; i++) {
5953                PackageParser.Service s = pkg.services.get(i);
5954                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5955                        s.info.processName, pkg.applicationInfo.uid);
5956                mServices.addService(s);
5957                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5958                    if (r == null) {
5959                        r = new StringBuilder(256);
5960                    } else {
5961                        r.append(' ');
5962                    }
5963                    r.append(s.info.name);
5964                }
5965            }
5966            if (r != null) {
5967                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5968            }
5969
5970            N = pkg.receivers.size();
5971            r = null;
5972            for (i=0; i<N; i++) {
5973                PackageParser.Activity a = pkg.receivers.get(i);
5974                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5975                        a.info.processName, pkg.applicationInfo.uid);
5976                mReceivers.addActivity(a, "receiver");
5977                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5978                    if (r == null) {
5979                        r = new StringBuilder(256);
5980                    } else {
5981                        r.append(' ');
5982                    }
5983                    r.append(a.info.name);
5984                }
5985            }
5986            if (r != null) {
5987                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5988            }
5989
5990            N = pkg.activities.size();
5991            r = null;
5992            for (i=0; i<N; i++) {
5993                PackageParser.Activity a = pkg.activities.get(i);
5994                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5995                        a.info.processName, pkg.applicationInfo.uid);
5996                mActivities.addActivity(a, "activity");
5997                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5998                    if (r == null) {
5999                        r = new StringBuilder(256);
6000                    } else {
6001                        r.append(' ');
6002                    }
6003                    r.append(a.info.name);
6004                }
6005            }
6006            if (r != null) {
6007                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6008            }
6009
6010            N = pkg.permissionGroups.size();
6011            r = null;
6012            for (i=0; i<N; i++) {
6013                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6014                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6015                if (cur == null) {
6016                    mPermissionGroups.put(pg.info.name, pg);
6017                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6018                        if (r == null) {
6019                            r = new StringBuilder(256);
6020                        } else {
6021                            r.append(' ');
6022                        }
6023                        r.append(pg.info.name);
6024                    }
6025                } else {
6026                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6027                            + pg.info.packageName + " ignored: original from "
6028                            + cur.info.packageName);
6029                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6030                        if (r == null) {
6031                            r = new StringBuilder(256);
6032                        } else {
6033                            r.append(' ');
6034                        }
6035                        r.append("DUP:");
6036                        r.append(pg.info.name);
6037                    }
6038                }
6039            }
6040            if (r != null) {
6041                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6042            }
6043
6044            N = pkg.permissions.size();
6045            r = null;
6046            for (i=0; i<N; i++) {
6047                PackageParser.Permission p = pkg.permissions.get(i);
6048                ArrayMap<String, BasePermission> permissionMap =
6049                        p.tree ? mSettings.mPermissionTrees
6050                        : mSettings.mPermissions;
6051                p.group = mPermissionGroups.get(p.info.group);
6052                if (p.info.group == null || p.group != null) {
6053                    BasePermission bp = permissionMap.get(p.info.name);
6054
6055                    // Allow system apps to redefine non-system permissions
6056                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6057                        final boolean currentOwnerIsSystem = (bp.perm != null
6058                                && isSystemApp(bp.perm.owner));
6059                        if (isSystemApp(p.owner)) {
6060                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6061                                // It's a built-in permission and no owner, take ownership now
6062                                bp.packageSetting = pkgSetting;
6063                                bp.perm = p;
6064                                bp.uid = pkg.applicationInfo.uid;
6065                                bp.sourcePackage = p.info.packageName;
6066                            } else if (!currentOwnerIsSystem) {
6067                                String msg = "New decl " + p.owner + " of permission  "
6068                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6069                                reportSettingsProblem(Log.WARN, msg);
6070                                bp = null;
6071                            }
6072                        }
6073                    }
6074
6075                    if (bp == null) {
6076                        bp = new BasePermission(p.info.name, p.info.packageName,
6077                                BasePermission.TYPE_NORMAL);
6078                        permissionMap.put(p.info.name, bp);
6079                    }
6080
6081                    if (bp.perm == null) {
6082                        if (bp.sourcePackage == null
6083                                || bp.sourcePackage.equals(p.info.packageName)) {
6084                            BasePermission tree = findPermissionTreeLP(p.info.name);
6085                            if (tree == null
6086                                    || tree.sourcePackage.equals(p.info.packageName)) {
6087                                bp.packageSetting = pkgSetting;
6088                                bp.perm = p;
6089                                bp.uid = pkg.applicationInfo.uid;
6090                                bp.sourcePackage = p.info.packageName;
6091                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6092                                    if (r == null) {
6093                                        r = new StringBuilder(256);
6094                                    } else {
6095                                        r.append(' ');
6096                                    }
6097                                    r.append(p.info.name);
6098                                }
6099                            } else {
6100                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6101                                        + p.info.packageName + " ignored: base tree "
6102                                        + tree.name + " is from package "
6103                                        + tree.sourcePackage);
6104                            }
6105                        } else {
6106                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6107                                    + p.info.packageName + " ignored: original from "
6108                                    + bp.sourcePackage);
6109                        }
6110                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6111                        if (r == null) {
6112                            r = new StringBuilder(256);
6113                        } else {
6114                            r.append(' ');
6115                        }
6116                        r.append("DUP:");
6117                        r.append(p.info.name);
6118                    }
6119                    if (bp.perm == p) {
6120                        bp.protectionLevel = p.info.protectionLevel;
6121                    }
6122                } else {
6123                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6124                            + p.info.packageName + " ignored: no group "
6125                            + p.group);
6126                }
6127            }
6128            if (r != null) {
6129                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6130            }
6131
6132            N = pkg.instrumentation.size();
6133            r = null;
6134            for (i=0; i<N; i++) {
6135                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6136                a.info.packageName = pkg.applicationInfo.packageName;
6137                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6138                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6139                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6140                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6141                a.info.dataDir = pkg.applicationInfo.dataDir;
6142
6143                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6144                // need other information about the application, like the ABI and what not ?
6145                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6146                mInstrumentation.put(a.getComponentName(), a);
6147                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6148                    if (r == null) {
6149                        r = new StringBuilder(256);
6150                    } else {
6151                        r.append(' ');
6152                    }
6153                    r.append(a.info.name);
6154                }
6155            }
6156            if (r != null) {
6157                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6158            }
6159
6160            if (pkg.protectedBroadcasts != null) {
6161                N = pkg.protectedBroadcasts.size();
6162                for (i=0; i<N; i++) {
6163                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6164                }
6165            }
6166
6167            pkgSetting.setTimeStamp(scanFileTime);
6168
6169            // Create idmap files for pairs of (packages, overlay packages).
6170            // Note: "android", ie framework-res.apk, is handled by native layers.
6171            if (pkg.mOverlayTarget != null) {
6172                // This is an overlay package.
6173                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6174                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6175                        mOverlays.put(pkg.mOverlayTarget,
6176                                new ArrayMap<String, PackageParser.Package>());
6177                    }
6178                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6179                    map.put(pkg.packageName, pkg);
6180                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6181                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6182                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6183                                "scanPackageLI failed to createIdmap");
6184                    }
6185                }
6186            } else if (mOverlays.containsKey(pkg.packageName) &&
6187                    !pkg.packageName.equals("android")) {
6188                // This is a regular package, with one or more known overlay packages.
6189                createIdmapsForPackageLI(pkg);
6190            }
6191        }
6192
6193        return pkg;
6194    }
6195
6196    /**
6197     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6198     * i.e, so that all packages can be run inside a single process if required.
6199     *
6200     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6201     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6202     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6203     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6204     * updating a package that belongs to a shared user.
6205     *
6206     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6207     * adds unnecessary complexity.
6208     */
6209    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6210            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6211        String requiredInstructionSet = null;
6212        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6213            requiredInstructionSet = VMRuntime.getInstructionSet(
6214                     scannedPackage.applicationInfo.primaryCpuAbi);
6215        }
6216
6217        PackageSetting requirer = null;
6218        for (PackageSetting ps : packagesForUser) {
6219            // If packagesForUser contains scannedPackage, we skip it. This will happen
6220            // when scannedPackage is an update of an existing package. Without this check,
6221            // we will never be able to change the ABI of any package belonging to a shared
6222            // user, even if it's compatible with other packages.
6223            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6224                if (ps.primaryCpuAbiString == null) {
6225                    continue;
6226                }
6227
6228                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6229                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6230                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6231                    // this but there's not much we can do.
6232                    String errorMessage = "Instruction set mismatch, "
6233                            + ((requirer == null) ? "[caller]" : requirer)
6234                            + " requires " + requiredInstructionSet + " whereas " + ps
6235                            + " requires " + instructionSet;
6236                    Slog.w(TAG, errorMessage);
6237                }
6238
6239                if (requiredInstructionSet == null) {
6240                    requiredInstructionSet = instructionSet;
6241                    requirer = ps;
6242                }
6243            }
6244        }
6245
6246        if (requiredInstructionSet != null) {
6247            String adjustedAbi;
6248            if (requirer != null) {
6249                // requirer != null implies that either scannedPackage was null or that scannedPackage
6250                // did not require an ABI, in which case we have to adjust scannedPackage to match
6251                // the ABI of the set (which is the same as requirer's ABI)
6252                adjustedAbi = requirer.primaryCpuAbiString;
6253                if (scannedPackage != null) {
6254                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6255                }
6256            } else {
6257                // requirer == null implies that we're updating all ABIs in the set to
6258                // match scannedPackage.
6259                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6260            }
6261
6262            for (PackageSetting ps : packagesForUser) {
6263                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6264                    if (ps.primaryCpuAbiString != null) {
6265                        continue;
6266                    }
6267
6268                    ps.primaryCpuAbiString = adjustedAbi;
6269                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6270                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6271                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6272
6273                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
6274                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
6275                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6276                            ps.primaryCpuAbiString = null;
6277                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6278                            return;
6279                        } else {
6280                            mInstaller.rmdex(ps.codePathString,
6281                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
6282                        }
6283                    }
6284                }
6285            }
6286        }
6287    }
6288
6289    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6290        synchronized (mPackages) {
6291            mResolverReplaced = true;
6292            // Set up information for custom user intent resolution activity.
6293            mResolveActivity.applicationInfo = pkg.applicationInfo;
6294            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6295            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6296            mResolveActivity.processName = pkg.applicationInfo.packageName;
6297            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6298            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6299                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6300            mResolveActivity.theme = 0;
6301            mResolveActivity.exported = true;
6302            mResolveActivity.enabled = true;
6303            mResolveInfo.activityInfo = mResolveActivity;
6304            mResolveInfo.priority = 0;
6305            mResolveInfo.preferredOrder = 0;
6306            mResolveInfo.match = 0;
6307            mResolveComponentName = mCustomResolverComponentName;
6308            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6309                    mResolveComponentName);
6310        }
6311    }
6312
6313    private static String calculateBundledApkRoot(final String codePathString) {
6314        final File codePath = new File(codePathString);
6315        final File codeRoot;
6316        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6317            codeRoot = Environment.getRootDirectory();
6318        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6319            codeRoot = Environment.getOemDirectory();
6320        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6321            codeRoot = Environment.getVendorDirectory();
6322        } else {
6323            // Unrecognized code path; take its top real segment as the apk root:
6324            // e.g. /something/app/blah.apk => /something
6325            try {
6326                File f = codePath.getCanonicalFile();
6327                File parent = f.getParentFile();    // non-null because codePath is a file
6328                File tmp;
6329                while ((tmp = parent.getParentFile()) != null) {
6330                    f = parent;
6331                    parent = tmp;
6332                }
6333                codeRoot = f;
6334                Slog.w(TAG, "Unrecognized code path "
6335                        + codePath + " - using " + codeRoot);
6336            } catch (IOException e) {
6337                // Can't canonicalize the code path -- shenanigans?
6338                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6339                return Environment.getRootDirectory().getPath();
6340            }
6341        }
6342        return codeRoot.getPath();
6343    }
6344
6345    /**
6346     * Derive and set the location of native libraries for the given package,
6347     * which varies depending on where and how the package was installed.
6348     */
6349    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6350        final ApplicationInfo info = pkg.applicationInfo;
6351        final String codePath = pkg.codePath;
6352        final File codeFile = new File(codePath);
6353        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6354        final boolean asecApp = info.isForwardLocked() || isExternal(info);
6355
6356        info.nativeLibraryRootDir = null;
6357        info.nativeLibraryRootRequiresIsa = false;
6358        info.nativeLibraryDir = null;
6359        info.secondaryNativeLibraryDir = null;
6360
6361        if (isApkFile(codeFile)) {
6362            // Monolithic install
6363            if (bundledApp) {
6364                // If "/system/lib64/apkname" exists, assume that is the per-package
6365                // native library directory to use; otherwise use "/system/lib/apkname".
6366                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6367                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6368                        getPrimaryInstructionSet(info));
6369
6370                // This is a bundled system app so choose the path based on the ABI.
6371                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6372                // is just the default path.
6373                final String apkName = deriveCodePathName(codePath);
6374                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6375                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6376                        apkName).getAbsolutePath();
6377
6378                if (info.secondaryCpuAbi != null) {
6379                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6380                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6381                            secondaryLibDir, apkName).getAbsolutePath();
6382                }
6383            } else if (asecApp) {
6384                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6385                        .getAbsolutePath();
6386            } else {
6387                final String apkName = deriveCodePathName(codePath);
6388                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6389                        .getAbsolutePath();
6390            }
6391
6392            info.nativeLibraryRootRequiresIsa = false;
6393            info.nativeLibraryDir = info.nativeLibraryRootDir;
6394        } else {
6395            // Cluster install
6396            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6397            info.nativeLibraryRootRequiresIsa = true;
6398
6399            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6400                    getPrimaryInstructionSet(info)).getAbsolutePath();
6401
6402            if (info.secondaryCpuAbi != null) {
6403                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6404                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6405            }
6406        }
6407    }
6408
6409    /**
6410     * Calculate the abis and roots for a bundled app. These can uniquely
6411     * be determined from the contents of the system partition, i.e whether
6412     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6413     * of this information, and instead assume that the system was built
6414     * sensibly.
6415     */
6416    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6417                                           PackageSetting pkgSetting) {
6418        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6419
6420        // If "/system/lib64/apkname" exists, assume that is the per-package
6421        // native library directory to use; otherwise use "/system/lib/apkname".
6422        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6423        setBundledAppAbi(pkg, apkRoot, apkName);
6424        // pkgSetting might be null during rescan following uninstall of updates
6425        // to a bundled app, so accommodate that possibility.  The settings in
6426        // that case will be established later from the parsed package.
6427        //
6428        // If the settings aren't null, sync them up with what we've just derived.
6429        // note that apkRoot isn't stored in the package settings.
6430        if (pkgSetting != null) {
6431            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6432            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6433        }
6434    }
6435
6436    /**
6437     * Deduces the ABI of a bundled app and sets the relevant fields on the
6438     * parsed pkg object.
6439     *
6440     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6441     *        under which system libraries are installed.
6442     * @param apkName the name of the installed package.
6443     */
6444    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6445        final File codeFile = new File(pkg.codePath);
6446
6447        final boolean has64BitLibs;
6448        final boolean has32BitLibs;
6449        if (isApkFile(codeFile)) {
6450            // Monolithic install
6451            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6452            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6453        } else {
6454            // Cluster install
6455            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6456            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6457                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6458                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6459                has64BitLibs = (new File(rootDir, isa)).exists();
6460            } else {
6461                has64BitLibs = false;
6462            }
6463            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6464                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6465                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6466                has32BitLibs = (new File(rootDir, isa)).exists();
6467            } else {
6468                has32BitLibs = false;
6469            }
6470        }
6471
6472        if (has64BitLibs && !has32BitLibs) {
6473            // The package has 64 bit libs, but not 32 bit libs. Its primary
6474            // ABI should be 64 bit. We can safely assume here that the bundled
6475            // native libraries correspond to the most preferred ABI in the list.
6476
6477            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6478            pkg.applicationInfo.secondaryCpuAbi = null;
6479        } else if (has32BitLibs && !has64BitLibs) {
6480            // The package has 32 bit libs but not 64 bit libs. Its primary
6481            // ABI should be 32 bit.
6482
6483            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6484            pkg.applicationInfo.secondaryCpuAbi = null;
6485        } else if (has32BitLibs && has64BitLibs) {
6486            // The application has both 64 and 32 bit bundled libraries. We check
6487            // here that the app declares multiArch support, and warn if it doesn't.
6488            //
6489            // We will be lenient here and record both ABIs. The primary will be the
6490            // ABI that's higher on the list, i.e, a device that's configured to prefer
6491            // 64 bit apps will see a 64 bit primary ABI,
6492
6493            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6494                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6495            }
6496
6497            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6498                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6499                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6500            } else {
6501                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6502                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6503            }
6504        } else {
6505            pkg.applicationInfo.primaryCpuAbi = null;
6506            pkg.applicationInfo.secondaryCpuAbi = null;
6507        }
6508    }
6509
6510    private void killApplication(String pkgName, int appId, String reason) {
6511        // Request the ActivityManager to kill the process(only for existing packages)
6512        // so that we do not end up in a confused state while the user is still using the older
6513        // version of the application while the new one gets installed.
6514        IActivityManager am = ActivityManagerNative.getDefault();
6515        if (am != null) {
6516            try {
6517                am.killApplicationWithAppId(pkgName, appId, reason);
6518            } catch (RemoteException e) {
6519            }
6520        }
6521    }
6522
6523    void removePackageLI(PackageSetting ps, boolean chatty) {
6524        if (DEBUG_INSTALL) {
6525            if (chatty)
6526                Log.d(TAG, "Removing package " + ps.name);
6527        }
6528
6529        // writer
6530        synchronized (mPackages) {
6531            mPackages.remove(ps.name);
6532            final PackageParser.Package pkg = ps.pkg;
6533            if (pkg != null) {
6534                cleanPackageDataStructuresLILPw(pkg, chatty);
6535            }
6536        }
6537    }
6538
6539    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6540        if (DEBUG_INSTALL) {
6541            if (chatty)
6542                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6543        }
6544
6545        // writer
6546        synchronized (mPackages) {
6547            mPackages.remove(pkg.applicationInfo.packageName);
6548            cleanPackageDataStructuresLILPw(pkg, chatty);
6549        }
6550    }
6551
6552    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6553        int N = pkg.providers.size();
6554        StringBuilder r = null;
6555        int i;
6556        for (i=0; i<N; i++) {
6557            PackageParser.Provider p = pkg.providers.get(i);
6558            mProviders.removeProvider(p);
6559            if (p.info.authority == null) {
6560
6561                /* There was another ContentProvider with this authority when
6562                 * this app was installed so this authority is null,
6563                 * Ignore it as we don't have to unregister the provider.
6564                 */
6565                continue;
6566            }
6567            String names[] = p.info.authority.split(";");
6568            for (int j = 0; j < names.length; j++) {
6569                if (mProvidersByAuthority.get(names[j]) == p) {
6570                    mProvidersByAuthority.remove(names[j]);
6571                    if (DEBUG_REMOVE) {
6572                        if (chatty)
6573                            Log.d(TAG, "Unregistered content provider: " + names[j]
6574                                    + ", className = " + p.info.name + ", isSyncable = "
6575                                    + p.info.isSyncable);
6576                    }
6577                }
6578            }
6579            if (DEBUG_REMOVE && chatty) {
6580                if (r == null) {
6581                    r = new StringBuilder(256);
6582                } else {
6583                    r.append(' ');
6584                }
6585                r.append(p.info.name);
6586            }
6587        }
6588        if (r != null) {
6589            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6590        }
6591
6592        N = pkg.services.size();
6593        r = null;
6594        for (i=0; i<N; i++) {
6595            PackageParser.Service s = pkg.services.get(i);
6596            mServices.removeService(s);
6597            if (chatty) {
6598                if (r == null) {
6599                    r = new StringBuilder(256);
6600                } else {
6601                    r.append(' ');
6602                }
6603                r.append(s.info.name);
6604            }
6605        }
6606        if (r != null) {
6607            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6608        }
6609
6610        N = pkg.receivers.size();
6611        r = null;
6612        for (i=0; i<N; i++) {
6613            PackageParser.Activity a = pkg.receivers.get(i);
6614            mReceivers.removeActivity(a, "receiver");
6615            if (DEBUG_REMOVE && chatty) {
6616                if (r == null) {
6617                    r = new StringBuilder(256);
6618                } else {
6619                    r.append(' ');
6620                }
6621                r.append(a.info.name);
6622            }
6623        }
6624        if (r != null) {
6625            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6626        }
6627
6628        N = pkg.activities.size();
6629        r = null;
6630        for (i=0; i<N; i++) {
6631            PackageParser.Activity a = pkg.activities.get(i);
6632            mActivities.removeActivity(a, "activity");
6633            if (DEBUG_REMOVE && chatty) {
6634                if (r == null) {
6635                    r = new StringBuilder(256);
6636                } else {
6637                    r.append(' ');
6638                }
6639                r.append(a.info.name);
6640            }
6641        }
6642        if (r != null) {
6643            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6644        }
6645
6646        N = pkg.permissions.size();
6647        r = null;
6648        for (i=0; i<N; i++) {
6649            PackageParser.Permission p = pkg.permissions.get(i);
6650            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6651            if (bp == null) {
6652                bp = mSettings.mPermissionTrees.get(p.info.name);
6653            }
6654            if (bp != null && bp.perm == p) {
6655                bp.perm = null;
6656                if (DEBUG_REMOVE && chatty) {
6657                    if (r == null) {
6658                        r = new StringBuilder(256);
6659                    } else {
6660                        r.append(' ');
6661                    }
6662                    r.append(p.info.name);
6663                }
6664            }
6665            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6666                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6667                if (appOpPerms != null) {
6668                    appOpPerms.remove(pkg.packageName);
6669                }
6670            }
6671        }
6672        if (r != null) {
6673            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6674        }
6675
6676        N = pkg.requestedPermissions.size();
6677        r = null;
6678        for (i=0; i<N; i++) {
6679            String perm = pkg.requestedPermissions.get(i);
6680            BasePermission bp = mSettings.mPermissions.get(perm);
6681            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6682                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6683                if (appOpPerms != null) {
6684                    appOpPerms.remove(pkg.packageName);
6685                    if (appOpPerms.isEmpty()) {
6686                        mAppOpPermissionPackages.remove(perm);
6687                    }
6688                }
6689            }
6690        }
6691        if (r != null) {
6692            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6693        }
6694
6695        N = pkg.instrumentation.size();
6696        r = null;
6697        for (i=0; i<N; i++) {
6698            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6699            mInstrumentation.remove(a.getComponentName());
6700            if (DEBUG_REMOVE && chatty) {
6701                if (r == null) {
6702                    r = new StringBuilder(256);
6703                } else {
6704                    r.append(' ');
6705                }
6706                r.append(a.info.name);
6707            }
6708        }
6709        if (r != null) {
6710            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6711        }
6712
6713        r = null;
6714        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6715            // Only system apps can hold shared libraries.
6716            if (pkg.libraryNames != null) {
6717                for (i=0; i<pkg.libraryNames.size(); i++) {
6718                    String name = pkg.libraryNames.get(i);
6719                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6720                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6721                        mSharedLibraries.remove(name);
6722                        if (DEBUG_REMOVE && chatty) {
6723                            if (r == null) {
6724                                r = new StringBuilder(256);
6725                            } else {
6726                                r.append(' ');
6727                            }
6728                            r.append(name);
6729                        }
6730                    }
6731                }
6732            }
6733        }
6734        if (r != null) {
6735            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6736        }
6737    }
6738
6739    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6740        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6741            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6742                return true;
6743            }
6744        }
6745        return false;
6746    }
6747
6748    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6749    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6750    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6751
6752    private void updatePermissionsLPw(String changingPkg,
6753            PackageParser.Package pkgInfo, int flags) {
6754        // Make sure there are no dangling permission trees.
6755        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6756        while (it.hasNext()) {
6757            final BasePermission bp = it.next();
6758            if (bp.packageSetting == null) {
6759                // We may not yet have parsed the package, so just see if
6760                // we still know about its settings.
6761                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6762            }
6763            if (bp.packageSetting == null) {
6764                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6765                        + " from package " + bp.sourcePackage);
6766                it.remove();
6767            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6768                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6769                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6770                            + " from package " + bp.sourcePackage);
6771                    flags |= UPDATE_PERMISSIONS_ALL;
6772                    it.remove();
6773                }
6774            }
6775        }
6776
6777        // Make sure all dynamic permissions have been assigned to a package,
6778        // and make sure there are no dangling permissions.
6779        it = mSettings.mPermissions.values().iterator();
6780        while (it.hasNext()) {
6781            final BasePermission bp = it.next();
6782            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6783                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6784                        + bp.name + " pkg=" + bp.sourcePackage
6785                        + " info=" + bp.pendingInfo);
6786                if (bp.packageSetting == null && bp.pendingInfo != null) {
6787                    final BasePermission tree = findPermissionTreeLP(bp.name);
6788                    if (tree != null && tree.perm != null) {
6789                        bp.packageSetting = tree.packageSetting;
6790                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6791                                new PermissionInfo(bp.pendingInfo));
6792                        bp.perm.info.packageName = tree.perm.info.packageName;
6793                        bp.perm.info.name = bp.name;
6794                        bp.uid = tree.uid;
6795                    }
6796                }
6797            }
6798            if (bp.packageSetting == null) {
6799                // We may not yet have parsed the package, so just see if
6800                // we still know about its settings.
6801                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6802            }
6803            if (bp.packageSetting == null) {
6804                Slog.w(TAG, "Removing dangling permission: " + bp.name
6805                        + " from package " + bp.sourcePackage);
6806                it.remove();
6807            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6808                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6809                    Slog.i(TAG, "Removing old permission: " + bp.name
6810                            + " from package " + bp.sourcePackage);
6811                    flags |= UPDATE_PERMISSIONS_ALL;
6812                    it.remove();
6813                }
6814            }
6815        }
6816
6817        // Now update the permissions for all packages, in particular
6818        // replace the granted permissions of the system packages.
6819        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6820            for (PackageParser.Package pkg : mPackages.values()) {
6821                if (pkg != pkgInfo) {
6822                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6823                            changingPkg);
6824                }
6825            }
6826        }
6827
6828        if (pkgInfo != null) {
6829            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6830        }
6831    }
6832
6833    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6834            String packageOfInterest) {
6835        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6836        if (ps == null) {
6837            return;
6838        }
6839        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6840        ArraySet<String> origPermissions = gp.grantedPermissions;
6841        boolean changedPermission = false;
6842
6843        if (replace) {
6844            ps.permissionsFixed = false;
6845            if (gp == ps) {
6846                origPermissions = new ArraySet<String>(gp.grantedPermissions);
6847                gp.grantedPermissions.clear();
6848                gp.gids = mGlobalGids;
6849            }
6850        }
6851
6852        if (gp.gids == null) {
6853            gp.gids = mGlobalGids;
6854        }
6855
6856        final int N = pkg.requestedPermissions.size();
6857        for (int i=0; i<N; i++) {
6858            final String name = pkg.requestedPermissions.get(i);
6859            final boolean required = pkg.requestedPermissionsRequired.get(i);
6860            final BasePermission bp = mSettings.mPermissions.get(name);
6861            if (DEBUG_INSTALL) {
6862                if (gp != ps) {
6863                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6864                }
6865            }
6866
6867            if (bp == null || bp.packageSetting == null) {
6868                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6869                    Slog.w(TAG, "Unknown permission " + name
6870                            + " in package " + pkg.packageName);
6871                }
6872                continue;
6873            }
6874
6875            final String perm = bp.name;
6876            boolean allowed;
6877            boolean allowedSig = false;
6878            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6879                // Keep track of app op permissions.
6880                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6881                if (pkgs == null) {
6882                    pkgs = new ArraySet<>();
6883                    mAppOpPermissionPackages.put(bp.name, pkgs);
6884                }
6885                pkgs.add(pkg.packageName);
6886            }
6887            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6888            if (level == PermissionInfo.PROTECTION_NORMAL
6889                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6890                // We grant a normal or dangerous permission if any of the following
6891                // are true:
6892                // 1) The permission is required
6893                // 2) The permission is optional, but was granted in the past
6894                // 3) The permission is optional, but was requested by an
6895                //    app in /system (not /data)
6896                //
6897                // Otherwise, reject the permission.
6898                allowed = (required || origPermissions.contains(perm)
6899                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6900            } else if (bp.packageSetting == null) {
6901                // This permission is invalid; skip it.
6902                allowed = false;
6903            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6904                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6905                if (allowed) {
6906                    allowedSig = true;
6907                }
6908            } else {
6909                allowed = false;
6910            }
6911            if (DEBUG_INSTALL) {
6912                if (gp != ps) {
6913                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6914                }
6915            }
6916            if (allowed) {
6917                if (!isSystemApp(ps) && ps.permissionsFixed) {
6918                    // If this is an existing, non-system package, then
6919                    // we can't add any new permissions to it.
6920                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6921                        // Except...  if this is a permission that was added
6922                        // to the platform (note: need to only do this when
6923                        // updating the platform).
6924                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6925                    }
6926                }
6927                if (allowed) {
6928                    if (!gp.grantedPermissions.contains(perm)) {
6929                        changedPermission = true;
6930                        gp.grantedPermissions.add(perm);
6931                        gp.gids = appendInts(gp.gids, bp.gids);
6932                    } else if (!ps.haveGids) {
6933                        gp.gids = appendInts(gp.gids, bp.gids);
6934                    }
6935                } else {
6936                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6937                        Slog.w(TAG, "Not granting permission " + perm
6938                                + " to package " + pkg.packageName
6939                                + " because it was previously installed without");
6940                    }
6941                }
6942            } else {
6943                if (gp.grantedPermissions.remove(perm)) {
6944                    changedPermission = true;
6945                    gp.gids = removeInts(gp.gids, bp.gids);
6946                    Slog.i(TAG, "Un-granting permission " + perm
6947                            + " from package " + pkg.packageName
6948                            + " (protectionLevel=" + bp.protectionLevel
6949                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6950                            + ")");
6951                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6952                    // Don't print warning for app op permissions, since it is fine for them
6953                    // not to be granted, there is a UI for the user to decide.
6954                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6955                        Slog.w(TAG, "Not granting permission " + perm
6956                                + " to package " + pkg.packageName
6957                                + " (protectionLevel=" + bp.protectionLevel
6958                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6959                                + ")");
6960                    }
6961                }
6962            }
6963        }
6964
6965        if ((changedPermission || replace) && !ps.permissionsFixed &&
6966                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6967            // This is the first that we have heard about this package, so the
6968            // permissions we have now selected are fixed until explicitly
6969            // changed.
6970            ps.permissionsFixed = true;
6971        }
6972        ps.haveGids = true;
6973    }
6974
6975    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6976        boolean allowed = false;
6977        final int NP = PackageParser.NEW_PERMISSIONS.length;
6978        for (int ip=0; ip<NP; ip++) {
6979            final PackageParser.NewPermissionInfo npi
6980                    = PackageParser.NEW_PERMISSIONS[ip];
6981            if (npi.name.equals(perm)
6982                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6983                allowed = true;
6984                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6985                        + pkg.packageName);
6986                break;
6987            }
6988        }
6989        return allowed;
6990    }
6991
6992    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6993                                          BasePermission bp, ArraySet<String> origPermissions) {
6994        boolean allowed;
6995        allowed = (compareSignatures(
6996                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6997                        == PackageManager.SIGNATURE_MATCH)
6998                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6999                        == PackageManager.SIGNATURE_MATCH);
7000        if (!allowed && (bp.protectionLevel
7001                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7002            if (isSystemApp(pkg)) {
7003                // For updated system applications, a system permission
7004                // is granted only if it had been defined by the original application.
7005                if (isUpdatedSystemApp(pkg)) {
7006                    final PackageSetting sysPs = mSettings
7007                            .getDisabledSystemPkgLPr(pkg.packageName);
7008                    final GrantedPermissions origGp = sysPs.sharedUser != null
7009                            ? sysPs.sharedUser : sysPs;
7010
7011                    if (origGp.grantedPermissions.contains(perm)) {
7012                        // If the original was granted this permission, we take
7013                        // that grant decision as read and propagate it to the
7014                        // update.
7015                        if (sysPs.isPrivileged()) {
7016                            allowed = true;
7017                        }
7018                    } else {
7019                        // The system apk may have been updated with an older
7020                        // version of the one on the data partition, but which
7021                        // granted a new system permission that it didn't have
7022                        // before.  In this case we do want to allow the app to
7023                        // now get the new permission if the ancestral apk is
7024                        // privileged to get it.
7025                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7026                            for (int j=0;
7027                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7028                                if (perm.equals(
7029                                        sysPs.pkg.requestedPermissions.get(j))) {
7030                                    allowed = true;
7031                                    break;
7032                                }
7033                            }
7034                        }
7035                    }
7036                } else {
7037                    allowed = isPrivilegedApp(pkg);
7038                }
7039            }
7040        }
7041        if (!allowed && (bp.protectionLevel
7042                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7043            // For development permissions, a development permission
7044            // is granted only if it was already granted.
7045            allowed = origPermissions.contains(perm);
7046        }
7047        return allowed;
7048    }
7049
7050    final class ActivityIntentResolver
7051            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7052        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7053                boolean defaultOnly, int userId) {
7054            if (!sUserManager.exists(userId)) return null;
7055            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7056            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7057        }
7058
7059        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7060                int userId) {
7061            if (!sUserManager.exists(userId)) return null;
7062            mFlags = flags;
7063            return super.queryIntent(intent, resolvedType,
7064                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7065        }
7066
7067        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7068                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7069            if (!sUserManager.exists(userId)) return null;
7070            if (packageActivities == null) {
7071                return null;
7072            }
7073            mFlags = flags;
7074            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7075            final int N = packageActivities.size();
7076            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7077                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7078
7079            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7080            for (int i = 0; i < N; ++i) {
7081                intentFilters = packageActivities.get(i).intents;
7082                if (intentFilters != null && intentFilters.size() > 0) {
7083                    PackageParser.ActivityIntentInfo[] array =
7084                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7085                    intentFilters.toArray(array);
7086                    listCut.add(array);
7087                }
7088            }
7089            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7090        }
7091
7092        public final void addActivity(PackageParser.Activity a, String type) {
7093            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7094            mActivities.put(a.getComponentName(), a);
7095            if (DEBUG_SHOW_INFO)
7096                Log.v(
7097                TAG, "  " + type + " " +
7098                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7099            if (DEBUG_SHOW_INFO)
7100                Log.v(TAG, "    Class=" + a.info.name);
7101            final int NI = a.intents.size();
7102            for (int j=0; j<NI; j++) {
7103                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7104                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7105                    intent.setPriority(0);
7106                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7107                            + a.className + " with priority > 0, forcing to 0");
7108                }
7109                if (DEBUG_SHOW_INFO) {
7110                    Log.v(TAG, "    IntentFilter:");
7111                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7112                }
7113                if (!intent.debugCheck()) {
7114                    Log.w(TAG, "==> For Activity " + a.info.name);
7115                }
7116                addFilter(intent);
7117            }
7118        }
7119
7120        public final void removeActivity(PackageParser.Activity a, String type) {
7121            mActivities.remove(a.getComponentName());
7122            if (DEBUG_SHOW_INFO) {
7123                Log.v(TAG, "  " + type + " "
7124                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7125                                : a.info.name) + ":");
7126                Log.v(TAG, "    Class=" + a.info.name);
7127            }
7128            final int NI = a.intents.size();
7129            for (int j=0; j<NI; j++) {
7130                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7131                if (DEBUG_SHOW_INFO) {
7132                    Log.v(TAG, "    IntentFilter:");
7133                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7134                }
7135                removeFilter(intent);
7136            }
7137        }
7138
7139        @Override
7140        protected boolean allowFilterResult(
7141                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7142            ActivityInfo filterAi = filter.activity.info;
7143            for (int i=dest.size()-1; i>=0; i--) {
7144                ActivityInfo destAi = dest.get(i).activityInfo;
7145                if (destAi.name == filterAi.name
7146                        && destAi.packageName == filterAi.packageName) {
7147                    return false;
7148                }
7149            }
7150            return true;
7151        }
7152
7153        @Override
7154        protected ActivityIntentInfo[] newArray(int size) {
7155            return new ActivityIntentInfo[size];
7156        }
7157
7158        @Override
7159        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7160            if (!sUserManager.exists(userId)) return true;
7161            PackageParser.Package p = filter.activity.owner;
7162            if (p != null) {
7163                PackageSetting ps = (PackageSetting)p.mExtras;
7164                if (ps != null) {
7165                    // System apps are never considered stopped for purposes of
7166                    // filtering, because there may be no way for the user to
7167                    // actually re-launch them.
7168                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7169                            && ps.getStopped(userId);
7170                }
7171            }
7172            return false;
7173        }
7174
7175        @Override
7176        protected boolean isPackageForFilter(String packageName,
7177                PackageParser.ActivityIntentInfo info) {
7178            return packageName.equals(info.activity.owner.packageName);
7179        }
7180
7181        @Override
7182        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7183                int match, int userId) {
7184            if (!sUserManager.exists(userId)) return null;
7185            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7186                return null;
7187            }
7188            final PackageParser.Activity activity = info.activity;
7189            if (mSafeMode && (activity.info.applicationInfo.flags
7190                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7191                return null;
7192            }
7193            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7194            if (ps == null) {
7195                return null;
7196            }
7197            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7198                    ps.readUserState(userId), userId);
7199            if (ai == null) {
7200                return null;
7201            }
7202            final ResolveInfo res = new ResolveInfo();
7203            res.activityInfo = ai;
7204            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7205                res.filter = info;
7206            }
7207            res.priority = info.getPriority();
7208            res.preferredOrder = activity.owner.mPreferredOrder;
7209            //System.out.println("Result: " + res.activityInfo.className +
7210            //                   " = " + res.priority);
7211            res.match = match;
7212            res.isDefault = info.hasDefault;
7213            res.labelRes = info.labelRes;
7214            res.nonLocalizedLabel = info.nonLocalizedLabel;
7215            if (userNeedsBadging(userId)) {
7216                res.noResourceId = true;
7217            } else {
7218                res.icon = info.icon;
7219            }
7220            res.system = isSystemApp(res.activityInfo.applicationInfo);
7221            return res;
7222        }
7223
7224        @Override
7225        protected void sortResults(List<ResolveInfo> results) {
7226            Collections.sort(results, mResolvePrioritySorter);
7227        }
7228
7229        @Override
7230        protected void dumpFilter(PrintWriter out, String prefix,
7231                PackageParser.ActivityIntentInfo filter) {
7232            out.print(prefix); out.print(
7233                    Integer.toHexString(System.identityHashCode(filter.activity)));
7234                    out.print(' ');
7235                    filter.activity.printComponentShortName(out);
7236                    out.print(" filter ");
7237                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7238        }
7239
7240        @Override
7241        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7242            return filter.activity;
7243        }
7244
7245        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7246            PackageParser.Activity activity = (PackageParser.Activity)label;
7247            out.print(prefix); out.print(
7248                    Integer.toHexString(System.identityHashCode(activity)));
7249                    out.print(' ');
7250                    activity.printComponentShortName(out);
7251            if (count > 1) {
7252                out.print(" ("); out.print(count); out.print(" filters)");
7253            }
7254            out.println();
7255        }
7256
7257//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7258//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7259//            final List<ResolveInfo> retList = Lists.newArrayList();
7260//            while (i.hasNext()) {
7261//                final ResolveInfo resolveInfo = i.next();
7262//                if (isEnabledLP(resolveInfo.activityInfo)) {
7263//                    retList.add(resolveInfo);
7264//                }
7265//            }
7266//            return retList;
7267//        }
7268
7269        // Keys are String (activity class name), values are Activity.
7270        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
7271                = new ArrayMap<ComponentName, PackageParser.Activity>();
7272        private int mFlags;
7273    }
7274
7275    private final class ServiceIntentResolver
7276            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7277        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7278                boolean defaultOnly, int userId) {
7279            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7280            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7281        }
7282
7283        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7284                int userId) {
7285            if (!sUserManager.exists(userId)) return null;
7286            mFlags = flags;
7287            return super.queryIntent(intent, resolvedType,
7288                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7289        }
7290
7291        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7292                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7293            if (!sUserManager.exists(userId)) return null;
7294            if (packageServices == null) {
7295                return null;
7296            }
7297            mFlags = flags;
7298            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7299            final int N = packageServices.size();
7300            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7301                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7302
7303            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7304            for (int i = 0; i < N; ++i) {
7305                intentFilters = packageServices.get(i).intents;
7306                if (intentFilters != null && intentFilters.size() > 0) {
7307                    PackageParser.ServiceIntentInfo[] array =
7308                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7309                    intentFilters.toArray(array);
7310                    listCut.add(array);
7311                }
7312            }
7313            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7314        }
7315
7316        public final void addService(PackageParser.Service s) {
7317            mServices.put(s.getComponentName(), s);
7318            if (DEBUG_SHOW_INFO) {
7319                Log.v(TAG, "  "
7320                        + (s.info.nonLocalizedLabel != null
7321                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7322                Log.v(TAG, "    Class=" + s.info.name);
7323            }
7324            final int NI = s.intents.size();
7325            int j;
7326            for (j=0; j<NI; j++) {
7327                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7328                if (DEBUG_SHOW_INFO) {
7329                    Log.v(TAG, "    IntentFilter:");
7330                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7331                }
7332                if (!intent.debugCheck()) {
7333                    Log.w(TAG, "==> For Service " + s.info.name);
7334                }
7335                addFilter(intent);
7336            }
7337        }
7338
7339        public final void removeService(PackageParser.Service s) {
7340            mServices.remove(s.getComponentName());
7341            if (DEBUG_SHOW_INFO) {
7342                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7343                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7344                Log.v(TAG, "    Class=" + s.info.name);
7345            }
7346            final int NI = s.intents.size();
7347            int j;
7348            for (j=0; j<NI; j++) {
7349                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7350                if (DEBUG_SHOW_INFO) {
7351                    Log.v(TAG, "    IntentFilter:");
7352                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7353                }
7354                removeFilter(intent);
7355            }
7356        }
7357
7358        @Override
7359        protected boolean allowFilterResult(
7360                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7361            ServiceInfo filterSi = filter.service.info;
7362            for (int i=dest.size()-1; i>=0; i--) {
7363                ServiceInfo destAi = dest.get(i).serviceInfo;
7364                if (destAi.name == filterSi.name
7365                        && destAi.packageName == filterSi.packageName) {
7366                    return false;
7367                }
7368            }
7369            return true;
7370        }
7371
7372        @Override
7373        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7374            return new PackageParser.ServiceIntentInfo[size];
7375        }
7376
7377        @Override
7378        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7379            if (!sUserManager.exists(userId)) return true;
7380            PackageParser.Package p = filter.service.owner;
7381            if (p != null) {
7382                PackageSetting ps = (PackageSetting)p.mExtras;
7383                if (ps != null) {
7384                    // System apps are never considered stopped for purposes of
7385                    // filtering, because there may be no way for the user to
7386                    // actually re-launch them.
7387                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7388                            && ps.getStopped(userId);
7389                }
7390            }
7391            return false;
7392        }
7393
7394        @Override
7395        protected boolean isPackageForFilter(String packageName,
7396                PackageParser.ServiceIntentInfo info) {
7397            return packageName.equals(info.service.owner.packageName);
7398        }
7399
7400        @Override
7401        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7402                int match, int userId) {
7403            if (!sUserManager.exists(userId)) return null;
7404            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7405            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7406                return null;
7407            }
7408            final PackageParser.Service service = info.service;
7409            if (mSafeMode && (service.info.applicationInfo.flags
7410                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7411                return null;
7412            }
7413            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7414            if (ps == null) {
7415                return null;
7416            }
7417            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7418                    ps.readUserState(userId), userId);
7419            if (si == null) {
7420                return null;
7421            }
7422            final ResolveInfo res = new ResolveInfo();
7423            res.serviceInfo = si;
7424            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7425                res.filter = filter;
7426            }
7427            res.priority = info.getPriority();
7428            res.preferredOrder = service.owner.mPreferredOrder;
7429            //System.out.println("Result: " + res.activityInfo.className +
7430            //                   " = " + res.priority);
7431            res.match = match;
7432            res.isDefault = info.hasDefault;
7433            res.labelRes = info.labelRes;
7434            res.nonLocalizedLabel = info.nonLocalizedLabel;
7435            res.icon = info.icon;
7436            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7437            return res;
7438        }
7439
7440        @Override
7441        protected void sortResults(List<ResolveInfo> results) {
7442            Collections.sort(results, mResolvePrioritySorter);
7443        }
7444
7445        @Override
7446        protected void dumpFilter(PrintWriter out, String prefix,
7447                PackageParser.ServiceIntentInfo filter) {
7448            out.print(prefix); out.print(
7449                    Integer.toHexString(System.identityHashCode(filter.service)));
7450                    out.print(' ');
7451                    filter.service.printComponentShortName(out);
7452                    out.print(" filter ");
7453                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7454        }
7455
7456        @Override
7457        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
7458            return filter.service;
7459        }
7460
7461        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7462            PackageParser.Service service = (PackageParser.Service)label;
7463            out.print(prefix); out.print(
7464                    Integer.toHexString(System.identityHashCode(service)));
7465                    out.print(' ');
7466                    service.printComponentShortName(out);
7467            if (count > 1) {
7468                out.print(" ("); out.print(count); out.print(" filters)");
7469            }
7470            out.println();
7471        }
7472
7473//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7474//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7475//            final List<ResolveInfo> retList = Lists.newArrayList();
7476//            while (i.hasNext()) {
7477//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7478//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7479//                    retList.add(resolveInfo);
7480//                }
7481//            }
7482//            return retList;
7483//        }
7484
7485        // Keys are String (activity class name), values are Activity.
7486        private final ArrayMap<ComponentName, PackageParser.Service> mServices
7487                = new ArrayMap<ComponentName, PackageParser.Service>();
7488        private int mFlags;
7489    };
7490
7491    private final class ProviderIntentResolver
7492            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7493        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7494                boolean defaultOnly, int userId) {
7495            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7496            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7497        }
7498
7499        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7500                int userId) {
7501            if (!sUserManager.exists(userId))
7502                return null;
7503            mFlags = flags;
7504            return super.queryIntent(intent, resolvedType,
7505                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7506        }
7507
7508        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7509                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7510            if (!sUserManager.exists(userId))
7511                return null;
7512            if (packageProviders == null) {
7513                return null;
7514            }
7515            mFlags = flags;
7516            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7517            final int N = packageProviders.size();
7518            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7519                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7520
7521            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7522            for (int i = 0; i < N; ++i) {
7523                intentFilters = packageProviders.get(i).intents;
7524                if (intentFilters != null && intentFilters.size() > 0) {
7525                    PackageParser.ProviderIntentInfo[] array =
7526                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7527                    intentFilters.toArray(array);
7528                    listCut.add(array);
7529                }
7530            }
7531            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7532        }
7533
7534        public final void addProvider(PackageParser.Provider p) {
7535            if (mProviders.containsKey(p.getComponentName())) {
7536                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7537                return;
7538            }
7539
7540            mProviders.put(p.getComponentName(), p);
7541            if (DEBUG_SHOW_INFO) {
7542                Log.v(TAG, "  "
7543                        + (p.info.nonLocalizedLabel != null
7544                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7545                Log.v(TAG, "    Class=" + p.info.name);
7546            }
7547            final int NI = p.intents.size();
7548            int j;
7549            for (j = 0; j < NI; j++) {
7550                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7551                if (DEBUG_SHOW_INFO) {
7552                    Log.v(TAG, "    IntentFilter:");
7553                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7554                }
7555                if (!intent.debugCheck()) {
7556                    Log.w(TAG, "==> For Provider " + p.info.name);
7557                }
7558                addFilter(intent);
7559            }
7560        }
7561
7562        public final void removeProvider(PackageParser.Provider p) {
7563            mProviders.remove(p.getComponentName());
7564            if (DEBUG_SHOW_INFO) {
7565                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7566                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7567                Log.v(TAG, "    Class=" + p.info.name);
7568            }
7569            final int NI = p.intents.size();
7570            int j;
7571            for (j = 0; j < NI; j++) {
7572                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7573                if (DEBUG_SHOW_INFO) {
7574                    Log.v(TAG, "    IntentFilter:");
7575                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7576                }
7577                removeFilter(intent);
7578            }
7579        }
7580
7581        @Override
7582        protected boolean allowFilterResult(
7583                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7584            ProviderInfo filterPi = filter.provider.info;
7585            for (int i = dest.size() - 1; i >= 0; i--) {
7586                ProviderInfo destPi = dest.get(i).providerInfo;
7587                if (destPi.name == filterPi.name
7588                        && destPi.packageName == filterPi.packageName) {
7589                    return false;
7590                }
7591            }
7592            return true;
7593        }
7594
7595        @Override
7596        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7597            return new PackageParser.ProviderIntentInfo[size];
7598        }
7599
7600        @Override
7601        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7602            if (!sUserManager.exists(userId))
7603                return true;
7604            PackageParser.Package p = filter.provider.owner;
7605            if (p != null) {
7606                PackageSetting ps = (PackageSetting) p.mExtras;
7607                if (ps != null) {
7608                    // System apps are never considered stopped for purposes of
7609                    // filtering, because there may be no way for the user to
7610                    // actually re-launch them.
7611                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7612                            && ps.getStopped(userId);
7613                }
7614            }
7615            return false;
7616        }
7617
7618        @Override
7619        protected boolean isPackageForFilter(String packageName,
7620                PackageParser.ProviderIntentInfo info) {
7621            return packageName.equals(info.provider.owner.packageName);
7622        }
7623
7624        @Override
7625        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7626                int match, int userId) {
7627            if (!sUserManager.exists(userId))
7628                return null;
7629            final PackageParser.ProviderIntentInfo info = filter;
7630            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7631                return null;
7632            }
7633            final PackageParser.Provider provider = info.provider;
7634            if (mSafeMode && (provider.info.applicationInfo.flags
7635                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7636                return null;
7637            }
7638            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7639            if (ps == null) {
7640                return null;
7641            }
7642            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7643                    ps.readUserState(userId), userId);
7644            if (pi == null) {
7645                return null;
7646            }
7647            final ResolveInfo res = new ResolveInfo();
7648            res.providerInfo = pi;
7649            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7650                res.filter = filter;
7651            }
7652            res.priority = info.getPriority();
7653            res.preferredOrder = provider.owner.mPreferredOrder;
7654            res.match = match;
7655            res.isDefault = info.hasDefault;
7656            res.labelRes = info.labelRes;
7657            res.nonLocalizedLabel = info.nonLocalizedLabel;
7658            res.icon = info.icon;
7659            res.system = isSystemApp(res.providerInfo.applicationInfo);
7660            return res;
7661        }
7662
7663        @Override
7664        protected void sortResults(List<ResolveInfo> results) {
7665            Collections.sort(results, mResolvePrioritySorter);
7666        }
7667
7668        @Override
7669        protected void dumpFilter(PrintWriter out, String prefix,
7670                PackageParser.ProviderIntentInfo filter) {
7671            out.print(prefix);
7672            out.print(
7673                    Integer.toHexString(System.identityHashCode(filter.provider)));
7674            out.print(' ');
7675            filter.provider.printComponentShortName(out);
7676            out.print(" filter ");
7677            out.println(Integer.toHexString(System.identityHashCode(filter)));
7678        }
7679
7680        @Override
7681        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
7682            return filter.provider;
7683        }
7684
7685        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7686            PackageParser.Provider provider = (PackageParser.Provider)label;
7687            out.print(prefix); out.print(
7688                    Integer.toHexString(System.identityHashCode(provider)));
7689                    out.print(' ');
7690                    provider.printComponentShortName(out);
7691            if (count > 1) {
7692                out.print(" ("); out.print(count); out.print(" filters)");
7693            }
7694            out.println();
7695        }
7696
7697        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
7698                = new ArrayMap<ComponentName, PackageParser.Provider>();
7699        private int mFlags;
7700    };
7701
7702    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7703            new Comparator<ResolveInfo>() {
7704        public int compare(ResolveInfo r1, ResolveInfo r2) {
7705            int v1 = r1.priority;
7706            int v2 = r2.priority;
7707            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7708            if (v1 != v2) {
7709                return (v1 > v2) ? -1 : 1;
7710            }
7711            v1 = r1.preferredOrder;
7712            v2 = r2.preferredOrder;
7713            if (v1 != v2) {
7714                return (v1 > v2) ? -1 : 1;
7715            }
7716            if (r1.isDefault != r2.isDefault) {
7717                return r1.isDefault ? -1 : 1;
7718            }
7719            v1 = r1.match;
7720            v2 = r2.match;
7721            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7722            if (v1 != v2) {
7723                return (v1 > v2) ? -1 : 1;
7724            }
7725            if (r1.system != r2.system) {
7726                return r1.system ? -1 : 1;
7727            }
7728            return 0;
7729        }
7730    };
7731
7732    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7733            new Comparator<ProviderInfo>() {
7734        public int compare(ProviderInfo p1, ProviderInfo p2) {
7735            final int v1 = p1.initOrder;
7736            final int v2 = p2.initOrder;
7737            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7738        }
7739    };
7740
7741    static final void sendPackageBroadcast(String action, String pkg,
7742            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7743            int[] userIds) {
7744        IActivityManager am = ActivityManagerNative.getDefault();
7745        if (am != null) {
7746            try {
7747                if (userIds == null) {
7748                    userIds = am.getRunningUserIds();
7749                }
7750                for (int id : userIds) {
7751                    final Intent intent = new Intent(action,
7752                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7753                    if (extras != null) {
7754                        intent.putExtras(extras);
7755                    }
7756                    if (targetPkg != null) {
7757                        intent.setPackage(targetPkg);
7758                    }
7759                    // Modify the UID when posting to other users
7760                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7761                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7762                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7763                        intent.putExtra(Intent.EXTRA_UID, uid);
7764                    }
7765                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7766                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7767                    if (DEBUG_BROADCASTS) {
7768                        RuntimeException here = new RuntimeException("here");
7769                        here.fillInStackTrace();
7770                        Slog.d(TAG, "Sending to user " + id + ": "
7771                                + intent.toShortString(false, true, false, false)
7772                                + " " + intent.getExtras(), here);
7773                    }
7774                    am.broadcastIntent(null, intent, null, finishedReceiver,
7775                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7776                            finishedReceiver != null, false, id);
7777                }
7778            } catch (RemoteException ex) {
7779            }
7780        }
7781    }
7782
7783    /**
7784     * Check if the external storage media is available. This is true if there
7785     * is a mounted external storage medium or if the external storage is
7786     * emulated.
7787     */
7788    private boolean isExternalMediaAvailable() {
7789        return mMediaMounted || Environment.isExternalStorageEmulated();
7790    }
7791
7792    @Override
7793    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7794        // writer
7795        synchronized (mPackages) {
7796            if (!isExternalMediaAvailable()) {
7797                // If the external storage is no longer mounted at this point,
7798                // the caller may not have been able to delete all of this
7799                // packages files and can not delete any more.  Bail.
7800                return null;
7801            }
7802            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7803            if (lastPackage != null) {
7804                pkgs.remove(lastPackage);
7805            }
7806            if (pkgs.size() > 0) {
7807                return pkgs.get(0);
7808            }
7809        }
7810        return null;
7811    }
7812
7813    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7814        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7815                userId, andCode ? 1 : 0, packageName);
7816        if (mSystemReady) {
7817            msg.sendToTarget();
7818        } else {
7819            if (mPostSystemReadyMessages == null) {
7820                mPostSystemReadyMessages = new ArrayList<>();
7821            }
7822            mPostSystemReadyMessages.add(msg);
7823        }
7824    }
7825
7826    void startCleaningPackages() {
7827        // reader
7828        synchronized (mPackages) {
7829            if (!isExternalMediaAvailable()) {
7830                return;
7831            }
7832            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7833                return;
7834            }
7835        }
7836        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7837        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7838        IActivityManager am = ActivityManagerNative.getDefault();
7839        if (am != null) {
7840            try {
7841                am.startService(null, intent, null, UserHandle.USER_OWNER);
7842            } catch (RemoteException e) {
7843            }
7844        }
7845    }
7846
7847    @Override
7848    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7849            int installFlags, String installerPackageName, VerificationParams verificationParams,
7850            String packageAbiOverride) {
7851        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7852                packageAbiOverride, UserHandle.getCallingUserId());
7853    }
7854
7855    @Override
7856    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7857            int installFlags, String installerPackageName, VerificationParams verificationParams,
7858            String packageAbiOverride, int userId) {
7859        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
7860
7861        final int callingUid = Binder.getCallingUid();
7862        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
7863
7864        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7865            try {
7866                if (observer != null) {
7867                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7868                }
7869            } catch (RemoteException re) {
7870            }
7871            return;
7872        }
7873
7874        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
7875            installFlags |= PackageManager.INSTALL_FROM_ADB;
7876
7877        } else {
7878            // Caller holds INSTALL_PACKAGES permission, so we're less strict
7879            // about installerPackageName.
7880
7881            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
7882            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
7883        }
7884
7885        UserHandle user;
7886        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7887            user = UserHandle.ALL;
7888        } else {
7889            user = new UserHandle(userId);
7890        }
7891
7892        verificationParams.setInstallerUid(callingUid);
7893
7894        final File originFile = new File(originPath);
7895        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7896
7897        final Message msg = mHandler.obtainMessage(INIT_COPY);
7898        msg.obj = new InstallParams(origin, observer, installFlags,
7899                installerPackageName, verificationParams, user, packageAbiOverride);
7900        mHandler.sendMessage(msg);
7901    }
7902
7903    void installStage(String packageName, File stagedDir, String stagedCid,
7904            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7905            String installerPackageName, int installerUid, UserHandle user) {
7906        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7907                params.referrerUri, installerUid, null);
7908
7909        final OriginInfo origin;
7910        if (stagedDir != null) {
7911            origin = OriginInfo.fromStagedFile(stagedDir);
7912        } else {
7913            origin = OriginInfo.fromStagedContainer(stagedCid);
7914        }
7915
7916        final Message msg = mHandler.obtainMessage(INIT_COPY);
7917        msg.obj = new InstallParams(origin, observer, params.installFlags,
7918                installerPackageName, verifParams, user, params.abiOverride);
7919        mHandler.sendMessage(msg);
7920    }
7921
7922    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7923        Bundle extras = new Bundle(1);
7924        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7925
7926        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7927                packageName, extras, null, null, new int[] {userId});
7928        try {
7929            IActivityManager am = ActivityManagerNative.getDefault();
7930            final boolean isSystem =
7931                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7932            if (isSystem && am.isUserRunning(userId, false)) {
7933                // The just-installed/enabled app is bundled on the system, so presumed
7934                // to be able to run automatically without needing an explicit launch.
7935                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7936                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7937                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7938                        .setPackage(packageName);
7939                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7940                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7941            }
7942        } catch (RemoteException e) {
7943            // shouldn't happen
7944            Slog.w(TAG, "Unable to bootstrap installed package", e);
7945        }
7946    }
7947
7948    @Override
7949    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7950            int userId) {
7951        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7952        PackageSetting pkgSetting;
7953        final int uid = Binder.getCallingUid();
7954        enforceCrossUserPermission(uid, userId, true, true,
7955                "setApplicationHiddenSetting for user " + userId);
7956
7957        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7958            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7959            return false;
7960        }
7961
7962        long callingId = Binder.clearCallingIdentity();
7963        try {
7964            boolean sendAdded = false;
7965            boolean sendRemoved = false;
7966            // writer
7967            synchronized (mPackages) {
7968                pkgSetting = mSettings.mPackages.get(packageName);
7969                if (pkgSetting == null) {
7970                    return false;
7971                }
7972                if (pkgSetting.getHidden(userId) != hidden) {
7973                    pkgSetting.setHidden(hidden, userId);
7974                    mSettings.writePackageRestrictionsLPr(userId);
7975                    if (hidden) {
7976                        sendRemoved = true;
7977                    } else {
7978                        sendAdded = true;
7979                    }
7980                }
7981            }
7982            if (sendAdded) {
7983                sendPackageAddedForUser(packageName, pkgSetting, userId);
7984                return true;
7985            }
7986            if (sendRemoved) {
7987                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7988                        "hiding pkg");
7989                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7990            }
7991        } finally {
7992            Binder.restoreCallingIdentity(callingId);
7993        }
7994        return false;
7995    }
7996
7997    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7998            int userId) {
7999        final PackageRemovedInfo info = new PackageRemovedInfo();
8000        info.removedPackage = packageName;
8001        info.removedUsers = new int[] {userId};
8002        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8003        info.sendBroadcast(false, false, false);
8004    }
8005
8006    /**
8007     * Returns true if application is not found or there was an error. Otherwise it returns
8008     * the hidden state of the package for the given user.
8009     */
8010    @Override
8011    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8012        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8013        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8014                false, "getApplicationHidden for user " + userId);
8015        PackageSetting pkgSetting;
8016        long callingId = Binder.clearCallingIdentity();
8017        try {
8018            // writer
8019            synchronized (mPackages) {
8020                pkgSetting = mSettings.mPackages.get(packageName);
8021                if (pkgSetting == null) {
8022                    return true;
8023                }
8024                return pkgSetting.getHidden(userId);
8025            }
8026        } finally {
8027            Binder.restoreCallingIdentity(callingId);
8028        }
8029    }
8030
8031    /**
8032     * @hide
8033     */
8034    @Override
8035    public int installExistingPackageAsUser(String packageName, int userId) {
8036        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8037                null);
8038        PackageSetting pkgSetting;
8039        final int uid = Binder.getCallingUid();
8040        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8041                + userId);
8042        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8043            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8044        }
8045
8046        long callingId = Binder.clearCallingIdentity();
8047        try {
8048            boolean sendAdded = false;
8049            Bundle extras = new Bundle(1);
8050
8051            // writer
8052            synchronized (mPackages) {
8053                pkgSetting = mSettings.mPackages.get(packageName);
8054                if (pkgSetting == null) {
8055                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8056                }
8057                if (!pkgSetting.getInstalled(userId)) {
8058                    pkgSetting.setInstalled(true, userId);
8059                    pkgSetting.setHidden(false, userId);
8060                    mSettings.writePackageRestrictionsLPr(userId);
8061                    sendAdded = true;
8062                }
8063            }
8064
8065            if (sendAdded) {
8066                sendPackageAddedForUser(packageName, pkgSetting, userId);
8067            }
8068        } finally {
8069            Binder.restoreCallingIdentity(callingId);
8070        }
8071
8072        return PackageManager.INSTALL_SUCCEEDED;
8073    }
8074
8075    boolean isUserRestricted(int userId, String restrictionKey) {
8076        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8077        if (restrictions.getBoolean(restrictionKey, false)) {
8078            Log.w(TAG, "User is restricted: " + restrictionKey);
8079            return true;
8080        }
8081        return false;
8082    }
8083
8084    @Override
8085    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8086        mContext.enforceCallingOrSelfPermission(
8087                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8088                "Only package verification agents can verify applications");
8089
8090        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8091        final PackageVerificationResponse response = new PackageVerificationResponse(
8092                verificationCode, Binder.getCallingUid());
8093        msg.arg1 = id;
8094        msg.obj = response;
8095        mHandler.sendMessage(msg);
8096    }
8097
8098    @Override
8099    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8100            long millisecondsToDelay) {
8101        mContext.enforceCallingOrSelfPermission(
8102                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8103                "Only package verification agents can extend verification timeouts");
8104
8105        final PackageVerificationState state = mPendingVerification.get(id);
8106        final PackageVerificationResponse response = new PackageVerificationResponse(
8107                verificationCodeAtTimeout, Binder.getCallingUid());
8108
8109        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8110            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8111        }
8112        if (millisecondsToDelay < 0) {
8113            millisecondsToDelay = 0;
8114        }
8115        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8116                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8117            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8118        }
8119
8120        if ((state != null) && !state.timeoutExtended()) {
8121            state.extendTimeout();
8122
8123            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8124            msg.arg1 = id;
8125            msg.obj = response;
8126            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8127        }
8128    }
8129
8130    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8131            int verificationCode, UserHandle user) {
8132        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8133        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8134        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8135        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8136        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8137
8138        mContext.sendBroadcastAsUser(intent, user,
8139                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8140    }
8141
8142    private ComponentName matchComponentForVerifier(String packageName,
8143            List<ResolveInfo> receivers) {
8144        ActivityInfo targetReceiver = null;
8145
8146        final int NR = receivers.size();
8147        for (int i = 0; i < NR; i++) {
8148            final ResolveInfo info = receivers.get(i);
8149            if (info.activityInfo == null) {
8150                continue;
8151            }
8152
8153            if (packageName.equals(info.activityInfo.packageName)) {
8154                targetReceiver = info.activityInfo;
8155                break;
8156            }
8157        }
8158
8159        if (targetReceiver == null) {
8160            return null;
8161        }
8162
8163        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8164    }
8165
8166    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8167            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8168        if (pkgInfo.verifiers.length == 0) {
8169            return null;
8170        }
8171
8172        final int N = pkgInfo.verifiers.length;
8173        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8174        for (int i = 0; i < N; i++) {
8175            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8176
8177            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8178                    receivers);
8179            if (comp == null) {
8180                continue;
8181            }
8182
8183            final int verifierUid = getUidForVerifier(verifierInfo);
8184            if (verifierUid == -1) {
8185                continue;
8186            }
8187
8188            if (DEBUG_VERIFY) {
8189                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8190                        + " with the correct signature");
8191            }
8192            sufficientVerifiers.add(comp);
8193            verificationState.addSufficientVerifier(verifierUid);
8194        }
8195
8196        return sufficientVerifiers;
8197    }
8198
8199    private int getUidForVerifier(VerifierInfo verifierInfo) {
8200        synchronized (mPackages) {
8201            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8202            if (pkg == null) {
8203                return -1;
8204            } else if (pkg.mSignatures.length != 1) {
8205                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8206                        + " has more than one signature; ignoring");
8207                return -1;
8208            }
8209
8210            /*
8211             * If the public key of the package's signature does not match
8212             * our expected public key, then this is a different package and
8213             * we should skip.
8214             */
8215
8216            final byte[] expectedPublicKey;
8217            try {
8218                final Signature verifierSig = pkg.mSignatures[0];
8219                final PublicKey publicKey = verifierSig.getPublicKey();
8220                expectedPublicKey = publicKey.getEncoded();
8221            } catch (CertificateException e) {
8222                return -1;
8223            }
8224
8225            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8226
8227            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8228                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8229                        + " does not have the expected public key; ignoring");
8230                return -1;
8231            }
8232
8233            return pkg.applicationInfo.uid;
8234        }
8235    }
8236
8237    @Override
8238    public void finishPackageInstall(int token) {
8239        enforceSystemOrRoot("Only the system is allowed to finish installs");
8240
8241        if (DEBUG_INSTALL) {
8242            Slog.v(TAG, "BM finishing package install for " + token);
8243        }
8244
8245        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8246        mHandler.sendMessage(msg);
8247    }
8248
8249    /**
8250     * Get the verification agent timeout.
8251     *
8252     * @return verification timeout in milliseconds
8253     */
8254    private long getVerificationTimeout() {
8255        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8256                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8257                DEFAULT_VERIFICATION_TIMEOUT);
8258    }
8259
8260    /**
8261     * Get the default verification agent response code.
8262     *
8263     * @return default verification response code
8264     */
8265    private int getDefaultVerificationResponse() {
8266        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8267                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8268                DEFAULT_VERIFICATION_RESPONSE);
8269    }
8270
8271    /**
8272     * Check whether or not package verification has been enabled.
8273     *
8274     * @return true if verification should be performed
8275     */
8276    private boolean isVerificationEnabled(int userId, int installFlags) {
8277        if (!DEFAULT_VERIFY_ENABLE) {
8278            return false;
8279        }
8280
8281        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8282
8283        // Check if installing from ADB
8284        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8285            // Do not run verification in a test harness environment
8286            if (ActivityManager.isRunningInTestHarness()) {
8287                return false;
8288            }
8289            if (ensureVerifyAppsEnabled) {
8290                return true;
8291            }
8292            // Check if the developer does not want package verification for ADB installs
8293            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8294                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8295                return false;
8296            }
8297        }
8298
8299        if (ensureVerifyAppsEnabled) {
8300            return true;
8301        }
8302
8303        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8304                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8305    }
8306
8307    /**
8308     * Get the "allow unknown sources" setting.
8309     *
8310     * @return the current "allow unknown sources" setting
8311     */
8312    private int getUnknownSourcesSettings() {
8313        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8314                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8315                -1);
8316    }
8317
8318    @Override
8319    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8320        final int uid = Binder.getCallingUid();
8321        // writer
8322        synchronized (mPackages) {
8323            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8324            if (targetPackageSetting == null) {
8325                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8326            }
8327
8328            PackageSetting installerPackageSetting;
8329            if (installerPackageName != null) {
8330                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8331                if (installerPackageSetting == null) {
8332                    throw new IllegalArgumentException("Unknown installer package: "
8333                            + installerPackageName);
8334                }
8335            } else {
8336                installerPackageSetting = null;
8337            }
8338
8339            Signature[] callerSignature;
8340            Object obj = mSettings.getUserIdLPr(uid);
8341            if (obj != null) {
8342                if (obj instanceof SharedUserSetting) {
8343                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8344                } else if (obj instanceof PackageSetting) {
8345                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8346                } else {
8347                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8348                }
8349            } else {
8350                throw new SecurityException("Unknown calling uid " + uid);
8351            }
8352
8353            // Verify: can't set installerPackageName to a package that is
8354            // not signed with the same cert as the caller.
8355            if (installerPackageSetting != null) {
8356                if (compareSignatures(callerSignature,
8357                        installerPackageSetting.signatures.mSignatures)
8358                        != PackageManager.SIGNATURE_MATCH) {
8359                    throw new SecurityException(
8360                            "Caller does not have same cert as new installer package "
8361                            + installerPackageName);
8362                }
8363            }
8364
8365            // Verify: if target already has an installer package, it must
8366            // be signed with the same cert as the caller.
8367            if (targetPackageSetting.installerPackageName != null) {
8368                PackageSetting setting = mSettings.mPackages.get(
8369                        targetPackageSetting.installerPackageName);
8370                // If the currently set package isn't valid, then it's always
8371                // okay to change it.
8372                if (setting != null) {
8373                    if (compareSignatures(callerSignature,
8374                            setting.signatures.mSignatures)
8375                            != PackageManager.SIGNATURE_MATCH) {
8376                        throw new SecurityException(
8377                                "Caller does not have same cert as old installer package "
8378                                + targetPackageSetting.installerPackageName);
8379                    }
8380                }
8381            }
8382
8383            // Okay!
8384            targetPackageSetting.installerPackageName = installerPackageName;
8385            scheduleWriteSettingsLocked();
8386        }
8387    }
8388
8389    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8390        // Queue up an async operation since the package installation may take a little while.
8391        mHandler.post(new Runnable() {
8392            public void run() {
8393                mHandler.removeCallbacks(this);
8394                 // Result object to be returned
8395                PackageInstalledInfo res = new PackageInstalledInfo();
8396                res.returnCode = currentStatus;
8397                res.uid = -1;
8398                res.pkg = null;
8399                res.removedInfo = new PackageRemovedInfo();
8400                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8401                    args.doPreInstall(res.returnCode);
8402                    synchronized (mInstallLock) {
8403                        installPackageLI(args, res);
8404                    }
8405                    args.doPostInstall(res.returnCode, res.uid);
8406                }
8407
8408                // A restore should be performed at this point if (a) the install
8409                // succeeded, (b) the operation is not an update, and (c) the new
8410                // package has not opted out of backup participation.
8411                final boolean update = res.removedInfo.removedPackage != null;
8412                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8413                boolean doRestore = !update
8414                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8415
8416                // Set up the post-install work request bookkeeping.  This will be used
8417                // and cleaned up by the post-install event handling regardless of whether
8418                // there's a restore pass performed.  Token values are >= 1.
8419                int token;
8420                if (mNextInstallToken < 0) mNextInstallToken = 1;
8421                token = mNextInstallToken++;
8422
8423                PostInstallData data = new PostInstallData(args, res);
8424                mRunningInstalls.put(token, data);
8425                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8426
8427                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8428                    // Pass responsibility to the Backup Manager.  It will perform a
8429                    // restore if appropriate, then pass responsibility back to the
8430                    // Package Manager to run the post-install observer callbacks
8431                    // and broadcasts.
8432                    IBackupManager bm = IBackupManager.Stub.asInterface(
8433                            ServiceManager.getService(Context.BACKUP_SERVICE));
8434                    if (bm != null) {
8435                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8436                                + " to BM for possible restore");
8437                        try {
8438                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
8439                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8440                            } else {
8441                                doRestore = false;
8442                            }
8443                        } catch (RemoteException e) {
8444                            // can't happen; the backup manager is local
8445                        } catch (Exception e) {
8446                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8447                            doRestore = false;
8448                        }
8449                    } else {
8450                        Slog.e(TAG, "Backup Manager not found!");
8451                        doRestore = false;
8452                    }
8453                }
8454
8455                if (!doRestore) {
8456                    // No restore possible, or the Backup Manager was mysteriously not
8457                    // available -- just fire the post-install work request directly.
8458                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8459                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8460                    mHandler.sendMessage(msg);
8461                }
8462            }
8463        });
8464    }
8465
8466    private abstract class HandlerParams {
8467        private static final int MAX_RETRIES = 4;
8468
8469        /**
8470         * Number of times startCopy() has been attempted and had a non-fatal
8471         * error.
8472         */
8473        private int mRetries = 0;
8474
8475        /** User handle for the user requesting the information or installation. */
8476        private final UserHandle mUser;
8477
8478        HandlerParams(UserHandle user) {
8479            mUser = user;
8480        }
8481
8482        UserHandle getUser() {
8483            return mUser;
8484        }
8485
8486        final boolean startCopy() {
8487            boolean res;
8488            try {
8489                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8490
8491                if (++mRetries > MAX_RETRIES) {
8492                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8493                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8494                    handleServiceError();
8495                    return false;
8496                } else {
8497                    handleStartCopy();
8498                    res = true;
8499                }
8500            } catch (RemoteException e) {
8501                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8502                mHandler.sendEmptyMessage(MCS_RECONNECT);
8503                res = false;
8504            }
8505            handleReturnCode();
8506            return res;
8507        }
8508
8509        final void serviceError() {
8510            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8511            handleServiceError();
8512            handleReturnCode();
8513        }
8514
8515        abstract void handleStartCopy() throws RemoteException;
8516        abstract void handleServiceError();
8517        abstract void handleReturnCode();
8518    }
8519
8520    class MeasureParams extends HandlerParams {
8521        private final PackageStats mStats;
8522        private boolean mSuccess;
8523
8524        private final IPackageStatsObserver mObserver;
8525
8526        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8527            super(new UserHandle(stats.userHandle));
8528            mObserver = observer;
8529            mStats = stats;
8530        }
8531
8532        @Override
8533        public String toString() {
8534            return "MeasureParams{"
8535                + Integer.toHexString(System.identityHashCode(this))
8536                + " " + mStats.packageName + "}";
8537        }
8538
8539        @Override
8540        void handleStartCopy() throws RemoteException {
8541            synchronized (mInstallLock) {
8542                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8543            }
8544
8545            if (mSuccess) {
8546                final boolean mounted;
8547                if (Environment.isExternalStorageEmulated()) {
8548                    mounted = true;
8549                } else {
8550                    final String status = Environment.getExternalStorageState();
8551                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8552                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8553                }
8554
8555                if (mounted) {
8556                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8557
8558                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8559                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8560
8561                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8562                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8563
8564                    // Always subtract cache size, since it's a subdirectory
8565                    mStats.externalDataSize -= mStats.externalCacheSize;
8566
8567                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8568                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8569
8570                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8571                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8572                }
8573            }
8574        }
8575
8576        @Override
8577        void handleReturnCode() {
8578            if (mObserver != null) {
8579                try {
8580                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8581                } catch (RemoteException e) {
8582                    Slog.i(TAG, "Observer no longer exists.");
8583                }
8584            }
8585        }
8586
8587        @Override
8588        void handleServiceError() {
8589            Slog.e(TAG, "Could not measure application " + mStats.packageName
8590                            + " external storage");
8591        }
8592    }
8593
8594    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8595            throws RemoteException {
8596        long result = 0;
8597        for (File path : paths) {
8598            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8599        }
8600        return result;
8601    }
8602
8603    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8604        for (File path : paths) {
8605            try {
8606                mcs.clearDirectory(path.getAbsolutePath());
8607            } catch (RemoteException e) {
8608            }
8609        }
8610    }
8611
8612    static class OriginInfo {
8613        /**
8614         * Location where install is coming from, before it has been
8615         * copied/renamed into place. This could be a single monolithic APK
8616         * file, or a cluster directory. This location may be untrusted.
8617         */
8618        final File file;
8619        final String cid;
8620
8621        /**
8622         * Flag indicating that {@link #file} or {@link #cid} has already been
8623         * staged, meaning downstream users don't need to defensively copy the
8624         * contents.
8625         */
8626        final boolean staged;
8627
8628        /**
8629         * Flag indicating that {@link #file} or {@link #cid} is an already
8630         * installed app that is being moved.
8631         */
8632        final boolean existing;
8633
8634        final String resolvedPath;
8635        final File resolvedFile;
8636
8637        static OriginInfo fromNothing() {
8638            return new OriginInfo(null, null, false, false);
8639        }
8640
8641        static OriginInfo fromUntrustedFile(File file) {
8642            return new OriginInfo(file, null, false, false);
8643        }
8644
8645        static OriginInfo fromExistingFile(File file) {
8646            return new OriginInfo(file, null, false, true);
8647        }
8648
8649        static OriginInfo fromStagedFile(File file) {
8650            return new OriginInfo(file, null, true, false);
8651        }
8652
8653        static OriginInfo fromStagedContainer(String cid) {
8654            return new OriginInfo(null, cid, true, false);
8655        }
8656
8657        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8658            this.file = file;
8659            this.cid = cid;
8660            this.staged = staged;
8661            this.existing = existing;
8662
8663            if (cid != null) {
8664                resolvedPath = PackageHelper.getSdDir(cid);
8665                resolvedFile = new File(resolvedPath);
8666            } else if (file != null) {
8667                resolvedPath = file.getAbsolutePath();
8668                resolvedFile = file;
8669            } else {
8670                resolvedPath = null;
8671                resolvedFile = null;
8672            }
8673        }
8674    }
8675
8676    class InstallParams extends HandlerParams {
8677        final OriginInfo origin;
8678        final IPackageInstallObserver2 observer;
8679        int installFlags;
8680        final String installerPackageName;
8681        final VerificationParams verificationParams;
8682        private InstallArgs mArgs;
8683        private int mRet;
8684        final String packageAbiOverride;
8685
8686        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8687                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8688                String packageAbiOverride) {
8689            super(user);
8690            this.origin = origin;
8691            this.observer = observer;
8692            this.installFlags = installFlags;
8693            this.installerPackageName = installerPackageName;
8694            this.verificationParams = verificationParams;
8695            this.packageAbiOverride = packageAbiOverride;
8696        }
8697
8698        @Override
8699        public String toString() {
8700            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8701                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8702        }
8703
8704        public ManifestDigest getManifestDigest() {
8705            if (verificationParams == null) {
8706                return null;
8707            }
8708            return verificationParams.getManifestDigest();
8709        }
8710
8711        private int installLocationPolicy(PackageInfoLite pkgLite) {
8712            String packageName = pkgLite.packageName;
8713            int installLocation = pkgLite.installLocation;
8714            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8715            // reader
8716            synchronized (mPackages) {
8717                PackageParser.Package pkg = mPackages.get(packageName);
8718                if (pkg != null) {
8719                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8720                        // Check for downgrading.
8721                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8722                            try {
8723                                checkDowngrade(pkg, pkgLite);
8724                            } catch (PackageManagerException e) {
8725                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
8726                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8727                            }
8728                        }
8729                        // Check for updated system application.
8730                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8731                            if (onSd) {
8732                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8733                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8734                            }
8735                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8736                        } else {
8737                            if (onSd) {
8738                                // Install flag overrides everything.
8739                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8740                            }
8741                            // If current upgrade specifies particular preference
8742                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8743                                // Application explicitly specified internal.
8744                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8745                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8746                                // App explictly prefers external. Let policy decide
8747                            } else {
8748                                // Prefer previous location
8749                                if (isExternal(pkg)) {
8750                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8751                                }
8752                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8753                            }
8754                        }
8755                    } else {
8756                        // Invalid install. Return error code
8757                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8758                    }
8759                }
8760            }
8761            // All the special cases have been taken care of.
8762            // Return result based on recommended install location.
8763            if (onSd) {
8764                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8765            }
8766            return pkgLite.recommendedInstallLocation;
8767        }
8768
8769        /*
8770         * Invoke remote method to get package information and install
8771         * location values. Override install location based on default
8772         * policy if needed and then create install arguments based
8773         * on the install location.
8774         */
8775        public void handleStartCopy() throws RemoteException {
8776            int ret = PackageManager.INSTALL_SUCCEEDED;
8777
8778            // If we're already staged, we've firmly committed to an install location
8779            if (origin.staged) {
8780                if (origin.file != null) {
8781                    installFlags |= PackageManager.INSTALL_INTERNAL;
8782                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8783                } else if (origin.cid != null) {
8784                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8785                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8786                } else {
8787                    throw new IllegalStateException("Invalid stage location");
8788                }
8789            }
8790
8791            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8792            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8793
8794            PackageInfoLite pkgLite = null;
8795
8796            if (onInt && onSd) {
8797                // Check if both bits are set.
8798                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8799                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8800            } else {
8801                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8802                        packageAbiOverride);
8803
8804                /*
8805                 * If we have too little free space, try to free cache
8806                 * before giving up.
8807                 */
8808                if (!origin.staged && pkgLite.recommendedInstallLocation
8809                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8810                    // TODO: focus freeing disk space on the target device
8811                    final StorageManager storage = StorageManager.from(mContext);
8812                    final long lowThreshold = storage.getStorageLowBytes(
8813                            Environment.getDataDirectory());
8814
8815                    final long sizeBytes = mContainerService.calculateInstalledSize(
8816                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8817
8818                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8819                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8820                                installFlags, packageAbiOverride);
8821                    }
8822
8823                    /*
8824                     * The cache free must have deleted the file we
8825                     * downloaded to install.
8826                     *
8827                     * TODO: fix the "freeCache" call to not delete
8828                     *       the file we care about.
8829                     */
8830                    if (pkgLite.recommendedInstallLocation
8831                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8832                        pkgLite.recommendedInstallLocation
8833                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8834                    }
8835                }
8836            }
8837
8838            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8839                int loc = pkgLite.recommendedInstallLocation;
8840                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8841                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8842                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8843                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8844                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8845                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8846                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8847                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8848                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8849                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8850                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8851                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8852                } else {
8853                    // Override with defaults if needed.
8854                    loc = installLocationPolicy(pkgLite);
8855                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8856                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8857                    } else if (!onSd && !onInt) {
8858                        // Override install location with flags
8859                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8860                            // Set the flag to install on external media.
8861                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8862                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8863                        } else {
8864                            // Make sure the flag for installing on external
8865                            // media is unset
8866                            installFlags |= PackageManager.INSTALL_INTERNAL;
8867                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8868                        }
8869                    }
8870                }
8871            }
8872
8873            final InstallArgs args = createInstallArgs(this);
8874            mArgs = args;
8875
8876            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8877                 /*
8878                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8879                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8880                 */
8881                int userIdentifier = getUser().getIdentifier();
8882                if (userIdentifier == UserHandle.USER_ALL
8883                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8884                    userIdentifier = UserHandle.USER_OWNER;
8885                }
8886
8887                /*
8888                 * Determine if we have any installed package verifiers. If we
8889                 * do, then we'll defer to them to verify the packages.
8890                 */
8891                final int requiredUid = mRequiredVerifierPackage == null ? -1
8892                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8893                if (!origin.existing && requiredUid != -1
8894                        && isVerificationEnabled(userIdentifier, installFlags)) {
8895                    final Intent verification = new Intent(
8896                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8897                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
8898                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8899                            PACKAGE_MIME_TYPE);
8900                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8901
8902                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8903                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8904                            0 /* TODO: Which userId? */);
8905
8906                    if (DEBUG_VERIFY) {
8907                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8908                                + verification.toString() + " with " + pkgLite.verifiers.length
8909                                + " optional verifiers");
8910                    }
8911
8912                    final int verificationId = mPendingVerificationToken++;
8913
8914                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8915
8916                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8917                            installerPackageName);
8918
8919                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8920                            installFlags);
8921
8922                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8923                            pkgLite.packageName);
8924
8925                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8926                            pkgLite.versionCode);
8927
8928                    if (verificationParams != null) {
8929                        if (verificationParams.getVerificationURI() != null) {
8930                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8931                                 verificationParams.getVerificationURI());
8932                        }
8933                        if (verificationParams.getOriginatingURI() != null) {
8934                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8935                                  verificationParams.getOriginatingURI());
8936                        }
8937                        if (verificationParams.getReferrer() != null) {
8938                            verification.putExtra(Intent.EXTRA_REFERRER,
8939                                  verificationParams.getReferrer());
8940                        }
8941                        if (verificationParams.getOriginatingUid() >= 0) {
8942                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8943                                  verificationParams.getOriginatingUid());
8944                        }
8945                        if (verificationParams.getInstallerUid() >= 0) {
8946                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8947                                  verificationParams.getInstallerUid());
8948                        }
8949                    }
8950
8951                    final PackageVerificationState verificationState = new PackageVerificationState(
8952                            requiredUid, args);
8953
8954                    mPendingVerification.append(verificationId, verificationState);
8955
8956                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8957                            receivers, verificationState);
8958
8959                    /*
8960                     * If any sufficient verifiers were listed in the package
8961                     * manifest, attempt to ask them.
8962                     */
8963                    if (sufficientVerifiers != null) {
8964                        final int N = sufficientVerifiers.size();
8965                        if (N == 0) {
8966                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8967                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8968                        } else {
8969                            for (int i = 0; i < N; i++) {
8970                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8971
8972                                final Intent sufficientIntent = new Intent(verification);
8973                                sufficientIntent.setComponent(verifierComponent);
8974
8975                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8976                            }
8977                        }
8978                    }
8979
8980                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8981                            mRequiredVerifierPackage, receivers);
8982                    if (ret == PackageManager.INSTALL_SUCCEEDED
8983                            && mRequiredVerifierPackage != null) {
8984                        /*
8985                         * Send the intent to the required verification agent,
8986                         * but only start the verification timeout after the
8987                         * target BroadcastReceivers have run.
8988                         */
8989                        verification.setComponent(requiredVerifierComponent);
8990                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8991                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8992                                new BroadcastReceiver() {
8993                                    @Override
8994                                    public void onReceive(Context context, Intent intent) {
8995                                        final Message msg = mHandler
8996                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8997                                        msg.arg1 = verificationId;
8998                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8999                                    }
9000                                }, null, 0, null, null);
9001
9002                        /*
9003                         * We don't want the copy to proceed until verification
9004                         * succeeds, so null out this field.
9005                         */
9006                        mArgs = null;
9007                    }
9008                } else {
9009                    /*
9010                     * No package verification is enabled, so immediately start
9011                     * the remote call to initiate copy using temporary file.
9012                     */
9013                    ret = args.copyApk(mContainerService, true);
9014                }
9015            }
9016
9017            mRet = ret;
9018        }
9019
9020        @Override
9021        void handleReturnCode() {
9022            // If mArgs is null, then MCS couldn't be reached. When it
9023            // reconnects, it will try again to install. At that point, this
9024            // will succeed.
9025            if (mArgs != null) {
9026                processPendingInstall(mArgs, mRet);
9027            }
9028        }
9029
9030        @Override
9031        void handleServiceError() {
9032            mArgs = createInstallArgs(this);
9033            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9034        }
9035
9036        public boolean isForwardLocked() {
9037            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9038        }
9039    }
9040
9041    /**
9042     * Used during creation of InstallArgs
9043     *
9044     * @param installFlags package installation flags
9045     * @return true if should be installed on external storage
9046     */
9047    private static boolean installOnSd(int installFlags) {
9048        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9049            return false;
9050        }
9051        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9052            return true;
9053        }
9054        return false;
9055    }
9056
9057    /**
9058     * Used during creation of InstallArgs
9059     *
9060     * @param installFlags package installation flags
9061     * @return true if should be installed as forward locked
9062     */
9063    private static boolean installForwardLocked(int installFlags) {
9064        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9065    }
9066
9067    private InstallArgs createInstallArgs(InstallParams params) {
9068        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
9069            return new AsecInstallArgs(params);
9070        } else {
9071            return new FileInstallArgs(params);
9072        }
9073    }
9074
9075    /**
9076     * Create args that describe an existing installed package. Typically used
9077     * when cleaning up old installs, or used as a move source.
9078     */
9079    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9080            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9081        final boolean isInAsec;
9082        if (installOnSd(installFlags)) {
9083            /* Apps on SD card are always in ASEC containers. */
9084            isInAsec = true;
9085        } else if (installForwardLocked(installFlags)
9086                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9087            /*
9088             * Forward-locked apps are only in ASEC containers if they're the
9089             * new style
9090             */
9091            isInAsec = true;
9092        } else {
9093            isInAsec = false;
9094        }
9095
9096        if (isInAsec) {
9097            return new AsecInstallArgs(codePath, instructionSets,
9098                    installOnSd(installFlags), installForwardLocked(installFlags));
9099        } else {
9100            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9101                    instructionSets);
9102        }
9103    }
9104
9105    static abstract class InstallArgs {
9106        /** @see InstallParams#origin */
9107        final OriginInfo origin;
9108
9109        final IPackageInstallObserver2 observer;
9110        // Always refers to PackageManager flags only
9111        final int installFlags;
9112        final String installerPackageName;
9113        final ManifestDigest manifestDigest;
9114        final UserHandle user;
9115        final String abiOverride;
9116
9117        // The list of instruction sets supported by this app. This is currently
9118        // only used during the rmdex() phase to clean up resources. We can get rid of this
9119        // if we move dex files under the common app path.
9120        /* nullable */ String[] instructionSets;
9121
9122        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9123                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9124                String[] instructionSets, String abiOverride) {
9125            this.origin = origin;
9126            this.installFlags = installFlags;
9127            this.observer = observer;
9128            this.installerPackageName = installerPackageName;
9129            this.manifestDigest = manifestDigest;
9130            this.user = user;
9131            this.instructionSets = instructionSets;
9132            this.abiOverride = abiOverride;
9133        }
9134
9135        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9136        abstract int doPreInstall(int status);
9137
9138        /**
9139         * Rename package into final resting place. All paths on the given
9140         * scanned package should be updated to reflect the rename.
9141         */
9142        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9143        abstract int doPostInstall(int status, int uid);
9144
9145        /** @see PackageSettingBase#codePathString */
9146        abstract String getCodePath();
9147        /** @see PackageSettingBase#resourcePathString */
9148        abstract String getResourcePath();
9149        abstract String getLegacyNativeLibraryPath();
9150
9151        // Need installer lock especially for dex file removal.
9152        abstract void cleanUpResourcesLI();
9153        abstract boolean doPostDeleteLI(boolean delete);
9154        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9155
9156        /**
9157         * Called before the source arguments are copied. This is used mostly
9158         * for MoveParams when it needs to read the source file to put it in the
9159         * destination.
9160         */
9161        int doPreCopy() {
9162            return PackageManager.INSTALL_SUCCEEDED;
9163        }
9164
9165        /**
9166         * Called after the source arguments are copied. This is used mostly for
9167         * MoveParams when it needs to read the source file to put it in the
9168         * destination.
9169         *
9170         * @return
9171         */
9172        int doPostCopy(int uid) {
9173            return PackageManager.INSTALL_SUCCEEDED;
9174        }
9175
9176        protected boolean isFwdLocked() {
9177            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9178        }
9179
9180        protected boolean isExternal() {
9181            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9182        }
9183
9184        UserHandle getUser() {
9185            return user;
9186        }
9187    }
9188
9189    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
9190        if (!allCodePaths.isEmpty()) {
9191            if (instructionSets == null) {
9192                throw new IllegalStateException("instructionSet == null");
9193            }
9194            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9195            for (String codePath : allCodePaths) {
9196                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9197                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9198                    if (retCode < 0) {
9199                        Slog.w(TAG, "Couldn't remove dex file for package: "
9200                                + " at location " + codePath + ", retcode=" + retCode);
9201                        // we don't consider this to be a failure of the core package deletion
9202                    }
9203                }
9204            }
9205        }
9206    }
9207
9208    /**
9209     * Logic to handle installation of non-ASEC applications, including copying
9210     * and renaming logic.
9211     */
9212    class FileInstallArgs extends InstallArgs {
9213        private File codeFile;
9214        private File resourceFile;
9215        private File legacyNativeLibraryPath;
9216
9217        // Example topology:
9218        // /data/app/com.example/base.apk
9219        // /data/app/com.example/split_foo.apk
9220        // /data/app/com.example/lib/arm/libfoo.so
9221        // /data/app/com.example/lib/arm64/libfoo.so
9222        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9223
9224        /** New install */
9225        FileInstallArgs(InstallParams params) {
9226            super(params.origin, params.observer, params.installFlags,
9227                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9228                    null /* instruction sets */, params.packageAbiOverride);
9229            if (isFwdLocked()) {
9230                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9231            }
9232        }
9233
9234        /** Existing install */
9235        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9236                String[] instructionSets) {
9237            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9238            this.codeFile = (codePath != null) ? new File(codePath) : null;
9239            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9240            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9241                    new File(legacyNativeLibraryPath) : null;
9242        }
9243
9244        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9245            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9246                    isFwdLocked(), abiOverride);
9247
9248            final StorageManager storage = StorageManager.from(mContext);
9249            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9250        }
9251
9252        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9253            if (origin.staged) {
9254                Slog.d(TAG, origin.file + " already staged; skipping copy");
9255                codeFile = origin.file;
9256                resourceFile = origin.file;
9257                return PackageManager.INSTALL_SUCCEEDED;
9258            }
9259
9260            try {
9261                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9262                codeFile = tempDir;
9263                resourceFile = tempDir;
9264            } catch (IOException e) {
9265                Slog.w(TAG, "Failed to create copy file: " + e);
9266                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9267            }
9268
9269            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9270                @Override
9271                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9272                    if (!FileUtils.isValidExtFilename(name)) {
9273                        throw new IllegalArgumentException("Invalid filename: " + name);
9274                    }
9275                    try {
9276                        final File file = new File(codeFile, name);
9277                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9278                                O_RDWR | O_CREAT, 0644);
9279                        Os.chmod(file.getAbsolutePath(), 0644);
9280                        return new ParcelFileDescriptor(fd);
9281                    } catch (ErrnoException e) {
9282                        throw new RemoteException("Failed to open: " + e.getMessage());
9283                    }
9284                }
9285            };
9286
9287            int ret = PackageManager.INSTALL_SUCCEEDED;
9288            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9289            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9290                Slog.e(TAG, "Failed to copy package");
9291                return ret;
9292            }
9293
9294            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9295            NativeLibraryHelper.Handle handle = null;
9296            try {
9297                handle = NativeLibraryHelper.Handle.create(codeFile);
9298                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9299                        abiOverride);
9300            } catch (IOException e) {
9301                Slog.e(TAG, "Copying native libraries failed", e);
9302                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9303            } finally {
9304                IoUtils.closeQuietly(handle);
9305            }
9306
9307            return ret;
9308        }
9309
9310        int doPreInstall(int status) {
9311            if (status != PackageManager.INSTALL_SUCCEEDED) {
9312                cleanUp();
9313            }
9314            return status;
9315        }
9316
9317        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9318            if (status != PackageManager.INSTALL_SUCCEEDED) {
9319                cleanUp();
9320                return false;
9321            } else {
9322                final File beforeCodeFile = codeFile;
9323                final File afterCodeFile = getNextCodePath(pkg.packageName);
9324
9325                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9326                try {
9327                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9328                } catch (ErrnoException e) {
9329                    Slog.d(TAG, "Failed to rename", e);
9330                    return false;
9331                }
9332
9333                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9334                    Slog.d(TAG, "Failed to restorecon");
9335                    return false;
9336                }
9337
9338                // Reflect the rename internally
9339                codeFile = afterCodeFile;
9340                resourceFile = afterCodeFile;
9341
9342                // Reflect the rename in scanned details
9343                pkg.codePath = afterCodeFile.getAbsolutePath();
9344                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9345                        pkg.baseCodePath);
9346                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9347                        pkg.splitCodePaths);
9348
9349                // Reflect the rename in app info
9350                pkg.applicationInfo.setCodePath(pkg.codePath);
9351                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9352                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9353                pkg.applicationInfo.setResourcePath(pkg.codePath);
9354                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9355                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9356
9357                return true;
9358            }
9359        }
9360
9361        int doPostInstall(int status, int uid) {
9362            if (status != PackageManager.INSTALL_SUCCEEDED) {
9363                cleanUp();
9364            }
9365            return status;
9366        }
9367
9368        @Override
9369        String getCodePath() {
9370            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9371        }
9372
9373        @Override
9374        String getResourcePath() {
9375            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9376        }
9377
9378        @Override
9379        String getLegacyNativeLibraryPath() {
9380            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9381        }
9382
9383        private boolean cleanUp() {
9384            if (codeFile == null || !codeFile.exists()) {
9385                return false;
9386            }
9387
9388            if (codeFile.isDirectory()) {
9389                FileUtils.deleteContents(codeFile);
9390            }
9391            codeFile.delete();
9392
9393            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9394                resourceFile.delete();
9395            }
9396
9397            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9398                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9399                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9400                }
9401                legacyNativeLibraryPath.delete();
9402            }
9403
9404            return true;
9405        }
9406
9407        void cleanUpResourcesLI() {
9408            // Try enumerating all code paths before deleting
9409            List<String> allCodePaths = Collections.EMPTY_LIST;
9410            if (codeFile != null && codeFile.exists()) {
9411                try {
9412                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9413                    allCodePaths = pkg.getAllCodePaths();
9414                } catch (PackageParserException e) {
9415                    // Ignored; we tried our best
9416                }
9417            }
9418
9419            cleanUp();
9420            removeDexFiles(allCodePaths, instructionSets);
9421        }
9422
9423        boolean doPostDeleteLI(boolean delete) {
9424            // XXX err, shouldn't we respect the delete flag?
9425            cleanUpResourcesLI();
9426            return true;
9427        }
9428    }
9429
9430    private boolean isAsecExternal(String cid) {
9431        final String asecPath = PackageHelper.getSdFilesystem(cid);
9432        return !asecPath.startsWith(mAsecInternalPath);
9433    }
9434
9435    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9436            PackageManagerException {
9437        if (copyRet < 0) {
9438            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9439                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9440                throw new PackageManagerException(copyRet, message);
9441            }
9442        }
9443    }
9444
9445    /**
9446     * Extract the MountService "container ID" from the full code path of an
9447     * .apk.
9448     */
9449    static String cidFromCodePath(String fullCodePath) {
9450        int eidx = fullCodePath.lastIndexOf("/");
9451        String subStr1 = fullCodePath.substring(0, eidx);
9452        int sidx = subStr1.lastIndexOf("/");
9453        return subStr1.substring(sidx+1, eidx);
9454    }
9455
9456    /**
9457     * Logic to handle installation of ASEC applications, including copying and
9458     * renaming logic.
9459     */
9460    class AsecInstallArgs extends InstallArgs {
9461        static final String RES_FILE_NAME = "pkg.apk";
9462        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9463
9464        String cid;
9465        String packagePath;
9466        String resourcePath;
9467        String legacyNativeLibraryDir;
9468
9469        /** New install */
9470        AsecInstallArgs(InstallParams params) {
9471            super(params.origin, params.observer, params.installFlags,
9472                    params.installerPackageName, params.getManifestDigest(),
9473                    params.getUser(), null /* instruction sets */,
9474                    params.packageAbiOverride);
9475        }
9476
9477        /** Existing install */
9478        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9479                        boolean isExternal, boolean isForwardLocked) {
9480            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9481                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9482                    instructionSets, null);
9483            // Hackily pretend we're still looking at a full code path
9484            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9485                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9486            }
9487
9488            // Extract cid from fullCodePath
9489            int eidx = fullCodePath.lastIndexOf("/");
9490            String subStr1 = fullCodePath.substring(0, eidx);
9491            int sidx = subStr1.lastIndexOf("/");
9492            cid = subStr1.substring(sidx+1, eidx);
9493            setMountPath(subStr1);
9494        }
9495
9496        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9497            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9498                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9499                    instructionSets, null);
9500            this.cid = cid;
9501            setMountPath(PackageHelper.getSdDir(cid));
9502        }
9503
9504        void createCopyFile() {
9505            cid = mInstallerService.allocateExternalStageCidLegacy();
9506        }
9507
9508        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9509            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9510                    abiOverride);
9511
9512            final File target;
9513            if (isExternal()) {
9514                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9515            } else {
9516                target = Environment.getDataDirectory();
9517            }
9518
9519            final StorageManager storage = StorageManager.from(mContext);
9520            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9521        }
9522
9523        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9524            if (origin.staged) {
9525                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9526                cid = origin.cid;
9527                setMountPath(PackageHelper.getSdDir(cid));
9528                return PackageManager.INSTALL_SUCCEEDED;
9529            }
9530
9531            if (temp) {
9532                createCopyFile();
9533            } else {
9534                /*
9535                 * Pre-emptively destroy the container since it's destroyed if
9536                 * copying fails due to it existing anyway.
9537                 */
9538                PackageHelper.destroySdDir(cid);
9539            }
9540
9541            final String newMountPath = imcs.copyPackageToContainer(
9542                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9543                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9544
9545            if (newMountPath != null) {
9546                setMountPath(newMountPath);
9547                return PackageManager.INSTALL_SUCCEEDED;
9548            } else {
9549                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9550            }
9551        }
9552
9553        @Override
9554        String getCodePath() {
9555            return packagePath;
9556        }
9557
9558        @Override
9559        String getResourcePath() {
9560            return resourcePath;
9561        }
9562
9563        @Override
9564        String getLegacyNativeLibraryPath() {
9565            return legacyNativeLibraryDir;
9566        }
9567
9568        int doPreInstall(int status) {
9569            if (status != PackageManager.INSTALL_SUCCEEDED) {
9570                // Destroy container
9571                PackageHelper.destroySdDir(cid);
9572            } else {
9573                boolean mounted = PackageHelper.isContainerMounted(cid);
9574                if (!mounted) {
9575                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9576                            Process.SYSTEM_UID);
9577                    if (newMountPath != null) {
9578                        setMountPath(newMountPath);
9579                    } else {
9580                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9581                    }
9582                }
9583            }
9584            return status;
9585        }
9586
9587        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9588            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9589            String newMountPath = null;
9590            if (PackageHelper.isContainerMounted(cid)) {
9591                // Unmount the container
9592                if (!PackageHelper.unMountSdDir(cid)) {
9593                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9594                    return false;
9595                }
9596            }
9597            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9598                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9599                        " which might be stale. Will try to clean up.");
9600                // Clean up the stale container and proceed to recreate.
9601                if (!PackageHelper.destroySdDir(newCacheId)) {
9602                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9603                    return false;
9604                }
9605                // Successfully cleaned up stale container. Try to rename again.
9606                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9607                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9608                            + " inspite of cleaning it up.");
9609                    return false;
9610                }
9611            }
9612            if (!PackageHelper.isContainerMounted(newCacheId)) {
9613                Slog.w(TAG, "Mounting container " + newCacheId);
9614                newMountPath = PackageHelper.mountSdDir(newCacheId,
9615                        getEncryptKey(), Process.SYSTEM_UID);
9616            } else {
9617                newMountPath = PackageHelper.getSdDir(newCacheId);
9618            }
9619            if (newMountPath == null) {
9620                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9621                return false;
9622            }
9623            Log.i(TAG, "Succesfully renamed " + cid +
9624                    " to " + newCacheId +
9625                    " at new path: " + newMountPath);
9626            cid = newCacheId;
9627
9628            final File beforeCodeFile = new File(packagePath);
9629            setMountPath(newMountPath);
9630            final File afterCodeFile = new File(packagePath);
9631
9632            // Reflect the rename in scanned details
9633            pkg.codePath = afterCodeFile.getAbsolutePath();
9634            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9635                    pkg.baseCodePath);
9636            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9637                    pkg.splitCodePaths);
9638
9639            // Reflect the rename in app info
9640            pkg.applicationInfo.setCodePath(pkg.codePath);
9641            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9642            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9643            pkg.applicationInfo.setResourcePath(pkg.codePath);
9644            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9645            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9646
9647            return true;
9648        }
9649
9650        private void setMountPath(String mountPath) {
9651            final File mountFile = new File(mountPath);
9652
9653            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9654            if (monolithicFile.exists()) {
9655                packagePath = monolithicFile.getAbsolutePath();
9656                if (isFwdLocked()) {
9657                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9658                } else {
9659                    resourcePath = packagePath;
9660                }
9661            } else {
9662                packagePath = mountFile.getAbsolutePath();
9663                resourcePath = packagePath;
9664            }
9665
9666            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9667        }
9668
9669        int doPostInstall(int status, int uid) {
9670            if (status != PackageManager.INSTALL_SUCCEEDED) {
9671                cleanUp();
9672            } else {
9673                final int groupOwner;
9674                final String protectedFile;
9675                if (isFwdLocked()) {
9676                    groupOwner = UserHandle.getSharedAppGid(uid);
9677                    protectedFile = RES_FILE_NAME;
9678                } else {
9679                    groupOwner = -1;
9680                    protectedFile = null;
9681                }
9682
9683                if (uid < Process.FIRST_APPLICATION_UID
9684                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9685                    Slog.e(TAG, "Failed to finalize " + cid);
9686                    PackageHelper.destroySdDir(cid);
9687                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9688                }
9689
9690                boolean mounted = PackageHelper.isContainerMounted(cid);
9691                if (!mounted) {
9692                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9693                }
9694            }
9695            return status;
9696        }
9697
9698        private void cleanUp() {
9699            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9700
9701            // Destroy secure container
9702            PackageHelper.destroySdDir(cid);
9703        }
9704
9705        private List<String> getAllCodePaths() {
9706            final File codeFile = new File(getCodePath());
9707            if (codeFile != null && codeFile.exists()) {
9708                try {
9709                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9710                    return pkg.getAllCodePaths();
9711                } catch (PackageParserException e) {
9712                    // Ignored; we tried our best
9713                }
9714            }
9715            return Collections.EMPTY_LIST;
9716        }
9717
9718        void cleanUpResourcesLI() {
9719            // Enumerate all code paths before deleting
9720            cleanUpResourcesLI(getAllCodePaths());
9721        }
9722
9723        private void cleanUpResourcesLI(List<String> allCodePaths) {
9724            cleanUp();
9725            removeDexFiles(allCodePaths, instructionSets);
9726        }
9727
9728
9729
9730        String getPackageName() {
9731            return getAsecPackageName(cid);
9732        }
9733
9734        boolean doPostDeleteLI(boolean delete) {
9735            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9736            final List<String> allCodePaths = getAllCodePaths();
9737            boolean mounted = PackageHelper.isContainerMounted(cid);
9738            if (mounted) {
9739                // Unmount first
9740                if (PackageHelper.unMountSdDir(cid)) {
9741                    mounted = false;
9742                }
9743            }
9744            if (!mounted && delete) {
9745                cleanUpResourcesLI(allCodePaths);
9746            }
9747            return !mounted;
9748        }
9749
9750        @Override
9751        int doPreCopy() {
9752            if (isFwdLocked()) {
9753                if (!PackageHelper.fixSdPermissions(cid,
9754                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9755                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9756                }
9757            }
9758
9759            return PackageManager.INSTALL_SUCCEEDED;
9760        }
9761
9762        @Override
9763        int doPostCopy(int uid) {
9764            if (isFwdLocked()) {
9765                if (uid < Process.FIRST_APPLICATION_UID
9766                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9767                                RES_FILE_NAME)) {
9768                    Slog.e(TAG, "Failed to finalize " + cid);
9769                    PackageHelper.destroySdDir(cid);
9770                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9771                }
9772            }
9773
9774            return PackageManager.INSTALL_SUCCEEDED;
9775        }
9776    }
9777
9778    static String getAsecPackageName(String packageCid) {
9779        int idx = packageCid.lastIndexOf("-");
9780        if (idx == -1) {
9781            return packageCid;
9782        }
9783        return packageCid.substring(0, idx);
9784    }
9785
9786    // Utility method used to create code paths based on package name and available index.
9787    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9788        String idxStr = "";
9789        int idx = 1;
9790        // Fall back to default value of idx=1 if prefix is not
9791        // part of oldCodePath
9792        if (oldCodePath != null) {
9793            String subStr = oldCodePath;
9794            // Drop the suffix right away
9795            if (suffix != null && subStr.endsWith(suffix)) {
9796                subStr = subStr.substring(0, subStr.length() - suffix.length());
9797            }
9798            // If oldCodePath already contains prefix find out the
9799            // ending index to either increment or decrement.
9800            int sidx = subStr.lastIndexOf(prefix);
9801            if (sidx != -1) {
9802                subStr = subStr.substring(sidx + prefix.length());
9803                if (subStr != null) {
9804                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9805                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9806                    }
9807                    try {
9808                        idx = Integer.parseInt(subStr);
9809                        if (idx <= 1) {
9810                            idx++;
9811                        } else {
9812                            idx--;
9813                        }
9814                    } catch(NumberFormatException e) {
9815                    }
9816                }
9817            }
9818        }
9819        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9820        return prefix + idxStr;
9821    }
9822
9823    private File getNextCodePath(String packageName) {
9824        int suffix = 1;
9825        File result;
9826        do {
9827            result = new File(mAppInstallDir, packageName + "-" + suffix);
9828            suffix++;
9829        } while (result.exists());
9830        return result;
9831    }
9832
9833    // Utility method used to ignore ADD/REMOVE events
9834    // by directory observer.
9835    private static boolean ignoreCodePath(String fullPathStr) {
9836        String apkName = deriveCodePathName(fullPathStr);
9837        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9838        if (idx != -1 && ((idx+1) < apkName.length())) {
9839            // Make sure the package ends with a numeral
9840            String version = apkName.substring(idx+1);
9841            try {
9842                Integer.parseInt(version);
9843                return true;
9844            } catch (NumberFormatException e) {}
9845        }
9846        return false;
9847    }
9848
9849    // Utility method that returns the relative package path with respect
9850    // to the installation directory. Like say for /data/data/com.test-1.apk
9851    // string com.test-1 is returned.
9852    static String deriveCodePathName(String codePath) {
9853        if (codePath == null) {
9854            return null;
9855        }
9856        final File codeFile = new File(codePath);
9857        final String name = codeFile.getName();
9858        if (codeFile.isDirectory()) {
9859            return name;
9860        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9861            final int lastDot = name.lastIndexOf('.');
9862            return name.substring(0, lastDot);
9863        } else {
9864            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9865            return null;
9866        }
9867    }
9868
9869    class PackageInstalledInfo {
9870        String name;
9871        int uid;
9872        // The set of users that originally had this package installed.
9873        int[] origUsers;
9874        // The set of users that now have this package installed.
9875        int[] newUsers;
9876        PackageParser.Package pkg;
9877        int returnCode;
9878        String returnMsg;
9879        PackageRemovedInfo removedInfo;
9880
9881        public void setError(int code, String msg) {
9882            returnCode = code;
9883            returnMsg = msg;
9884            Slog.w(TAG, msg);
9885        }
9886
9887        public void setError(String msg, PackageParserException e) {
9888            returnCode = e.error;
9889            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9890            Slog.w(TAG, msg, e);
9891        }
9892
9893        public void setError(String msg, PackageManagerException e) {
9894            returnCode = e.error;
9895            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9896            Slog.w(TAG, msg, e);
9897        }
9898
9899        // In some error cases we want to convey more info back to the observer
9900        String origPackage;
9901        String origPermission;
9902    }
9903
9904    /*
9905     * Install a non-existing package.
9906     */
9907    private void installNewPackageLI(PackageParser.Package pkg,
9908            int parseFlags, int scanFlags, UserHandle user,
9909            String installerPackageName, PackageInstalledInfo res) {
9910        // Remember this for later, in case we need to rollback this install
9911        String pkgName = pkg.packageName;
9912
9913        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9914        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9915        synchronized(mPackages) {
9916            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9917                // A package with the same name is already installed, though
9918                // it has been renamed to an older name.  The package we
9919                // are trying to install should be installed as an update to
9920                // the existing one, but that has not been requested, so bail.
9921                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9922                        + " without first uninstalling package running as "
9923                        + mSettings.mRenamedPackages.get(pkgName));
9924                return;
9925            }
9926            if (mPackages.containsKey(pkgName)) {
9927                // Don't allow installation over an existing package with the same name.
9928                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9929                        + " without first uninstalling.");
9930                return;
9931            }
9932        }
9933
9934        try {
9935            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9936                    System.currentTimeMillis(), user);
9937
9938            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9939            // delete the partially installed application. the data directory will have to be
9940            // restored if it was already existing
9941            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9942                // remove package from internal structures.  Note that we want deletePackageX to
9943                // delete the package data and cache directories that it created in
9944                // scanPackageLocked, unless those directories existed before we even tried to
9945                // install.
9946                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9947                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9948                                res.removedInfo, true);
9949            }
9950
9951        } catch (PackageManagerException e) {
9952            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9953        }
9954    }
9955
9956    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9957        // Upgrade keysets are being used.  Determine if new package has a superset of the
9958        // required keys.
9959        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9960        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9961        for (int i = 0; i < upgradeKeySets.length; i++) {
9962            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9963            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9964                return true;
9965            }
9966        }
9967        return false;
9968    }
9969
9970    private void replacePackageLI(PackageParser.Package pkg,
9971            int parseFlags, int scanFlags, UserHandle user,
9972            String installerPackageName, PackageInstalledInfo res) {
9973        PackageParser.Package oldPackage;
9974        String pkgName = pkg.packageName;
9975        int[] allUsers;
9976        boolean[] perUserInstalled;
9977
9978        // First find the old package info and check signatures
9979        synchronized(mPackages) {
9980            oldPackage = mPackages.get(pkgName);
9981            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9982            PackageSetting ps = mSettings.mPackages.get(pkgName);
9983            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9984                // default to original signature matching
9985                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9986                    != PackageManager.SIGNATURE_MATCH) {
9987                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9988                            "New package has a different signature: " + pkgName);
9989                    return;
9990                }
9991            } else {
9992                if(!checkUpgradeKeySetLP(ps, pkg)) {
9993                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9994                            "New package not signed by keys specified by upgrade-keysets: "
9995                            + pkgName);
9996                    return;
9997                }
9998            }
9999
10000            // In case of rollback, remember per-user/profile install state
10001            allUsers = sUserManager.getUserIds();
10002            perUserInstalled = new boolean[allUsers.length];
10003            for (int i = 0; i < allUsers.length; i++) {
10004                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10005            }
10006        }
10007
10008        boolean sysPkg = (isSystemApp(oldPackage));
10009        if (sysPkg) {
10010            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10011                    user, allUsers, perUserInstalled, installerPackageName, res);
10012        } else {
10013            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10014                    user, allUsers, perUserInstalled, installerPackageName, res);
10015        }
10016    }
10017
10018    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10019            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10020            int[] allUsers, boolean[] perUserInstalled,
10021            String installerPackageName, PackageInstalledInfo res) {
10022        String pkgName = deletedPackage.packageName;
10023        boolean deletedPkg = true;
10024        boolean updatedSettings = false;
10025
10026        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10027                + deletedPackage);
10028        long origUpdateTime;
10029        if (pkg.mExtras != null) {
10030            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10031        } else {
10032            origUpdateTime = 0;
10033        }
10034
10035        // First delete the existing package while retaining the data directory
10036        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10037                res.removedInfo, true)) {
10038            // If the existing package wasn't successfully deleted
10039            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10040            deletedPkg = false;
10041        } else {
10042            // Successfully deleted the old package; proceed with replace.
10043
10044            // If deleted package lived in a container, give users a chance to
10045            // relinquish resources before killing.
10046            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
10047                if (DEBUG_INSTALL) {
10048                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10049                }
10050                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10051                final ArrayList<String> pkgList = new ArrayList<String>(1);
10052                pkgList.add(deletedPackage.applicationInfo.packageName);
10053                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10054            }
10055
10056            deleteCodeCacheDirsLI(pkgName);
10057            try {
10058                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10059                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10060                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10061                updatedSettings = true;
10062            } catch (PackageManagerException e) {
10063                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10064            }
10065        }
10066
10067        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10068            // remove package from internal structures.  Note that we want deletePackageX to
10069            // delete the package data and cache directories that it created in
10070            // scanPackageLocked, unless those directories existed before we even tried to
10071            // install.
10072            if(updatedSettings) {
10073                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10074                deletePackageLI(
10075                        pkgName, null, true, allUsers, perUserInstalled,
10076                        PackageManager.DELETE_KEEP_DATA,
10077                                res.removedInfo, true);
10078            }
10079            // Since we failed to install the new package we need to restore the old
10080            // package that we deleted.
10081            if (deletedPkg) {
10082                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10083                File restoreFile = new File(deletedPackage.codePath);
10084                // Parse old package
10085                boolean oldOnSd = isExternal(deletedPackage);
10086                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10087                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10088                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10089                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10090                try {
10091                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10092                } catch (PackageManagerException e) {
10093                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10094                            + e.getMessage());
10095                    return;
10096                }
10097                // Restore of old package succeeded. Update permissions.
10098                // writer
10099                synchronized (mPackages) {
10100                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10101                            UPDATE_PERMISSIONS_ALL);
10102                    // can downgrade to reader
10103                    mSettings.writeLPr();
10104                }
10105                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10106            }
10107        }
10108    }
10109
10110    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10111            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10112            int[] allUsers, boolean[] perUserInstalled,
10113            String installerPackageName, PackageInstalledInfo res) {
10114        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10115                + ", old=" + deletedPackage);
10116        boolean disabledSystem = false;
10117        boolean updatedSettings = false;
10118        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10119        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
10120                != 0) {
10121            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10122        }
10123        String packageName = deletedPackage.packageName;
10124        if (packageName == null) {
10125            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10126                    "Attempt to delete null packageName.");
10127            return;
10128        }
10129        PackageParser.Package oldPkg;
10130        PackageSetting oldPkgSetting;
10131        // reader
10132        synchronized (mPackages) {
10133            oldPkg = mPackages.get(packageName);
10134            oldPkgSetting = mSettings.mPackages.get(packageName);
10135            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10136                    (oldPkgSetting == null)) {
10137                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10138                        "Couldn't find package:" + packageName + " information");
10139                return;
10140            }
10141        }
10142
10143        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10144
10145        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10146        res.removedInfo.removedPackage = packageName;
10147        // Remove existing system package
10148        removePackageLI(oldPkgSetting, true);
10149        // writer
10150        synchronized (mPackages) {
10151            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10152            if (!disabledSystem && deletedPackage != null) {
10153                // We didn't need to disable the .apk as a current system package,
10154                // which means we are replacing another update that is already
10155                // installed.  We need to make sure to delete the older one's .apk.
10156                res.removedInfo.args = createInstallArgsForExisting(0,
10157                        deletedPackage.applicationInfo.getCodePath(),
10158                        deletedPackage.applicationInfo.getResourcePath(),
10159                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10160                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10161            } else {
10162                res.removedInfo.args = null;
10163            }
10164        }
10165
10166        // Successfully disabled the old package. Now proceed with re-installation
10167        deleteCodeCacheDirsLI(packageName);
10168
10169        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10170        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10171
10172        PackageParser.Package newPackage = null;
10173        try {
10174            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10175            if (newPackage.mExtras != null) {
10176                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10177                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10178                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10179
10180                // is the update attempting to change shared user? that isn't going to work...
10181                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10182                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10183                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10184                            + " to " + newPkgSetting.sharedUser);
10185                    updatedSettings = true;
10186                }
10187            }
10188
10189            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10190                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10191                updatedSettings = true;
10192            }
10193
10194        } catch (PackageManagerException e) {
10195            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10196        }
10197
10198        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10199            // Re installation failed. Restore old information
10200            // Remove new pkg information
10201            if (newPackage != null) {
10202                removeInstalledPackageLI(newPackage, true);
10203            }
10204            // Add back the old system package
10205            try {
10206                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10207            } catch (PackageManagerException e) {
10208                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10209            }
10210            // Restore the old system information in Settings
10211            synchronized (mPackages) {
10212                if (disabledSystem) {
10213                    mSettings.enableSystemPackageLPw(packageName);
10214                }
10215                if (updatedSettings) {
10216                    mSettings.setInstallerPackageName(packageName,
10217                            oldPkgSetting.installerPackageName);
10218                }
10219                mSettings.writeLPr();
10220            }
10221        }
10222    }
10223
10224    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10225            int[] allUsers, boolean[] perUserInstalled,
10226            PackageInstalledInfo res) {
10227        String pkgName = newPackage.packageName;
10228        synchronized (mPackages) {
10229            //write settings. the installStatus will be incomplete at this stage.
10230            //note that the new package setting would have already been
10231            //added to mPackages. It hasn't been persisted yet.
10232            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10233            mSettings.writeLPr();
10234        }
10235
10236        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10237
10238        synchronized (mPackages) {
10239            updatePermissionsLPw(newPackage.packageName, newPackage,
10240                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10241                            ? UPDATE_PERMISSIONS_ALL : 0));
10242            // For system-bundled packages, we assume that installing an upgraded version
10243            // of the package implies that the user actually wants to run that new code,
10244            // so we enable the package.
10245            if (isSystemApp(newPackage)) {
10246                // NB: implicit assumption that system package upgrades apply to all users
10247                if (DEBUG_INSTALL) {
10248                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10249                }
10250                PackageSetting ps = mSettings.mPackages.get(pkgName);
10251                if (ps != null) {
10252                    if (res.origUsers != null) {
10253                        for (int userHandle : res.origUsers) {
10254                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10255                                    userHandle, installerPackageName);
10256                        }
10257                    }
10258                    // Also convey the prior install/uninstall state
10259                    if (allUsers != null && perUserInstalled != null) {
10260                        for (int i = 0; i < allUsers.length; i++) {
10261                            if (DEBUG_INSTALL) {
10262                                Slog.d(TAG, "    user " + allUsers[i]
10263                                        + " => " + perUserInstalled[i]);
10264                            }
10265                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10266                        }
10267                        // these install state changes will be persisted in the
10268                        // upcoming call to mSettings.writeLPr().
10269                    }
10270                }
10271            }
10272            res.name = pkgName;
10273            res.uid = newPackage.applicationInfo.uid;
10274            res.pkg = newPackage;
10275            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10276            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10277            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10278            //to update install status
10279            mSettings.writeLPr();
10280        }
10281    }
10282
10283    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10284        final int installFlags = args.installFlags;
10285        String installerPackageName = args.installerPackageName;
10286        File tmpPackageFile = new File(args.getCodePath());
10287        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10288        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10289        boolean replace = false;
10290        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10291        // Result object to be returned
10292        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10293
10294        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10295        // Retrieve PackageSettings and parse package
10296        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10297                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10298                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10299        PackageParser pp = new PackageParser();
10300        pp.setSeparateProcesses(mSeparateProcesses);
10301        pp.setDisplayMetrics(mMetrics);
10302
10303        final PackageParser.Package pkg;
10304        try {
10305            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10306        } catch (PackageParserException e) {
10307            res.setError("Failed parse during installPackageLI", e);
10308            return;
10309        }
10310
10311        // Mark that we have an install time CPU ABI override.
10312        pkg.cpuAbiOverride = args.abiOverride;
10313
10314        String pkgName = res.name = pkg.packageName;
10315        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10316            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10317                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10318                return;
10319            }
10320        }
10321
10322        try {
10323            pp.collectCertificates(pkg, parseFlags);
10324            pp.collectManifestDigest(pkg);
10325        } catch (PackageParserException e) {
10326            res.setError("Failed collect during installPackageLI", e);
10327            return;
10328        }
10329
10330        /* If the installer passed in a manifest digest, compare it now. */
10331        if (args.manifestDigest != null) {
10332            if (DEBUG_INSTALL) {
10333                final String parsedManifest = pkg.manifestDigest == null ? "null"
10334                        : pkg.manifestDigest.toString();
10335                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10336                        + parsedManifest);
10337            }
10338
10339            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10340                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10341                return;
10342            }
10343        } else if (DEBUG_INSTALL) {
10344            final String parsedManifest = pkg.manifestDigest == null
10345                    ? "null" : pkg.manifestDigest.toString();
10346            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10347        }
10348
10349        // Get rid of all references to package scan path via parser.
10350        pp = null;
10351        String oldCodePath = null;
10352        boolean systemApp = false;
10353        synchronized (mPackages) {
10354            // Check if installing already existing package
10355            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10356                String oldName = mSettings.mRenamedPackages.get(pkgName);
10357                if (pkg.mOriginalPackages != null
10358                        && pkg.mOriginalPackages.contains(oldName)
10359                        && mPackages.containsKey(oldName)) {
10360                    // This package is derived from an original package,
10361                    // and this device has been updating from that original
10362                    // name.  We must continue using the original name, so
10363                    // rename the new package here.
10364                    pkg.setPackageName(oldName);
10365                    pkgName = pkg.packageName;
10366                    replace = true;
10367                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10368                            + oldName + " pkgName=" + pkgName);
10369                } else if (mPackages.containsKey(pkgName)) {
10370                    // This package, under its official name, already exists
10371                    // on the device; we should replace it.
10372                    replace = true;
10373                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10374                }
10375            }
10376
10377            PackageSetting ps = mSettings.mPackages.get(pkgName);
10378            if (ps != null) {
10379                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10380
10381                // Quick sanity check that we're signed correctly if updating;
10382                // we'll check this again later when scanning, but we want to
10383                // bail early here before tripping over redefined permissions.
10384                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10385                    try {
10386                        verifySignaturesLP(ps, pkg);
10387                    } catch (PackageManagerException e) {
10388                        res.setError(e.error, e.getMessage());
10389                        return;
10390                    }
10391                } else {
10392                    if (!checkUpgradeKeySetLP(ps, pkg)) {
10393                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
10394                                + pkg.packageName + " upgrade keys do not match the "
10395                                + "previously installed version");
10396                        return;
10397                    }
10398                }
10399
10400                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10401                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10402                    systemApp = (ps.pkg.applicationInfo.flags &
10403                            ApplicationInfo.FLAG_SYSTEM) != 0;
10404                }
10405                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10406            }
10407
10408            // Check whether the newly-scanned package wants to define an already-defined perm
10409            int N = pkg.permissions.size();
10410            for (int i = N-1; i >= 0; i--) {
10411                PackageParser.Permission perm = pkg.permissions.get(i);
10412                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10413                if (bp != null) {
10414                    // If the defining package is signed with our cert, it's okay.  This
10415                    // also includes the "updating the same package" case, of course.
10416                    // "updating same package" could also involve key-rotation.
10417                    final boolean sigsOk;
10418                    if (!bp.sourcePackage.equals(pkg.packageName)
10419                            || !(bp.packageSetting instanceof PackageSetting)
10420                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10421                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10422                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10423                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10424                    } else {
10425                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10426                    }
10427                    if (!sigsOk) {
10428                        // If the owning package is the system itself, we log but allow
10429                        // install to proceed; we fail the install on all other permission
10430                        // redefinitions.
10431                        if (!bp.sourcePackage.equals("android")) {
10432                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10433                                    + pkg.packageName + " attempting to redeclare permission "
10434                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10435                            res.origPermission = perm.info.name;
10436                            res.origPackage = bp.sourcePackage;
10437                            return;
10438                        } else {
10439                            Slog.w(TAG, "Package " + pkg.packageName
10440                                    + " attempting to redeclare system permission "
10441                                    + perm.info.name + "; ignoring new declaration");
10442                            pkg.permissions.remove(i);
10443                        }
10444                    }
10445                }
10446            }
10447
10448        }
10449
10450        if (systemApp && onSd) {
10451            // Disable updates to system apps on sdcard
10452            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10453                    "Cannot install updates to system apps on sdcard");
10454            return;
10455        }
10456
10457        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10458            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10459            return;
10460        }
10461
10462        if (replace) {
10463            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10464                    installerPackageName, res);
10465        } else {
10466            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10467                    args.user, installerPackageName, res);
10468        }
10469        synchronized (mPackages) {
10470            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10471            if (ps != null) {
10472                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10473            }
10474        }
10475    }
10476
10477    private static boolean isMultiArch(PackageSetting ps) {
10478        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10479    }
10480
10481    private static boolean isMultiArch(ApplicationInfo info) {
10482        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10483    }
10484
10485    private static boolean isExternal(PackageParser.Package pkg) {
10486        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10487    }
10488
10489    private static boolean isExternal(PackageSetting ps) {
10490        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10491    }
10492
10493    private static boolean isExternal(ApplicationInfo info) {
10494        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10495    }
10496
10497    private static boolean isSystemApp(PackageParser.Package pkg) {
10498        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10499    }
10500
10501    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10502        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
10503    }
10504
10505    private static boolean isSystemApp(ApplicationInfo info) {
10506        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10507    }
10508
10509    private static boolean isSystemApp(PackageSetting ps) {
10510        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10511    }
10512
10513    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10514        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10515    }
10516
10517    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10518        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10519    }
10520
10521    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10522        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10523    }
10524
10525    private int packageFlagsToInstallFlags(PackageSetting ps) {
10526        int installFlags = 0;
10527        if (isExternal(ps)) {
10528            installFlags |= PackageManager.INSTALL_EXTERNAL;
10529        }
10530        if (ps.isForwardLocked()) {
10531            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10532        }
10533        return installFlags;
10534    }
10535
10536    private void deleteTempPackageFiles() {
10537        final FilenameFilter filter = new FilenameFilter() {
10538            public boolean accept(File dir, String name) {
10539                return name.startsWith("vmdl") && name.endsWith(".tmp");
10540            }
10541        };
10542        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10543            file.delete();
10544        }
10545    }
10546
10547    @Override
10548    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10549            int flags) {
10550        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10551                flags);
10552    }
10553
10554    @Override
10555    public void deletePackage(final String packageName,
10556            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10557        mContext.enforceCallingOrSelfPermission(
10558                android.Manifest.permission.DELETE_PACKAGES, null);
10559        final int uid = Binder.getCallingUid();
10560        if (UserHandle.getUserId(uid) != userId) {
10561            mContext.enforceCallingPermission(
10562                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10563                    "deletePackage for user " + userId);
10564        }
10565        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10566            try {
10567                observer.onPackageDeleted(packageName,
10568                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10569            } catch (RemoteException re) {
10570            }
10571            return;
10572        }
10573
10574        boolean uninstallBlocked = false;
10575        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10576            int[] users = sUserManager.getUserIds();
10577            for (int i = 0; i < users.length; ++i) {
10578                if (getBlockUninstallForUser(packageName, users[i])) {
10579                    uninstallBlocked = true;
10580                    break;
10581                }
10582            }
10583        } else {
10584            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10585        }
10586        if (uninstallBlocked) {
10587            try {
10588                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10589                        null);
10590            } catch (RemoteException re) {
10591            }
10592            return;
10593        }
10594
10595        if (DEBUG_REMOVE) {
10596            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10597        }
10598        // Queue up an async operation since the package deletion may take a little while.
10599        mHandler.post(new Runnable() {
10600            public void run() {
10601                mHandler.removeCallbacks(this);
10602                final int returnCode = deletePackageX(packageName, userId, flags);
10603                if (observer != null) {
10604                    try {
10605                        observer.onPackageDeleted(packageName, returnCode, null);
10606                    } catch (RemoteException e) {
10607                        Log.i(TAG, "Observer no longer exists.");
10608                    } //end catch
10609                } //end if
10610            } //end run
10611        });
10612    }
10613
10614    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10615        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10616                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10617        try {
10618            if (dpm != null) {
10619                if (dpm.isDeviceOwner(packageName)) {
10620                    return true;
10621                }
10622                int[] users;
10623                if (userId == UserHandle.USER_ALL) {
10624                    users = sUserManager.getUserIds();
10625                } else {
10626                    users = new int[]{userId};
10627                }
10628                for (int i = 0; i < users.length; ++i) {
10629                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10630                        return true;
10631                    }
10632                }
10633            }
10634        } catch (RemoteException e) {
10635        }
10636        return false;
10637    }
10638
10639    /**
10640     *  This method is an internal method that could be get invoked either
10641     *  to delete an installed package or to clean up a failed installation.
10642     *  After deleting an installed package, a broadcast is sent to notify any
10643     *  listeners that the package has been installed. For cleaning up a failed
10644     *  installation, the broadcast is not necessary since the package's
10645     *  installation wouldn't have sent the initial broadcast either
10646     *  The key steps in deleting a package are
10647     *  deleting the package information in internal structures like mPackages,
10648     *  deleting the packages base directories through installd
10649     *  updating mSettings to reflect current status
10650     *  persisting settings for later use
10651     *  sending a broadcast if necessary
10652     */
10653    private int deletePackageX(String packageName, int userId, int flags) {
10654        final PackageRemovedInfo info = new PackageRemovedInfo();
10655        final boolean res;
10656
10657        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10658                ? UserHandle.ALL : new UserHandle(userId);
10659
10660        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10661            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10662            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10663        }
10664
10665        boolean removedForAllUsers = false;
10666        boolean systemUpdate = false;
10667
10668        // for the uninstall-updates case and restricted profiles, remember the per-
10669        // userhandle installed state
10670        int[] allUsers;
10671        boolean[] perUserInstalled;
10672        synchronized (mPackages) {
10673            PackageSetting ps = mSettings.mPackages.get(packageName);
10674            allUsers = sUserManager.getUserIds();
10675            perUserInstalled = new boolean[allUsers.length];
10676            for (int i = 0; i < allUsers.length; i++) {
10677                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10678            }
10679        }
10680
10681        synchronized (mInstallLock) {
10682            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10683            res = deletePackageLI(packageName, removeForUser,
10684                    true, allUsers, perUserInstalled,
10685                    flags | REMOVE_CHATTY, info, true);
10686            systemUpdate = info.isRemovedPackageSystemUpdate;
10687            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10688                removedForAllUsers = true;
10689            }
10690            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10691                    + " removedForAllUsers=" + removedForAllUsers);
10692        }
10693
10694        if (res) {
10695            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10696
10697            // If the removed package was a system update, the old system package
10698            // was re-enabled; we need to broadcast this information
10699            if (systemUpdate) {
10700                Bundle extras = new Bundle(1);
10701                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10702                        ? info.removedAppId : info.uid);
10703                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10704
10705                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10706                        extras, null, null, null);
10707                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10708                        extras, null, null, null);
10709                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10710                        null, packageName, null, null);
10711            }
10712        }
10713        // Force a gc here.
10714        Runtime.getRuntime().gc();
10715        // Delete the resources here after sending the broadcast to let
10716        // other processes clean up before deleting resources.
10717        if (info.args != null) {
10718            synchronized (mInstallLock) {
10719                info.args.doPostDeleteLI(true);
10720            }
10721        }
10722
10723        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10724    }
10725
10726    static class PackageRemovedInfo {
10727        String removedPackage;
10728        int uid = -1;
10729        int removedAppId = -1;
10730        int[] removedUsers = null;
10731        boolean isRemovedPackageSystemUpdate = false;
10732        // Clean up resources deleted packages.
10733        InstallArgs args = null;
10734
10735        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10736            Bundle extras = new Bundle(1);
10737            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10738            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10739            if (replacing) {
10740                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10741            }
10742            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10743            if (removedPackage != null) {
10744                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10745                        extras, null, null, removedUsers);
10746                if (fullRemove && !replacing) {
10747                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10748                            extras, null, null, removedUsers);
10749                }
10750            }
10751            if (removedAppId >= 0) {
10752                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10753                        removedUsers);
10754            }
10755        }
10756    }
10757
10758    /*
10759     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10760     * flag is not set, the data directory is removed as well.
10761     * make sure this flag is set for partially installed apps. If not its meaningless to
10762     * delete a partially installed application.
10763     */
10764    private void removePackageDataLI(PackageSetting ps,
10765            int[] allUserHandles, boolean[] perUserInstalled,
10766            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10767        String packageName = ps.name;
10768        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10769        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10770        // Retrieve object to delete permissions for shared user later on
10771        final PackageSetting deletedPs;
10772        // reader
10773        synchronized (mPackages) {
10774            deletedPs = mSettings.mPackages.get(packageName);
10775            if (outInfo != null) {
10776                outInfo.removedPackage = packageName;
10777                outInfo.removedUsers = deletedPs != null
10778                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10779                        : null;
10780            }
10781        }
10782        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10783            removeDataDirsLI(packageName);
10784            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10785        }
10786        // writer
10787        synchronized (mPackages) {
10788            if (deletedPs != null) {
10789                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10790                    if (outInfo != null) {
10791                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10792                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10793                    }
10794                    if (deletedPs != null) {
10795                        updatePermissionsLPw(deletedPs.name, null, 0);
10796                        if (deletedPs.sharedUser != null) {
10797                            // remove permissions associated with package
10798                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10799                        }
10800                    }
10801                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10802                }
10803                // make sure to preserve per-user disabled state if this removal was just
10804                // a downgrade of a system app to the factory package
10805                if (allUserHandles != null && perUserInstalled != null) {
10806                    if (DEBUG_REMOVE) {
10807                        Slog.d(TAG, "Propagating install state across downgrade");
10808                    }
10809                    for (int i = 0; i < allUserHandles.length; i++) {
10810                        if (DEBUG_REMOVE) {
10811                            Slog.d(TAG, "    user " + allUserHandles[i]
10812                                    + " => " + perUserInstalled[i]);
10813                        }
10814                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10815                    }
10816                }
10817            }
10818            // can downgrade to reader
10819            if (writeSettings) {
10820                // Save settings now
10821                mSettings.writeLPr();
10822            }
10823        }
10824        if (outInfo != null) {
10825            // A user ID was deleted here. Go through all users and remove it
10826            // from KeyStore.
10827            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10828        }
10829    }
10830
10831    static boolean locationIsPrivileged(File path) {
10832        try {
10833            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10834                    .getCanonicalPath();
10835            return path.getCanonicalPath().startsWith(privilegedAppDir);
10836        } catch (IOException e) {
10837            Slog.e(TAG, "Unable to access code path " + path);
10838        }
10839        return false;
10840    }
10841
10842    /*
10843     * Tries to delete system package.
10844     */
10845    private boolean deleteSystemPackageLI(PackageSetting newPs,
10846            int[] allUserHandles, boolean[] perUserInstalled,
10847            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10848        final boolean applyUserRestrictions
10849                = (allUserHandles != null) && (perUserInstalled != null);
10850        PackageSetting disabledPs = null;
10851        // Confirm if the system package has been updated
10852        // An updated system app can be deleted. This will also have to restore
10853        // the system pkg from system partition
10854        // reader
10855        synchronized (mPackages) {
10856            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10857        }
10858        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10859                + " disabledPs=" + disabledPs);
10860        if (disabledPs == null) {
10861            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10862            return false;
10863        } else if (DEBUG_REMOVE) {
10864            Slog.d(TAG, "Deleting system pkg from data partition");
10865        }
10866        if (DEBUG_REMOVE) {
10867            if (applyUserRestrictions) {
10868                Slog.d(TAG, "Remembering install states:");
10869                for (int i = 0; i < allUserHandles.length; i++) {
10870                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10871                }
10872            }
10873        }
10874        // Delete the updated package
10875        outInfo.isRemovedPackageSystemUpdate = true;
10876        if (disabledPs.versionCode < newPs.versionCode) {
10877            // Delete data for downgrades
10878            flags &= ~PackageManager.DELETE_KEEP_DATA;
10879        } else {
10880            // Preserve data by setting flag
10881            flags |= PackageManager.DELETE_KEEP_DATA;
10882        }
10883        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10884                allUserHandles, perUserInstalled, outInfo, writeSettings);
10885        if (!ret) {
10886            return false;
10887        }
10888        // writer
10889        synchronized (mPackages) {
10890            // Reinstate the old system package
10891            mSettings.enableSystemPackageLPw(newPs.name);
10892            // Remove any native libraries from the upgraded package.
10893            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10894        }
10895        // Install the system package
10896        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10897        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10898        if (locationIsPrivileged(disabledPs.codePath)) {
10899            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10900        }
10901
10902        final PackageParser.Package newPkg;
10903        try {
10904            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10905        } catch (PackageManagerException e) {
10906            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10907            return false;
10908        }
10909
10910        // writer
10911        synchronized (mPackages) {
10912            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10913            updatePermissionsLPw(newPkg.packageName, newPkg,
10914                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10915            if (applyUserRestrictions) {
10916                if (DEBUG_REMOVE) {
10917                    Slog.d(TAG, "Propagating install state across reinstall");
10918                }
10919                for (int i = 0; i < allUserHandles.length; i++) {
10920                    if (DEBUG_REMOVE) {
10921                        Slog.d(TAG, "    user " + allUserHandles[i]
10922                                + " => " + perUserInstalled[i]);
10923                    }
10924                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10925                }
10926                // Regardless of writeSettings we need to ensure that this restriction
10927                // state propagation is persisted
10928                mSettings.writeAllUsersPackageRestrictionsLPr();
10929            }
10930            // can downgrade to reader here
10931            if (writeSettings) {
10932                mSettings.writeLPr();
10933            }
10934        }
10935        return true;
10936    }
10937
10938    private boolean deleteInstalledPackageLI(PackageSetting ps,
10939            boolean deleteCodeAndResources, int flags,
10940            int[] allUserHandles, boolean[] perUserInstalled,
10941            PackageRemovedInfo outInfo, boolean writeSettings) {
10942        if (outInfo != null) {
10943            outInfo.uid = ps.appId;
10944        }
10945
10946        // Delete package data from internal structures and also remove data if flag is set
10947        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10948
10949        // Delete application code and resources
10950        if (deleteCodeAndResources && (outInfo != null)) {
10951            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10952                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10953                    getAppDexInstructionSets(ps));
10954            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10955        }
10956        return true;
10957    }
10958
10959    @Override
10960    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10961            int userId) {
10962        mContext.enforceCallingOrSelfPermission(
10963                android.Manifest.permission.DELETE_PACKAGES, null);
10964        synchronized (mPackages) {
10965            PackageSetting ps = mSettings.mPackages.get(packageName);
10966            if (ps == null) {
10967                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10968                return false;
10969            }
10970            if (!ps.getInstalled(userId)) {
10971                // Can't block uninstall for an app that is not installed or enabled.
10972                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10973                return false;
10974            }
10975            ps.setBlockUninstall(blockUninstall, userId);
10976            mSettings.writePackageRestrictionsLPr(userId);
10977        }
10978        return true;
10979    }
10980
10981    @Override
10982    public boolean getBlockUninstallForUser(String packageName, int userId) {
10983        synchronized (mPackages) {
10984            PackageSetting ps = mSettings.mPackages.get(packageName);
10985            if (ps == null) {
10986                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10987                return false;
10988            }
10989            return ps.getBlockUninstall(userId);
10990        }
10991    }
10992
10993    /*
10994     * This method handles package deletion in general
10995     */
10996    private boolean deletePackageLI(String packageName, UserHandle user,
10997            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10998            int flags, PackageRemovedInfo outInfo,
10999            boolean writeSettings) {
11000        if (packageName == null) {
11001            Slog.w(TAG, "Attempt to delete null packageName.");
11002            return false;
11003        }
11004        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11005        PackageSetting ps;
11006        boolean dataOnly = false;
11007        int removeUser = -1;
11008        int appId = -1;
11009        synchronized (mPackages) {
11010            ps = mSettings.mPackages.get(packageName);
11011            if (ps == null) {
11012                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11013                return false;
11014            }
11015            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11016                    && user.getIdentifier() != UserHandle.USER_ALL) {
11017                // The caller is asking that the package only be deleted for a single
11018                // user.  To do this, we just mark its uninstalled state and delete
11019                // its data.  If this is a system app, we only allow this to happen if
11020                // they have set the special DELETE_SYSTEM_APP which requests different
11021                // semantics than normal for uninstalling system apps.
11022                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11023                ps.setUserState(user.getIdentifier(),
11024                        COMPONENT_ENABLED_STATE_DEFAULT,
11025                        false, //installed
11026                        true,  //stopped
11027                        true,  //notLaunched
11028                        false, //hidden
11029                        null, null, null,
11030                        false // blockUninstall
11031                        );
11032                if (!isSystemApp(ps)) {
11033                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11034                        // Other user still have this package installed, so all
11035                        // we need to do is clear this user's data and save that
11036                        // it is uninstalled.
11037                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11038                        removeUser = user.getIdentifier();
11039                        appId = ps.appId;
11040                        mSettings.writePackageRestrictionsLPr(removeUser);
11041                    } else {
11042                        // We need to set it back to 'installed' so the uninstall
11043                        // broadcasts will be sent correctly.
11044                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11045                        ps.setInstalled(true, user.getIdentifier());
11046                    }
11047                } else {
11048                    // This is a system app, so we assume that the
11049                    // other users still have this package installed, so all
11050                    // we need to do is clear this user's data and save that
11051                    // it is uninstalled.
11052                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11053                    removeUser = user.getIdentifier();
11054                    appId = ps.appId;
11055                    mSettings.writePackageRestrictionsLPr(removeUser);
11056                }
11057            }
11058        }
11059
11060        if (removeUser >= 0) {
11061            // From above, we determined that we are deleting this only
11062            // for a single user.  Continue the work here.
11063            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11064            if (outInfo != null) {
11065                outInfo.removedPackage = packageName;
11066                outInfo.removedAppId = appId;
11067                outInfo.removedUsers = new int[] {removeUser};
11068            }
11069            mInstaller.clearUserData(packageName, removeUser);
11070            removeKeystoreDataIfNeeded(removeUser, appId);
11071            schedulePackageCleaning(packageName, removeUser, false);
11072            return true;
11073        }
11074
11075        if (dataOnly) {
11076            // Delete application data first
11077            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11078            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11079            return true;
11080        }
11081
11082        boolean ret = false;
11083        if (isSystemApp(ps)) {
11084            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11085            // When an updated system application is deleted we delete the existing resources as well and
11086            // fall back to existing code in system partition
11087            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11088                    flags, outInfo, writeSettings);
11089        } else {
11090            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11091            // Kill application pre-emptively especially for apps on sd.
11092            killApplication(packageName, ps.appId, "uninstall pkg");
11093            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11094                    allUserHandles, perUserInstalled,
11095                    outInfo, writeSettings);
11096        }
11097
11098        return ret;
11099    }
11100
11101    private final class ClearStorageConnection implements ServiceConnection {
11102        IMediaContainerService mContainerService;
11103
11104        @Override
11105        public void onServiceConnected(ComponentName name, IBinder service) {
11106            synchronized (this) {
11107                mContainerService = IMediaContainerService.Stub.asInterface(service);
11108                notifyAll();
11109            }
11110        }
11111
11112        @Override
11113        public void onServiceDisconnected(ComponentName name) {
11114        }
11115    }
11116
11117    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11118        final boolean mounted;
11119        if (Environment.isExternalStorageEmulated()) {
11120            mounted = true;
11121        } else {
11122            final String status = Environment.getExternalStorageState();
11123
11124            mounted = status.equals(Environment.MEDIA_MOUNTED)
11125                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11126        }
11127
11128        if (!mounted) {
11129            return;
11130        }
11131
11132        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11133        int[] users;
11134        if (userId == UserHandle.USER_ALL) {
11135            users = sUserManager.getUserIds();
11136        } else {
11137            users = new int[] { userId };
11138        }
11139        final ClearStorageConnection conn = new ClearStorageConnection();
11140        if (mContext.bindServiceAsUser(
11141                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11142            try {
11143                for (int curUser : users) {
11144                    long timeout = SystemClock.uptimeMillis() + 5000;
11145                    synchronized (conn) {
11146                        long now = SystemClock.uptimeMillis();
11147                        while (conn.mContainerService == null && now < timeout) {
11148                            try {
11149                                conn.wait(timeout - now);
11150                            } catch (InterruptedException e) {
11151                            }
11152                        }
11153                    }
11154                    if (conn.mContainerService == null) {
11155                        return;
11156                    }
11157
11158                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11159                    clearDirectory(conn.mContainerService,
11160                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11161                    if (allData) {
11162                        clearDirectory(conn.mContainerService,
11163                                userEnv.buildExternalStorageAppDataDirs(packageName));
11164                        clearDirectory(conn.mContainerService,
11165                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11166                    }
11167                }
11168            } finally {
11169                mContext.unbindService(conn);
11170            }
11171        }
11172    }
11173
11174    @Override
11175    public void clearApplicationUserData(final String packageName,
11176            final IPackageDataObserver observer, final int userId) {
11177        mContext.enforceCallingOrSelfPermission(
11178                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11179        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11180        // Queue up an async operation since the package deletion may take a little while.
11181        mHandler.post(new Runnable() {
11182            public void run() {
11183                mHandler.removeCallbacks(this);
11184                final boolean succeeded;
11185                synchronized (mInstallLock) {
11186                    succeeded = clearApplicationUserDataLI(packageName, userId);
11187                }
11188                clearExternalStorageDataSync(packageName, userId, true);
11189                if (succeeded) {
11190                    // invoke DeviceStorageMonitor's update method to clear any notifications
11191                    DeviceStorageMonitorInternal
11192                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11193                    if (dsm != null) {
11194                        dsm.checkMemory();
11195                    }
11196                }
11197                if(observer != null) {
11198                    try {
11199                        observer.onRemoveCompleted(packageName, succeeded);
11200                    } catch (RemoteException e) {
11201                        Log.i(TAG, "Observer no longer exists.");
11202                    }
11203                } //end if observer
11204            } //end run
11205        });
11206    }
11207
11208    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11209        if (packageName == null) {
11210            Slog.w(TAG, "Attempt to delete null packageName.");
11211            return false;
11212        }
11213
11214        // Try finding details about the requested package
11215        PackageParser.Package pkg;
11216        synchronized (mPackages) {
11217            pkg = mPackages.get(packageName);
11218            if (pkg == null) {
11219                final PackageSetting ps = mSettings.mPackages.get(packageName);
11220                if (ps != null) {
11221                    pkg = ps.pkg;
11222                }
11223            }
11224        }
11225
11226        if (pkg == null) {
11227            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11228        }
11229
11230        // Always delete data directories for package, even if we found no other
11231        // record of app. This helps users recover from UID mismatches without
11232        // resorting to a full data wipe.
11233        int retCode = mInstaller.clearUserData(packageName, userId);
11234        if (retCode < 0) {
11235            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11236            return false;
11237        }
11238
11239        if (pkg == null) {
11240            return false;
11241        }
11242
11243        if (pkg != null && pkg.applicationInfo != null) {
11244            final int appId = pkg.applicationInfo.uid;
11245            removeKeystoreDataIfNeeded(userId, appId);
11246        }
11247
11248        // Create a native library symlink only if we have native libraries
11249        // and if the native libraries are 32 bit libraries. We do not provide
11250        // this symlink for 64 bit libraries.
11251        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11252                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11253            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11254            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11255                Slog.w(TAG, "Failed linking native library dir");
11256                return false;
11257            }
11258        }
11259
11260        return true;
11261    }
11262
11263    /**
11264     * Remove entries from the keystore daemon. Will only remove it if the
11265     * {@code appId} is valid.
11266     */
11267    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11268        if (appId < 0) {
11269            return;
11270        }
11271
11272        final KeyStore keyStore = KeyStore.getInstance();
11273        if (keyStore != null) {
11274            if (userId == UserHandle.USER_ALL) {
11275                for (final int individual : sUserManager.getUserIds()) {
11276                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11277                }
11278            } else {
11279                keyStore.clearUid(UserHandle.getUid(userId, appId));
11280            }
11281        } else {
11282            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11283        }
11284    }
11285
11286    @Override
11287    public void deleteApplicationCacheFiles(final String packageName,
11288            final IPackageDataObserver observer) {
11289        mContext.enforceCallingOrSelfPermission(
11290                android.Manifest.permission.DELETE_CACHE_FILES, null);
11291        // Queue up an async operation since the package deletion may take a little while.
11292        final int userId = UserHandle.getCallingUserId();
11293        mHandler.post(new Runnable() {
11294            public void run() {
11295                mHandler.removeCallbacks(this);
11296                final boolean succeded;
11297                synchronized (mInstallLock) {
11298                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11299                }
11300                clearExternalStorageDataSync(packageName, userId, false);
11301                if(observer != null) {
11302                    try {
11303                        observer.onRemoveCompleted(packageName, succeded);
11304                    } catch (RemoteException e) {
11305                        Log.i(TAG, "Observer no longer exists.");
11306                    }
11307                } //end if observer
11308            } //end run
11309        });
11310    }
11311
11312    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11313        if (packageName == null) {
11314            Slog.w(TAG, "Attempt to delete null packageName.");
11315            return false;
11316        }
11317        PackageParser.Package p;
11318        synchronized (mPackages) {
11319            p = mPackages.get(packageName);
11320        }
11321        if (p == null) {
11322            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11323            return false;
11324        }
11325        final ApplicationInfo applicationInfo = p.applicationInfo;
11326        if (applicationInfo == null) {
11327            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11328            return false;
11329        }
11330        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11331        if (retCode < 0) {
11332            Slog.w(TAG, "Couldn't remove cache files for package: "
11333                       + packageName + " u" + userId);
11334            return false;
11335        }
11336        return true;
11337    }
11338
11339    @Override
11340    public void getPackageSizeInfo(final String packageName, int userHandle,
11341            final IPackageStatsObserver observer) {
11342        mContext.enforceCallingOrSelfPermission(
11343                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11344        if (packageName == null) {
11345            throw new IllegalArgumentException("Attempt to get size of null packageName");
11346        }
11347
11348        PackageStats stats = new PackageStats(packageName, userHandle);
11349
11350        /*
11351         * Queue up an async operation since the package measurement may take a
11352         * little while.
11353         */
11354        Message msg = mHandler.obtainMessage(INIT_COPY);
11355        msg.obj = new MeasureParams(stats, observer);
11356        mHandler.sendMessage(msg);
11357    }
11358
11359    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11360            PackageStats pStats) {
11361        if (packageName == null) {
11362            Slog.w(TAG, "Attempt to get size of null packageName.");
11363            return false;
11364        }
11365        PackageParser.Package p;
11366        boolean dataOnly = false;
11367        String libDirRoot = null;
11368        String asecPath = null;
11369        PackageSetting ps = null;
11370        synchronized (mPackages) {
11371            p = mPackages.get(packageName);
11372            ps = mSettings.mPackages.get(packageName);
11373            if(p == null) {
11374                dataOnly = true;
11375                if((ps == null) || (ps.pkg == null)) {
11376                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11377                    return false;
11378                }
11379                p = ps.pkg;
11380            }
11381            if (ps != null) {
11382                libDirRoot = ps.legacyNativeLibraryPathString;
11383            }
11384            if (p != null && (isExternal(p) || p.isForwardLocked())) {
11385                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11386                if (secureContainerId != null) {
11387                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11388                }
11389            }
11390        }
11391        String publicSrcDir = null;
11392        if(!dataOnly) {
11393            final ApplicationInfo applicationInfo = p.applicationInfo;
11394            if (applicationInfo == null) {
11395                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11396                return false;
11397            }
11398            if (p.isForwardLocked()) {
11399                publicSrcDir = applicationInfo.getBaseResourcePath();
11400            }
11401        }
11402        // TODO: extend to measure size of split APKs
11403        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11404        // not just the first level.
11405        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11406        // just the primary.
11407        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11408        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11409                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11410        if (res < 0) {
11411            return false;
11412        }
11413
11414        // Fix-up for forward-locked applications in ASEC containers.
11415        if (!isExternal(p)) {
11416            pStats.codeSize += pStats.externalCodeSize;
11417            pStats.externalCodeSize = 0L;
11418        }
11419
11420        return true;
11421    }
11422
11423
11424    @Override
11425    public void addPackageToPreferred(String packageName) {
11426        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11427    }
11428
11429    @Override
11430    public void removePackageFromPreferred(String packageName) {
11431        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11432    }
11433
11434    @Override
11435    public List<PackageInfo> getPreferredPackages(int flags) {
11436        return new ArrayList<PackageInfo>();
11437    }
11438
11439    private int getUidTargetSdkVersionLockedLPr(int uid) {
11440        Object obj = mSettings.getUserIdLPr(uid);
11441        if (obj instanceof SharedUserSetting) {
11442            final SharedUserSetting sus = (SharedUserSetting) obj;
11443            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11444            final Iterator<PackageSetting> it = sus.packages.iterator();
11445            while (it.hasNext()) {
11446                final PackageSetting ps = it.next();
11447                if (ps.pkg != null) {
11448                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11449                    if (v < vers) vers = v;
11450                }
11451            }
11452            return vers;
11453        } else if (obj instanceof PackageSetting) {
11454            final PackageSetting ps = (PackageSetting) obj;
11455            if (ps.pkg != null) {
11456                return ps.pkg.applicationInfo.targetSdkVersion;
11457            }
11458        }
11459        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11460    }
11461
11462    @Override
11463    public void addPreferredActivity(IntentFilter filter, int match,
11464            ComponentName[] set, ComponentName activity, int userId) {
11465        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11466                "Adding preferred");
11467    }
11468
11469    private void addPreferredActivityInternal(IntentFilter filter, int match,
11470            ComponentName[] set, ComponentName activity, boolean always, int userId,
11471            String opname) {
11472        // writer
11473        int callingUid = Binder.getCallingUid();
11474        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11475        if (filter.countActions() == 0) {
11476            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11477            return;
11478        }
11479        synchronized (mPackages) {
11480            if (mContext.checkCallingOrSelfPermission(
11481                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11482                    != PackageManager.PERMISSION_GRANTED) {
11483                if (getUidTargetSdkVersionLockedLPr(callingUid)
11484                        < Build.VERSION_CODES.FROYO) {
11485                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11486                            + callingUid);
11487                    return;
11488                }
11489                mContext.enforceCallingOrSelfPermission(
11490                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11491            }
11492
11493            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11494            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11495                    + userId + ":");
11496            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11497            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11498            scheduleWritePackageRestrictionsLocked(userId);
11499        }
11500    }
11501
11502    @Override
11503    public void replacePreferredActivity(IntentFilter filter, int match,
11504            ComponentName[] set, ComponentName activity, int userId) {
11505        if (filter.countActions() != 1) {
11506            throw new IllegalArgumentException(
11507                    "replacePreferredActivity expects filter to have only 1 action.");
11508        }
11509        if (filter.countDataAuthorities() != 0
11510                || filter.countDataPaths() != 0
11511                || filter.countDataSchemes() > 1
11512                || filter.countDataTypes() != 0) {
11513            throw new IllegalArgumentException(
11514                    "replacePreferredActivity expects filter to have no data authorities, " +
11515                    "paths, or types; and at most one scheme.");
11516        }
11517
11518        final int callingUid = Binder.getCallingUid();
11519        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11520        synchronized (mPackages) {
11521            if (mContext.checkCallingOrSelfPermission(
11522                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11523                    != PackageManager.PERMISSION_GRANTED) {
11524                if (getUidTargetSdkVersionLockedLPr(callingUid)
11525                        < Build.VERSION_CODES.FROYO) {
11526                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11527                            + Binder.getCallingUid());
11528                    return;
11529                }
11530                mContext.enforceCallingOrSelfPermission(
11531                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11532            }
11533
11534            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11535            if (pir != null) {
11536                // Get all of the existing entries that exactly match this filter.
11537                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11538                if (existing != null && existing.size() == 1) {
11539                    PreferredActivity cur = existing.get(0);
11540                    if (DEBUG_PREFERRED) {
11541                        Slog.i(TAG, "Checking replace of preferred:");
11542                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11543                        if (!cur.mPref.mAlways) {
11544                            Slog.i(TAG, "  -- CUR; not mAlways!");
11545                        } else {
11546                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11547                            Slog.i(TAG, "  -- CUR: mSet="
11548                                    + Arrays.toString(cur.mPref.mSetComponents));
11549                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11550                            Slog.i(TAG, "  -- NEW: mMatch="
11551                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11552                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11553                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11554                        }
11555                    }
11556                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11557                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11558                            && cur.mPref.sameSet(set)) {
11559                        // Setting the preferred activity to what it happens to be already
11560                        if (DEBUG_PREFERRED) {
11561                            Slog.i(TAG, "Replacing with same preferred activity "
11562                                    + cur.mPref.mShortComponent + " for user "
11563                                    + userId + ":");
11564                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11565                        }
11566                        return;
11567                    }
11568                }
11569
11570                if (existing != null) {
11571                    if (DEBUG_PREFERRED) {
11572                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11573                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11574                    }
11575                    for (int i = 0; i < existing.size(); i++) {
11576                        PreferredActivity pa = existing.get(i);
11577                        if (DEBUG_PREFERRED) {
11578                            Slog.i(TAG, "Removing existing preferred activity "
11579                                    + pa.mPref.mComponent + ":");
11580                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11581                        }
11582                        pir.removeFilter(pa);
11583                    }
11584                }
11585            }
11586            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11587                    "Replacing preferred");
11588        }
11589    }
11590
11591    @Override
11592    public void clearPackagePreferredActivities(String packageName) {
11593        final int uid = Binder.getCallingUid();
11594        // writer
11595        synchronized (mPackages) {
11596            PackageParser.Package pkg = mPackages.get(packageName);
11597            if (pkg == null || pkg.applicationInfo.uid != uid) {
11598                if (mContext.checkCallingOrSelfPermission(
11599                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11600                        != PackageManager.PERMISSION_GRANTED) {
11601                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11602                            < Build.VERSION_CODES.FROYO) {
11603                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11604                                + Binder.getCallingUid());
11605                        return;
11606                    }
11607                    mContext.enforceCallingOrSelfPermission(
11608                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11609                }
11610            }
11611
11612            int user = UserHandle.getCallingUserId();
11613            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11614                scheduleWritePackageRestrictionsLocked(user);
11615            }
11616        }
11617    }
11618
11619    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11620    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11621        ArrayList<PreferredActivity> removed = null;
11622        boolean changed = false;
11623        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11624            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11625            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11626            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11627                continue;
11628            }
11629            Iterator<PreferredActivity> it = pir.filterIterator();
11630            while (it.hasNext()) {
11631                PreferredActivity pa = it.next();
11632                // Mark entry for removal only if it matches the package name
11633                // and the entry is of type "always".
11634                if (packageName == null ||
11635                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11636                                && pa.mPref.mAlways)) {
11637                    if (removed == null) {
11638                        removed = new ArrayList<PreferredActivity>();
11639                    }
11640                    removed.add(pa);
11641                }
11642            }
11643            if (removed != null) {
11644                for (int j=0; j<removed.size(); j++) {
11645                    PreferredActivity pa = removed.get(j);
11646                    pir.removeFilter(pa);
11647                }
11648                changed = true;
11649            }
11650        }
11651        return changed;
11652    }
11653
11654    @Override
11655    public void resetPreferredActivities(int userId) {
11656        /* TODO: Actually use userId. Why is it being passed in? */
11657        mContext.enforceCallingOrSelfPermission(
11658                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11659        // writer
11660        synchronized (mPackages) {
11661            int user = UserHandle.getCallingUserId();
11662            clearPackagePreferredActivitiesLPw(null, user);
11663            mSettings.readDefaultPreferredAppsLPw(this, user);
11664            scheduleWritePackageRestrictionsLocked(user);
11665        }
11666    }
11667
11668    @Override
11669    public int getPreferredActivities(List<IntentFilter> outFilters,
11670            List<ComponentName> outActivities, String packageName) {
11671
11672        int num = 0;
11673        final int userId = UserHandle.getCallingUserId();
11674        // reader
11675        synchronized (mPackages) {
11676            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11677            if (pir != null) {
11678                final Iterator<PreferredActivity> it = pir.filterIterator();
11679                while (it.hasNext()) {
11680                    final PreferredActivity pa = it.next();
11681                    if (packageName == null
11682                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11683                                    && pa.mPref.mAlways)) {
11684                        if (outFilters != null) {
11685                            outFilters.add(new IntentFilter(pa));
11686                        }
11687                        if (outActivities != null) {
11688                            outActivities.add(pa.mPref.mComponent);
11689                        }
11690                    }
11691                }
11692            }
11693        }
11694
11695        return num;
11696    }
11697
11698    @Override
11699    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11700            int userId) {
11701        int callingUid = Binder.getCallingUid();
11702        if (callingUid != Process.SYSTEM_UID) {
11703            throw new SecurityException(
11704                    "addPersistentPreferredActivity can only be run by the system");
11705        }
11706        if (filter.countActions() == 0) {
11707            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11708            return;
11709        }
11710        synchronized (mPackages) {
11711            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11712                    " :");
11713            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11714            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11715                    new PersistentPreferredActivity(filter, activity));
11716            scheduleWritePackageRestrictionsLocked(userId);
11717        }
11718    }
11719
11720    @Override
11721    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11722        int callingUid = Binder.getCallingUid();
11723        if (callingUid != Process.SYSTEM_UID) {
11724            throw new SecurityException(
11725                    "clearPackagePersistentPreferredActivities can only be run by the system");
11726        }
11727        ArrayList<PersistentPreferredActivity> removed = null;
11728        boolean changed = false;
11729        synchronized (mPackages) {
11730            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11731                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11732                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11733                        .valueAt(i);
11734                if (userId != thisUserId) {
11735                    continue;
11736                }
11737                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11738                while (it.hasNext()) {
11739                    PersistentPreferredActivity ppa = it.next();
11740                    // Mark entry for removal only if it matches the package name.
11741                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11742                        if (removed == null) {
11743                            removed = new ArrayList<PersistentPreferredActivity>();
11744                        }
11745                        removed.add(ppa);
11746                    }
11747                }
11748                if (removed != null) {
11749                    for (int j=0; j<removed.size(); j++) {
11750                        PersistentPreferredActivity ppa = removed.get(j);
11751                        ppir.removeFilter(ppa);
11752                    }
11753                    changed = true;
11754                }
11755            }
11756
11757            if (changed) {
11758                scheduleWritePackageRestrictionsLocked(userId);
11759            }
11760        }
11761    }
11762
11763    @Override
11764    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11765            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11766        mContext.enforceCallingOrSelfPermission(
11767                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11768        int callingUid = Binder.getCallingUid();
11769        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11770        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11771        if (intentFilter.countActions() == 0) {
11772            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11773            return;
11774        }
11775        synchronized (mPackages) {
11776            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
11777                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11778            CrossProfileIntentResolver resolver =
11779                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11780            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
11781            // We have all those whose filter is equal. Now checking if the rest is equal as well.
11782            if (existing != null) {
11783                int size = existing.size();
11784                for (int i = 0; i < size; i++) {
11785                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
11786                        return;
11787                    }
11788                }
11789            }
11790            resolver.addFilter(newFilter);
11791            scheduleWritePackageRestrictionsLocked(sourceUserId);
11792        }
11793    }
11794
11795    @Override
11796    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11797            int ownerUserId) {
11798        mContext.enforceCallingOrSelfPermission(
11799                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11800        int callingUid = Binder.getCallingUid();
11801        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11802        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11803        int callingUserId = UserHandle.getUserId(callingUid);
11804        synchronized (mPackages) {
11805            CrossProfileIntentResolver resolver =
11806                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11807            ArraySet<CrossProfileIntentFilter> set =
11808                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
11809            for (CrossProfileIntentFilter filter : set) {
11810                if (filter.getOwnerPackage().equals(ownerPackage)
11811                        && filter.getOwnerUserId() == callingUserId) {
11812                    resolver.removeFilter(filter);
11813                }
11814            }
11815            scheduleWritePackageRestrictionsLocked(sourceUserId);
11816        }
11817    }
11818
11819    // Enforcing that callingUid is owning pkg on userId
11820    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11821        // The system owns everything.
11822        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11823            return;
11824        }
11825        int callingUserId = UserHandle.getUserId(callingUid);
11826        if (callingUserId != userId) {
11827            throw new SecurityException("calling uid " + callingUid
11828                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11829                    + callingUserId);
11830        }
11831        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11832        if (pi == null) {
11833            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11834                    + callingUserId);
11835        }
11836        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11837            throw new SecurityException("Calling uid " + callingUid
11838                    + " does not own package " + pkg);
11839        }
11840    }
11841
11842    @Override
11843    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11844        Intent intent = new Intent(Intent.ACTION_MAIN);
11845        intent.addCategory(Intent.CATEGORY_HOME);
11846
11847        final int callingUserId = UserHandle.getCallingUserId();
11848        List<ResolveInfo> list = queryIntentActivities(intent, null,
11849                PackageManager.GET_META_DATA, callingUserId);
11850        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11851                true, false, false, callingUserId);
11852
11853        allHomeCandidates.clear();
11854        if (list != null) {
11855            for (ResolveInfo ri : list) {
11856                allHomeCandidates.add(ri);
11857            }
11858        }
11859        return (preferred == null || preferred.activityInfo == null)
11860                ? null
11861                : new ComponentName(preferred.activityInfo.packageName,
11862                        preferred.activityInfo.name);
11863    }
11864
11865    @Override
11866    public void setApplicationEnabledSetting(String appPackageName,
11867            int newState, int flags, int userId, String callingPackage) {
11868        if (!sUserManager.exists(userId)) return;
11869        if (callingPackage == null) {
11870            callingPackage = Integer.toString(Binder.getCallingUid());
11871        }
11872        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11873    }
11874
11875    @Override
11876    public void setComponentEnabledSetting(ComponentName componentName,
11877            int newState, int flags, int userId) {
11878        if (!sUserManager.exists(userId)) return;
11879        setEnabledSetting(componentName.getPackageName(),
11880                componentName.getClassName(), newState, flags, userId, null);
11881    }
11882
11883    private void setEnabledSetting(final String packageName, String className, int newState,
11884            final int flags, int userId, String callingPackage) {
11885        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11886              || newState == COMPONENT_ENABLED_STATE_ENABLED
11887              || newState == COMPONENT_ENABLED_STATE_DISABLED
11888              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11889              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11890            throw new IllegalArgumentException("Invalid new component state: "
11891                    + newState);
11892        }
11893        PackageSetting pkgSetting;
11894        final int uid = Binder.getCallingUid();
11895        final int permission = mContext.checkCallingOrSelfPermission(
11896                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11897        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
11898        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11899        boolean sendNow = false;
11900        boolean isApp = (className == null);
11901        String componentName = isApp ? packageName : className;
11902        int packageUid = -1;
11903        ArrayList<String> components;
11904
11905        // writer
11906        synchronized (mPackages) {
11907            pkgSetting = mSettings.mPackages.get(packageName);
11908            if (pkgSetting == null) {
11909                if (className == null) {
11910                    throw new IllegalArgumentException(
11911                            "Unknown package: " + packageName);
11912                }
11913                throw new IllegalArgumentException(
11914                        "Unknown component: " + packageName
11915                        + "/" + className);
11916            }
11917            // Allow root and verify that userId is not being specified by a different user
11918            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11919                throw new SecurityException(
11920                        "Permission Denial: attempt to change component state from pid="
11921                        + Binder.getCallingPid()
11922                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11923            }
11924            if (className == null) {
11925                // We're dealing with an application/package level state change
11926                if (pkgSetting.getEnabled(userId) == newState) {
11927                    // Nothing to do
11928                    return;
11929                }
11930                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11931                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11932                    // Don't care about who enables an app.
11933                    callingPackage = null;
11934                }
11935                pkgSetting.setEnabled(newState, userId, callingPackage);
11936                // pkgSetting.pkg.mSetEnabled = newState;
11937            } else {
11938                // We're dealing with a component level state change
11939                // First, verify that this is a valid class name.
11940                PackageParser.Package pkg = pkgSetting.pkg;
11941                if (pkg == null || !pkg.hasComponentClassName(className)) {
11942                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11943                        throw new IllegalArgumentException("Component class " + className
11944                                + " does not exist in " + packageName);
11945                    } else {
11946                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11947                                + className + " does not exist in " + packageName);
11948                    }
11949                }
11950                switch (newState) {
11951                case COMPONENT_ENABLED_STATE_ENABLED:
11952                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11953                        return;
11954                    }
11955                    break;
11956                case COMPONENT_ENABLED_STATE_DISABLED:
11957                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11958                        return;
11959                    }
11960                    break;
11961                case COMPONENT_ENABLED_STATE_DEFAULT:
11962                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11963                        return;
11964                    }
11965                    break;
11966                default:
11967                    Slog.e(TAG, "Invalid new component state: " + newState);
11968                    return;
11969                }
11970            }
11971            mSettings.writePackageRestrictionsLPr(userId);
11972            components = mPendingBroadcasts.get(userId, packageName);
11973            final boolean newPackage = components == null;
11974            if (newPackage) {
11975                components = new ArrayList<String>();
11976            }
11977            if (!components.contains(componentName)) {
11978                components.add(componentName);
11979            }
11980            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11981                sendNow = true;
11982                // Purge entry from pending broadcast list if another one exists already
11983                // since we are sending one right away.
11984                mPendingBroadcasts.remove(userId, packageName);
11985            } else {
11986                if (newPackage) {
11987                    mPendingBroadcasts.put(userId, packageName, components);
11988                }
11989                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11990                    // Schedule a message
11991                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11992                }
11993            }
11994        }
11995
11996        long callingId = Binder.clearCallingIdentity();
11997        try {
11998            if (sendNow) {
11999                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12000                sendPackageChangedBroadcast(packageName,
12001                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12002            }
12003        } finally {
12004            Binder.restoreCallingIdentity(callingId);
12005        }
12006    }
12007
12008    private void sendPackageChangedBroadcast(String packageName,
12009            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12010        if (DEBUG_INSTALL)
12011            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12012                    + componentNames);
12013        Bundle extras = new Bundle(4);
12014        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12015        String nameList[] = new String[componentNames.size()];
12016        componentNames.toArray(nameList);
12017        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12018        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12019        extras.putInt(Intent.EXTRA_UID, packageUid);
12020        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12021                new int[] {UserHandle.getUserId(packageUid)});
12022    }
12023
12024    @Override
12025    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12026        if (!sUserManager.exists(userId)) return;
12027        final int uid = Binder.getCallingUid();
12028        final int permission = mContext.checkCallingOrSelfPermission(
12029                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12030        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12031        enforceCrossUserPermission(uid, userId, true, true, "stop package");
12032        // writer
12033        synchronized (mPackages) {
12034            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12035                    uid, userId)) {
12036                scheduleWritePackageRestrictionsLocked(userId);
12037            }
12038        }
12039    }
12040
12041    @Override
12042    public String getInstallerPackageName(String packageName) {
12043        // reader
12044        synchronized (mPackages) {
12045            return mSettings.getInstallerPackageNameLPr(packageName);
12046        }
12047    }
12048
12049    @Override
12050    public int getApplicationEnabledSetting(String packageName, int userId) {
12051        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12052        int uid = Binder.getCallingUid();
12053        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
12054        // reader
12055        synchronized (mPackages) {
12056            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12057        }
12058    }
12059
12060    @Override
12061    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12062        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12063        int uid = Binder.getCallingUid();
12064        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
12065        // reader
12066        synchronized (mPackages) {
12067            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12068        }
12069    }
12070
12071    @Override
12072    public void enterSafeMode() {
12073        enforceSystemOrRoot("Only the system can request entering safe mode");
12074
12075        if (!mSystemReady) {
12076            mSafeMode = true;
12077        }
12078    }
12079
12080    @Override
12081    public void systemReady() {
12082        mSystemReady = true;
12083
12084        // Read the compatibilty setting when the system is ready.
12085        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12086                mContext.getContentResolver(),
12087                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12088        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12089        if (DEBUG_SETTINGS) {
12090            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12091        }
12092
12093        synchronized (mPackages) {
12094            // Verify that all of the preferred activity components actually
12095            // exist.  It is possible for applications to be updated and at
12096            // that point remove a previously declared activity component that
12097            // had been set as a preferred activity.  We try to clean this up
12098            // the next time we encounter that preferred activity, but it is
12099            // possible for the user flow to never be able to return to that
12100            // situation so here we do a sanity check to make sure we haven't
12101            // left any junk around.
12102            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12103            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12104                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12105                removed.clear();
12106                for (PreferredActivity pa : pir.filterSet()) {
12107                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12108                        removed.add(pa);
12109                    }
12110                }
12111                if (removed.size() > 0) {
12112                    for (int r=0; r<removed.size(); r++) {
12113                        PreferredActivity pa = removed.get(r);
12114                        Slog.w(TAG, "Removing dangling preferred activity: "
12115                                + pa.mPref.mComponent);
12116                        pir.removeFilter(pa);
12117                    }
12118                    mSettings.writePackageRestrictionsLPr(
12119                            mSettings.mPreferredActivities.keyAt(i));
12120                }
12121            }
12122        }
12123        sUserManager.systemReady();
12124
12125        // Kick off any messages waiting for system ready
12126        if (mPostSystemReadyMessages != null) {
12127            for (Message msg : mPostSystemReadyMessages) {
12128                msg.sendToTarget();
12129            }
12130            mPostSystemReadyMessages = null;
12131        }
12132    }
12133
12134    @Override
12135    public boolean isSafeMode() {
12136        return mSafeMode;
12137    }
12138
12139    @Override
12140    public boolean hasSystemUidErrors() {
12141        return mHasSystemUidErrors;
12142    }
12143
12144    static String arrayToString(int[] array) {
12145        StringBuffer buf = new StringBuffer(128);
12146        buf.append('[');
12147        if (array != null) {
12148            for (int i=0; i<array.length; i++) {
12149                if (i > 0) buf.append(", ");
12150                buf.append(array[i]);
12151            }
12152        }
12153        buf.append(']');
12154        return buf.toString();
12155    }
12156
12157    static class DumpState {
12158        public static final int DUMP_LIBS = 1 << 0;
12159        public static final int DUMP_FEATURES = 1 << 1;
12160        public static final int DUMP_RESOLVERS = 1 << 2;
12161        public static final int DUMP_PERMISSIONS = 1 << 3;
12162        public static final int DUMP_PACKAGES = 1 << 4;
12163        public static final int DUMP_SHARED_USERS = 1 << 5;
12164        public static final int DUMP_MESSAGES = 1 << 6;
12165        public static final int DUMP_PROVIDERS = 1 << 7;
12166        public static final int DUMP_VERIFIERS = 1 << 8;
12167        public static final int DUMP_PREFERRED = 1 << 9;
12168        public static final int DUMP_PREFERRED_XML = 1 << 10;
12169        public static final int DUMP_KEYSETS = 1 << 11;
12170        public static final int DUMP_VERSION = 1 << 12;
12171        public static final int DUMP_INSTALLS = 1 << 13;
12172
12173        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12174
12175        private int mTypes;
12176
12177        private int mOptions;
12178
12179        private boolean mTitlePrinted;
12180
12181        private SharedUserSetting mSharedUser;
12182
12183        public boolean isDumping(int type) {
12184            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12185                return true;
12186            }
12187
12188            return (mTypes & type) != 0;
12189        }
12190
12191        public void setDump(int type) {
12192            mTypes |= type;
12193        }
12194
12195        public boolean isOptionEnabled(int option) {
12196            return (mOptions & option) != 0;
12197        }
12198
12199        public void setOptionEnabled(int option) {
12200            mOptions |= option;
12201        }
12202
12203        public boolean onTitlePrinted() {
12204            final boolean printed = mTitlePrinted;
12205            mTitlePrinted = true;
12206            return printed;
12207        }
12208
12209        public boolean getTitlePrinted() {
12210            return mTitlePrinted;
12211        }
12212
12213        public void setTitlePrinted(boolean enabled) {
12214            mTitlePrinted = enabled;
12215        }
12216
12217        public SharedUserSetting getSharedUser() {
12218            return mSharedUser;
12219        }
12220
12221        public void setSharedUser(SharedUserSetting user) {
12222            mSharedUser = user;
12223        }
12224    }
12225
12226    @Override
12227    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12228        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12229                != PackageManager.PERMISSION_GRANTED) {
12230            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12231                    + Binder.getCallingPid()
12232                    + ", uid=" + Binder.getCallingUid()
12233                    + " without permission "
12234                    + android.Manifest.permission.DUMP);
12235            return;
12236        }
12237
12238        DumpState dumpState = new DumpState();
12239        boolean fullPreferred = false;
12240        boolean checkin = false;
12241
12242        String packageName = null;
12243
12244        int opti = 0;
12245        while (opti < args.length) {
12246            String opt = args[opti];
12247            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12248                break;
12249            }
12250            opti++;
12251
12252            if ("-a".equals(opt)) {
12253                // Right now we only know how to print all.
12254            } else if ("-h".equals(opt)) {
12255                pw.println("Package manager dump options:");
12256                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12257                pw.println("    --checkin: dump for a checkin");
12258                pw.println("    -f: print details of intent filters");
12259                pw.println("    -h: print this help");
12260                pw.println("  cmd may be one of:");
12261                pw.println("    l[ibraries]: list known shared libraries");
12262                pw.println("    f[ibraries]: list device features");
12263                pw.println("    k[eysets]: print known keysets");
12264                pw.println("    r[esolvers]: dump intent resolvers");
12265                pw.println("    perm[issions]: dump permissions");
12266                pw.println("    pref[erred]: print preferred package settings");
12267                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12268                pw.println("    prov[iders]: dump content providers");
12269                pw.println("    p[ackages]: dump installed packages");
12270                pw.println("    s[hared-users]: dump shared user IDs");
12271                pw.println("    m[essages]: print collected runtime messages");
12272                pw.println("    v[erifiers]: print package verifier info");
12273                pw.println("    version: print database version info");
12274                pw.println("    write: write current settings now");
12275                pw.println("    <package.name>: info about given package");
12276                pw.println("    installs: details about install sessions");
12277                return;
12278            } else if ("--checkin".equals(opt)) {
12279                checkin = true;
12280            } else if ("-f".equals(opt)) {
12281                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12282            } else {
12283                pw.println("Unknown argument: " + opt + "; use -h for help");
12284            }
12285        }
12286
12287        // Is the caller requesting to dump a particular piece of data?
12288        if (opti < args.length) {
12289            String cmd = args[opti];
12290            opti++;
12291            // Is this a package name?
12292            if ("android".equals(cmd) || cmd.contains(".")) {
12293                packageName = cmd;
12294                // When dumping a single package, we always dump all of its
12295                // filter information since the amount of data will be reasonable.
12296                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12297            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12298                dumpState.setDump(DumpState.DUMP_LIBS);
12299            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12300                dumpState.setDump(DumpState.DUMP_FEATURES);
12301            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12302                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12303            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12304                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12305            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12306                dumpState.setDump(DumpState.DUMP_PREFERRED);
12307            } else if ("preferred-xml".equals(cmd)) {
12308                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12309                if (opti < args.length && "--full".equals(args[opti])) {
12310                    fullPreferred = true;
12311                    opti++;
12312                }
12313            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12314                dumpState.setDump(DumpState.DUMP_PACKAGES);
12315            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12316                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12317            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12318                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12319            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12320                dumpState.setDump(DumpState.DUMP_MESSAGES);
12321            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12322                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12323            } else if ("version".equals(cmd)) {
12324                dumpState.setDump(DumpState.DUMP_VERSION);
12325            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12326                dumpState.setDump(DumpState.DUMP_KEYSETS);
12327            } else if ("installs".equals(cmd)) {
12328                dumpState.setDump(DumpState.DUMP_INSTALLS);
12329            } else if ("write".equals(cmd)) {
12330                synchronized (mPackages) {
12331                    mSettings.writeLPr();
12332                    pw.println("Settings written.");
12333                    return;
12334                }
12335            }
12336        }
12337
12338        if (checkin) {
12339            pw.println("vers,1");
12340        }
12341
12342        // reader
12343        synchronized (mPackages) {
12344            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12345                if (!checkin) {
12346                    if (dumpState.onTitlePrinted())
12347                        pw.println();
12348                    pw.println("Database versions:");
12349                    pw.print("  SDK Version:");
12350                    pw.print(" internal=");
12351                    pw.print(mSettings.mInternalSdkPlatform);
12352                    pw.print(" external=");
12353                    pw.println(mSettings.mExternalSdkPlatform);
12354                    pw.print("  DB Version:");
12355                    pw.print(" internal=");
12356                    pw.print(mSettings.mInternalDatabaseVersion);
12357                    pw.print(" external=");
12358                    pw.println(mSettings.mExternalDatabaseVersion);
12359                }
12360            }
12361
12362            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12363                if (!checkin) {
12364                    if (dumpState.onTitlePrinted())
12365                        pw.println();
12366                    pw.println("Verifiers:");
12367                    pw.print("  Required: ");
12368                    pw.print(mRequiredVerifierPackage);
12369                    pw.print(" (uid=");
12370                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12371                    pw.println(")");
12372                } else if (mRequiredVerifierPackage != null) {
12373                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12374                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12375                }
12376            }
12377
12378            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12379                boolean printedHeader = false;
12380                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12381                while (it.hasNext()) {
12382                    String name = it.next();
12383                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12384                    if (!checkin) {
12385                        if (!printedHeader) {
12386                            if (dumpState.onTitlePrinted())
12387                                pw.println();
12388                            pw.println("Libraries:");
12389                            printedHeader = true;
12390                        }
12391                        pw.print("  ");
12392                    } else {
12393                        pw.print("lib,");
12394                    }
12395                    pw.print(name);
12396                    if (!checkin) {
12397                        pw.print(" -> ");
12398                    }
12399                    if (ent.path != null) {
12400                        if (!checkin) {
12401                            pw.print("(jar) ");
12402                            pw.print(ent.path);
12403                        } else {
12404                            pw.print(",jar,");
12405                            pw.print(ent.path);
12406                        }
12407                    } else {
12408                        if (!checkin) {
12409                            pw.print("(apk) ");
12410                            pw.print(ent.apk);
12411                        } else {
12412                            pw.print(",apk,");
12413                            pw.print(ent.apk);
12414                        }
12415                    }
12416                    pw.println();
12417                }
12418            }
12419
12420            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12421                if (dumpState.onTitlePrinted())
12422                    pw.println();
12423                if (!checkin) {
12424                    pw.println("Features:");
12425                }
12426                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12427                while (it.hasNext()) {
12428                    String name = it.next();
12429                    if (!checkin) {
12430                        pw.print("  ");
12431                    } else {
12432                        pw.print("feat,");
12433                    }
12434                    pw.println(name);
12435                }
12436            }
12437
12438            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12439                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12440                        : "Activity Resolver Table:", "  ", packageName,
12441                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12442                    dumpState.setTitlePrinted(true);
12443                }
12444                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12445                        : "Receiver Resolver Table:", "  ", packageName,
12446                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12447                    dumpState.setTitlePrinted(true);
12448                }
12449                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12450                        : "Service Resolver Table:", "  ", packageName,
12451                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12452                    dumpState.setTitlePrinted(true);
12453                }
12454                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12455                        : "Provider Resolver Table:", "  ", packageName,
12456                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12457                    dumpState.setTitlePrinted(true);
12458                }
12459            }
12460
12461            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12462                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12463                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12464                    int user = mSettings.mPreferredActivities.keyAt(i);
12465                    if (pir.dump(pw,
12466                            dumpState.getTitlePrinted()
12467                                ? "\nPreferred Activities User " + user + ":"
12468                                : "Preferred Activities User " + user + ":", "  ",
12469                            packageName, true, false)) {
12470                        dumpState.setTitlePrinted(true);
12471                    }
12472                }
12473            }
12474
12475            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12476                pw.flush();
12477                FileOutputStream fout = new FileOutputStream(fd);
12478                BufferedOutputStream str = new BufferedOutputStream(fout);
12479                XmlSerializer serializer = new FastXmlSerializer();
12480                try {
12481                    serializer.setOutput(str, "utf-8");
12482                    serializer.startDocument(null, true);
12483                    serializer.setFeature(
12484                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12485                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12486                    serializer.endDocument();
12487                    serializer.flush();
12488                } catch (IllegalArgumentException e) {
12489                    pw.println("Failed writing: " + e);
12490                } catch (IllegalStateException e) {
12491                    pw.println("Failed writing: " + e);
12492                } catch (IOException e) {
12493                    pw.println("Failed writing: " + e);
12494                }
12495            }
12496
12497            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12498                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12499                if (packageName == null) {
12500                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12501                        if (iperm == 0) {
12502                            if (dumpState.onTitlePrinted())
12503                                pw.println();
12504                            pw.println("AppOp Permissions:");
12505                        }
12506                        pw.print("  AppOp Permission ");
12507                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12508                        pw.println(":");
12509                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12510                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12511                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12512                        }
12513                    }
12514                }
12515            }
12516
12517            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12518                boolean printedSomething = false;
12519                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12520                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12521                        continue;
12522                    }
12523                    if (!printedSomething) {
12524                        if (dumpState.onTitlePrinted())
12525                            pw.println();
12526                        pw.println("Registered ContentProviders:");
12527                        printedSomething = true;
12528                    }
12529                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12530                    pw.print("    "); pw.println(p.toString());
12531                }
12532                printedSomething = false;
12533                for (Map.Entry<String, PackageParser.Provider> entry :
12534                        mProvidersByAuthority.entrySet()) {
12535                    PackageParser.Provider p = entry.getValue();
12536                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12537                        continue;
12538                    }
12539                    if (!printedSomething) {
12540                        if (dumpState.onTitlePrinted())
12541                            pw.println();
12542                        pw.println("ContentProvider Authorities:");
12543                        printedSomething = true;
12544                    }
12545                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12546                    pw.print("    "); pw.println(p.toString());
12547                    if (p.info != null && p.info.applicationInfo != null) {
12548                        final String appInfo = p.info.applicationInfo.toString();
12549                        pw.print("      applicationInfo="); pw.println(appInfo);
12550                    }
12551                }
12552            }
12553
12554            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12555                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12556            }
12557
12558            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12559                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12560            }
12561
12562            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12563                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
12564            }
12565
12566            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12567                // XXX should handle packageName != null by dumping only install data that
12568                // the given package is involved with.
12569                if (dumpState.onTitlePrinted()) pw.println();
12570                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12571            }
12572
12573            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12574                if (dumpState.onTitlePrinted()) pw.println();
12575                mSettings.dumpReadMessagesLPr(pw, dumpState);
12576
12577                pw.println();
12578                pw.println("Package warning messages:");
12579                BufferedReader in = null;
12580                String line = null;
12581                try {
12582                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12583                    while ((line = in.readLine()) != null) {
12584                        if (line.contains("ignored: updated version")) continue;
12585                        pw.println(line);
12586                    }
12587                } catch (IOException ignored) {
12588                } finally {
12589                    IoUtils.closeQuietly(in);
12590                }
12591            }
12592
12593            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
12594                BufferedReader in = null;
12595                String line = null;
12596                try {
12597                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12598                    while ((line = in.readLine()) != null) {
12599                        if (line.contains("ignored: updated version")) continue;
12600                        pw.print("msg,");
12601                        pw.println(line);
12602                    }
12603                } catch (IOException ignored) {
12604                } finally {
12605                    IoUtils.closeQuietly(in);
12606                }
12607            }
12608        }
12609    }
12610
12611    // ------- apps on sdcard specific code -------
12612    static final boolean DEBUG_SD_INSTALL = false;
12613
12614    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12615
12616    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12617
12618    private boolean mMediaMounted = false;
12619
12620    static String getEncryptKey() {
12621        try {
12622            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12623                    SD_ENCRYPTION_KEYSTORE_NAME);
12624            if (sdEncKey == null) {
12625                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12626                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12627                if (sdEncKey == null) {
12628                    Slog.e(TAG, "Failed to create encryption keys");
12629                    return null;
12630                }
12631            }
12632            return sdEncKey;
12633        } catch (NoSuchAlgorithmException nsae) {
12634            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12635            return null;
12636        } catch (IOException ioe) {
12637            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12638            return null;
12639        }
12640    }
12641
12642    /*
12643     * Update media status on PackageManager.
12644     */
12645    @Override
12646    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12647        int callingUid = Binder.getCallingUid();
12648        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12649            throw new SecurityException("Media status can only be updated by the system");
12650        }
12651        // reader; this apparently protects mMediaMounted, but should probably
12652        // be a different lock in that case.
12653        synchronized (mPackages) {
12654            Log.i(TAG, "Updating external media status from "
12655                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12656                    + (mediaStatus ? "mounted" : "unmounted"));
12657            if (DEBUG_SD_INSTALL)
12658                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12659                        + ", mMediaMounted=" + mMediaMounted);
12660            if (mediaStatus == mMediaMounted) {
12661                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12662                        : 0, -1);
12663                mHandler.sendMessage(msg);
12664                return;
12665            }
12666            mMediaMounted = mediaStatus;
12667        }
12668        // Queue up an async operation since the package installation may take a
12669        // little while.
12670        mHandler.post(new Runnable() {
12671            public void run() {
12672                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12673            }
12674        });
12675    }
12676
12677    /**
12678     * Called by MountService when the initial ASECs to scan are available.
12679     * Should block until all the ASEC containers are finished being scanned.
12680     */
12681    public void scanAvailableAsecs() {
12682        updateExternalMediaStatusInner(true, false, false);
12683        if (mShouldRestoreconData) {
12684            SELinuxMMAC.setRestoreconDone();
12685            mShouldRestoreconData = false;
12686        }
12687    }
12688
12689    /*
12690     * Collect information of applications on external media, map them against
12691     * existing containers and update information based on current mount status.
12692     * Please note that we always have to report status if reportStatus has been
12693     * set to true especially when unloading packages.
12694     */
12695    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12696            boolean externalStorage) {
12697        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12698        int[] uidArr = EmptyArray.INT;
12699
12700        final String[] list = PackageHelper.getSecureContainerList();
12701        if (ArrayUtils.isEmpty(list)) {
12702            Log.i(TAG, "No secure containers found");
12703        } else {
12704            // Process list of secure containers and categorize them
12705            // as active or stale based on their package internal state.
12706
12707            // reader
12708            synchronized (mPackages) {
12709                for (String cid : list) {
12710                    // Leave stages untouched for now; installer service owns them
12711                    if (PackageInstallerService.isStageName(cid)) continue;
12712
12713                    if (DEBUG_SD_INSTALL)
12714                        Log.i(TAG, "Processing container " + cid);
12715                    String pkgName = getAsecPackageName(cid);
12716                    if (pkgName == null) {
12717                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12718                        continue;
12719                    }
12720                    if (DEBUG_SD_INSTALL)
12721                        Log.i(TAG, "Looking for pkg : " + pkgName);
12722
12723                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12724                    if (ps == null) {
12725                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12726                        continue;
12727                    }
12728
12729                    /*
12730                     * Skip packages that are not external if we're unmounting
12731                     * external storage.
12732                     */
12733                    if (externalStorage && !isMounted && !isExternal(ps)) {
12734                        continue;
12735                    }
12736
12737                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12738                            getAppDexInstructionSets(ps), ps.isForwardLocked());
12739                    // The package status is changed only if the code path
12740                    // matches between settings and the container id.
12741                    if (ps.codePathString != null
12742                            && ps.codePathString.startsWith(args.getCodePath())) {
12743                        if (DEBUG_SD_INSTALL) {
12744                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12745                                    + " at code path: " + ps.codePathString);
12746                        }
12747
12748                        // We do have a valid package installed on sdcard
12749                        processCids.put(args, ps.codePathString);
12750                        final int uid = ps.appId;
12751                        if (uid != -1) {
12752                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12753                        }
12754                    } else {
12755                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12756                                + ps.codePathString);
12757                    }
12758                }
12759            }
12760
12761            Arrays.sort(uidArr);
12762        }
12763
12764        // Process packages with valid entries.
12765        if (isMounted) {
12766            if (DEBUG_SD_INSTALL)
12767                Log.i(TAG, "Loading packages");
12768            loadMediaPackages(processCids, uidArr);
12769            startCleaningPackages();
12770            mInstallerService.onSecureContainersAvailable();
12771        } else {
12772            if (DEBUG_SD_INSTALL)
12773                Log.i(TAG, "Unloading packages");
12774            unloadMediaPackages(processCids, uidArr, reportStatus);
12775        }
12776    }
12777
12778    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12779            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12780        int size = pkgList.size();
12781        if (size > 0) {
12782            // Send broadcasts here
12783            Bundle extras = new Bundle();
12784            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12785                    .toArray(new String[size]));
12786            if (uidArr != null) {
12787                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12788            }
12789            if (replacing) {
12790                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12791            }
12792            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12793                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12794            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12795        }
12796    }
12797
12798   /*
12799     * Look at potentially valid container ids from processCids If package
12800     * information doesn't match the one on record or package scanning fails,
12801     * the cid is added to list of removeCids. We currently don't delete stale
12802     * containers.
12803     */
12804    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12805        ArrayList<String> pkgList = new ArrayList<String>();
12806        Set<AsecInstallArgs> keys = processCids.keySet();
12807
12808        for (AsecInstallArgs args : keys) {
12809            String codePath = processCids.get(args);
12810            if (DEBUG_SD_INSTALL)
12811                Log.i(TAG, "Loading container : " + args.cid);
12812            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12813            try {
12814                // Make sure there are no container errors first.
12815                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12816                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12817                            + " when installing from sdcard");
12818                    continue;
12819                }
12820                // Check code path here.
12821                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12822                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12823                            + " does not match one in settings " + codePath);
12824                    continue;
12825                }
12826                // Parse package
12827                int parseFlags = mDefParseFlags;
12828                if (args.isExternal()) {
12829                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12830                }
12831                if (args.isFwdLocked()) {
12832                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12833                }
12834
12835                synchronized (mInstallLock) {
12836                    PackageParser.Package pkg = null;
12837                    try {
12838                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12839                    } catch (PackageManagerException e) {
12840                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12841                    }
12842                    // Scan the package
12843                    if (pkg != null) {
12844                        /*
12845                         * TODO why is the lock being held? doPostInstall is
12846                         * called in other places without the lock. This needs
12847                         * to be straightened out.
12848                         */
12849                        // writer
12850                        synchronized (mPackages) {
12851                            retCode = PackageManager.INSTALL_SUCCEEDED;
12852                            pkgList.add(pkg.packageName);
12853                            // Post process args
12854                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12855                                    pkg.applicationInfo.uid);
12856                        }
12857                    } else {
12858                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12859                    }
12860                }
12861
12862            } finally {
12863                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12864                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12865                }
12866            }
12867        }
12868        // writer
12869        synchronized (mPackages) {
12870            // If the platform SDK has changed since the last time we booted,
12871            // we need to re-grant app permission to catch any new ones that
12872            // appear. This is really a hack, and means that apps can in some
12873            // cases get permissions that the user didn't initially explicitly
12874            // allow... it would be nice to have some better way to handle
12875            // this situation.
12876            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12877            if (regrantPermissions)
12878                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12879                        + mSdkVersion + "; regranting permissions for external storage");
12880            mSettings.mExternalSdkPlatform = mSdkVersion;
12881
12882            // Make sure group IDs have been assigned, and any permission
12883            // changes in other apps are accounted for
12884            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12885                    | (regrantPermissions
12886                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12887                            : 0));
12888
12889            mSettings.updateExternalDatabaseVersion();
12890
12891            // can downgrade to reader
12892            // Persist settings
12893            mSettings.writeLPr();
12894        }
12895        // Send a broadcast to let everyone know we are done processing
12896        if (pkgList.size() > 0) {
12897            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12898        }
12899    }
12900
12901   /*
12902     * Utility method to unload a list of specified containers
12903     */
12904    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12905        // Just unmount all valid containers.
12906        for (AsecInstallArgs arg : cidArgs) {
12907            synchronized (mInstallLock) {
12908                arg.doPostDeleteLI(false);
12909           }
12910       }
12911   }
12912
12913    /*
12914     * Unload packages mounted on external media. This involves deleting package
12915     * data from internal structures, sending broadcasts about diabled packages,
12916     * gc'ing to free up references, unmounting all secure containers
12917     * corresponding to packages on external media, and posting a
12918     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12919     * that we always have to post this message if status has been requested no
12920     * matter what.
12921     */
12922    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12923            final boolean reportStatus) {
12924        if (DEBUG_SD_INSTALL)
12925            Log.i(TAG, "unloading media packages");
12926        ArrayList<String> pkgList = new ArrayList<String>();
12927        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12928        final Set<AsecInstallArgs> keys = processCids.keySet();
12929        for (AsecInstallArgs args : keys) {
12930            String pkgName = args.getPackageName();
12931            if (DEBUG_SD_INSTALL)
12932                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12933            // Delete package internally
12934            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12935            synchronized (mInstallLock) {
12936                boolean res = deletePackageLI(pkgName, null, false, null, null,
12937                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12938                if (res) {
12939                    pkgList.add(pkgName);
12940                } else {
12941                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12942                    failedList.add(args);
12943                }
12944            }
12945        }
12946
12947        // reader
12948        synchronized (mPackages) {
12949            // We didn't update the settings after removing each package;
12950            // write them now for all packages.
12951            mSettings.writeLPr();
12952        }
12953
12954        // We have to absolutely send UPDATED_MEDIA_STATUS only
12955        // after confirming that all the receivers processed the ordered
12956        // broadcast when packages get disabled, force a gc to clean things up.
12957        // and unload all the containers.
12958        if (pkgList.size() > 0) {
12959            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12960                    new IIntentReceiver.Stub() {
12961                public void performReceive(Intent intent, int resultCode, String data,
12962                        Bundle extras, boolean ordered, boolean sticky,
12963                        int sendingUser) throws RemoteException {
12964                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12965                            reportStatus ? 1 : 0, 1, keys);
12966                    mHandler.sendMessage(msg);
12967                }
12968            });
12969        } else {
12970            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12971                    keys);
12972            mHandler.sendMessage(msg);
12973        }
12974    }
12975
12976    /** Binder call */
12977    @Override
12978    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12979            final int flags) {
12980        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12981        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12982        int returnCode = PackageManager.MOVE_SUCCEEDED;
12983        int currInstallFlags = 0;
12984        int newInstallFlags = 0;
12985
12986        File codeFile = null;
12987        String installerPackageName = null;
12988        String packageAbiOverride = null;
12989
12990        // reader
12991        synchronized (mPackages) {
12992            final PackageParser.Package pkg = mPackages.get(packageName);
12993            final PackageSetting ps = mSettings.mPackages.get(packageName);
12994            if (pkg == null || ps == null) {
12995                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12996            } else {
12997                // Disable moving fwd locked apps and system packages
12998                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12999                    Slog.w(TAG, "Cannot move system application");
13000                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
13001                } else if (pkg.mOperationPending) {
13002                    Slog.w(TAG, "Attempt to move package which has pending operations");
13003                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
13004                } else {
13005                    // Find install location first
13006                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13007                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13008                        Slog.w(TAG, "Ambigous flags specified for move location.");
13009                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13010                    } else {
13011                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13012                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13013                        currInstallFlags = isExternal(pkg)
13014                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13015
13016                        if (newInstallFlags == currInstallFlags) {
13017                            Slog.w(TAG, "No move required. Trying to move to same location");
13018                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13019                        } else {
13020                            if (pkg.isForwardLocked()) {
13021                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13022                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13023                            }
13024                        }
13025                    }
13026                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13027                        pkg.mOperationPending = true;
13028                    }
13029                }
13030
13031                codeFile = new File(pkg.codePath);
13032                installerPackageName = ps.installerPackageName;
13033                packageAbiOverride = ps.cpuAbiOverrideString;
13034            }
13035        }
13036
13037        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13038            try {
13039                observer.packageMoved(packageName, returnCode);
13040            } catch (RemoteException ignored) {
13041            }
13042            return;
13043        }
13044
13045        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
13046            @Override
13047            public void onUserActionRequired(Intent intent) throws RemoteException {
13048                throw new IllegalStateException();
13049            }
13050
13051            @Override
13052            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
13053                    Bundle extras) throws RemoteException {
13054                Slog.d(TAG, "Install result for move: "
13055                        + PackageManager.installStatusToString(returnCode, msg));
13056
13057                // We usually have a new package now after the install, but if
13058                // we failed we need to clear the pending flag on the original
13059                // package object.
13060                synchronized (mPackages) {
13061                    final PackageParser.Package pkg = mPackages.get(packageName);
13062                    if (pkg != null) {
13063                        pkg.mOperationPending = false;
13064                    }
13065                }
13066
13067                final int status = PackageManager.installStatusToPublicStatus(returnCode);
13068                switch (status) {
13069                    case PackageInstaller.STATUS_SUCCESS:
13070                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
13071                        break;
13072                    case PackageInstaller.STATUS_FAILURE_STORAGE:
13073                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
13074                        break;
13075                    default:
13076                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
13077                        break;
13078                }
13079            }
13080        };
13081
13082        // Treat a move like reinstalling an existing app, which ensures that we
13083        // process everythign uniformly, like unpacking native libraries.
13084        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
13085
13086        final Message msg = mHandler.obtainMessage(INIT_COPY);
13087        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
13088        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
13089                installerPackageName, null, user, packageAbiOverride);
13090        mHandler.sendMessage(msg);
13091    }
13092
13093    @Override
13094    public boolean setInstallLocation(int loc) {
13095        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13096                null);
13097        if (getInstallLocation() == loc) {
13098            return true;
13099        }
13100        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13101                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13102            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13103                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13104            return true;
13105        }
13106        return false;
13107   }
13108
13109    @Override
13110    public int getInstallLocation() {
13111        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13112                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13113                PackageHelper.APP_INSTALL_AUTO);
13114    }
13115
13116    /** Called by UserManagerService */
13117    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13118        mDirtyUsers.remove(userHandle);
13119        mSettings.removeUserLPw(userHandle);
13120        mPendingBroadcasts.remove(userHandle);
13121        if (mInstaller != null) {
13122            // Technically, we shouldn't be doing this with the package lock
13123            // held.  However, this is very rare, and there is already so much
13124            // other disk I/O going on, that we'll let it slide for now.
13125            mInstaller.removeUserDataDirs(userHandle);
13126        }
13127        mUserNeedsBadging.delete(userHandle);
13128        removeUnusedPackagesLILPw(userManager, userHandle);
13129    }
13130
13131    /**
13132     * We're removing userHandle and would like to remove any downloaded packages
13133     * that are no longer in use by any other user.
13134     * @param userHandle the user being removed
13135     */
13136    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13137        final boolean DEBUG_CLEAN_APKS = false;
13138        int [] users = userManager.getUserIdsLPr();
13139        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13140        while (psit.hasNext()) {
13141            PackageSetting ps = psit.next();
13142            if (ps.pkg == null) {
13143                continue;
13144            }
13145            final String packageName = ps.pkg.packageName;
13146            // Skip over if system app
13147            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13148                continue;
13149            }
13150            if (DEBUG_CLEAN_APKS) {
13151                Slog.i(TAG, "Checking package " + packageName);
13152            }
13153            boolean keep = false;
13154            for (int i = 0; i < users.length; i++) {
13155                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13156                    keep = true;
13157                    if (DEBUG_CLEAN_APKS) {
13158                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13159                                + users[i]);
13160                    }
13161                    break;
13162                }
13163            }
13164            if (!keep) {
13165                if (DEBUG_CLEAN_APKS) {
13166                    Slog.i(TAG, "  Removing package " + packageName);
13167                }
13168                mHandler.post(new Runnable() {
13169                    public void run() {
13170                        deletePackageX(packageName, userHandle, 0);
13171                    } //end run
13172                });
13173            }
13174        }
13175    }
13176
13177    /** Called by UserManagerService */
13178    void createNewUserLILPw(int userHandle, File path) {
13179        if (mInstaller != null) {
13180            mInstaller.createUserConfig(userHandle);
13181            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13182        }
13183    }
13184
13185    @Override
13186    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13187        mContext.enforceCallingOrSelfPermission(
13188                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13189                "Only package verification agents can read the verifier device identity");
13190
13191        synchronized (mPackages) {
13192            return mSettings.getVerifierDeviceIdentityLPw();
13193        }
13194    }
13195
13196    @Override
13197    public void setPermissionEnforced(String permission, boolean enforced) {
13198        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13199        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13200            synchronized (mPackages) {
13201                if (mSettings.mReadExternalStorageEnforced == null
13202                        || mSettings.mReadExternalStorageEnforced != enforced) {
13203                    mSettings.mReadExternalStorageEnforced = enforced;
13204                    mSettings.writeLPr();
13205                }
13206            }
13207            // kill any non-foreground processes so we restart them and
13208            // grant/revoke the GID.
13209            final IActivityManager am = ActivityManagerNative.getDefault();
13210            if (am != null) {
13211                final long token = Binder.clearCallingIdentity();
13212                try {
13213                    am.killProcessesBelowForeground("setPermissionEnforcement");
13214                } catch (RemoteException e) {
13215                } finally {
13216                    Binder.restoreCallingIdentity(token);
13217                }
13218            }
13219        } else {
13220            throw new IllegalArgumentException("No selective enforcement for " + permission);
13221        }
13222    }
13223
13224    @Override
13225    @Deprecated
13226    public boolean isPermissionEnforced(String permission) {
13227        return true;
13228    }
13229
13230    @Override
13231    public boolean isStorageLow() {
13232        final long token = Binder.clearCallingIdentity();
13233        try {
13234            final DeviceStorageMonitorInternal
13235                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13236            if (dsm != null) {
13237                return dsm.isMemoryLow();
13238            } else {
13239                return false;
13240            }
13241        } finally {
13242            Binder.restoreCallingIdentity(token);
13243        }
13244    }
13245
13246    @Override
13247    public IPackageInstaller getPackageInstaller() {
13248        return mInstallerService;
13249    }
13250
13251    private boolean userNeedsBadging(int userId) {
13252        int index = mUserNeedsBadging.indexOfKey(userId);
13253        if (index < 0) {
13254            final UserInfo userInfo;
13255            final long token = Binder.clearCallingIdentity();
13256            try {
13257                userInfo = sUserManager.getUserInfo(userId);
13258            } finally {
13259                Binder.restoreCallingIdentity(token);
13260            }
13261            final boolean b;
13262            if (userInfo != null && userInfo.isManagedProfile()) {
13263                b = true;
13264            } else {
13265                b = false;
13266            }
13267            mUserNeedsBadging.put(userId, b);
13268            return b;
13269        }
13270        return mUserNeedsBadging.valueAt(index);
13271    }
13272
13273    @Override
13274    public KeySet getKeySetByAlias(String packageName, String alias) {
13275        if (packageName == null || alias == null) {
13276            return null;
13277        }
13278        synchronized(mPackages) {
13279            final PackageParser.Package pkg = mPackages.get(packageName);
13280            if (pkg == null) {
13281                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13282                throw new IllegalArgumentException("Unknown package: " + packageName);
13283            }
13284            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13285            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13286        }
13287    }
13288
13289    @Override
13290    public KeySet getSigningKeySet(String packageName) {
13291        if (packageName == null) {
13292            return null;
13293        }
13294        synchronized(mPackages) {
13295            final PackageParser.Package pkg = mPackages.get(packageName);
13296            if (pkg == null) {
13297                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13298                throw new IllegalArgumentException("Unknown package: " + packageName);
13299            }
13300            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13301                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13302                throw new SecurityException("May not access signing KeySet of other apps.");
13303            }
13304            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13305            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13306        }
13307    }
13308
13309    @Override
13310    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13311        if (packageName == null || ks == null) {
13312            return false;
13313        }
13314        synchronized(mPackages) {
13315            final PackageParser.Package pkg = mPackages.get(packageName);
13316            if (pkg == null) {
13317                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13318                throw new IllegalArgumentException("Unknown package: " + packageName);
13319            }
13320            IBinder ksh = ks.getToken();
13321            if (ksh instanceof KeySetHandle) {
13322                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13323                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13324            }
13325            return false;
13326        }
13327    }
13328
13329    @Override
13330    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13331        if (packageName == null || ks == null) {
13332            return false;
13333        }
13334        synchronized(mPackages) {
13335            final PackageParser.Package pkg = mPackages.get(packageName);
13336            if (pkg == null) {
13337                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13338                throw new IllegalArgumentException("Unknown package: " + packageName);
13339            }
13340            IBinder ksh = ks.getToken();
13341            if (ksh instanceof KeySetHandle) {
13342                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13343                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13344            }
13345            return false;
13346        }
13347    }
13348
13349    public void getUsageStatsIfNoPackageUsageInfo() {
13350        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
13351            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
13352            if (usm == null) {
13353                throw new IllegalStateException("UsageStatsManager must be initialized");
13354            }
13355            long now = System.currentTimeMillis();
13356            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
13357            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
13358                String packageName = entry.getKey();
13359                PackageParser.Package pkg = mPackages.get(packageName);
13360                if (pkg == null) {
13361                    continue;
13362                }
13363                UsageStats usage = entry.getValue();
13364                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
13365                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
13366            }
13367        }
13368    }
13369
13370    /**
13371     * Check and throw if the given before/after packages would be considered a
13372     * downgrade.
13373     */
13374    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
13375            throws PackageManagerException {
13376        if (after.versionCode < before.mVersionCode) {
13377            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13378                    "Update version code " + after.versionCode + " is older than current "
13379                    + before.mVersionCode);
13380        } else if (after.versionCode == before.mVersionCode) {
13381            if (after.baseRevisionCode < before.baseRevisionCode) {
13382                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13383                        "Update base revision code " + after.baseRevisionCode
13384                        + " is older than current " + before.baseRevisionCode);
13385            }
13386
13387            if (!ArrayUtils.isEmpty(after.splitNames)) {
13388                for (int i = 0; i < after.splitNames.length; i++) {
13389                    final String splitName = after.splitNames[i];
13390                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
13391                    if (j != -1) {
13392                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
13393                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13394                                    "Update split " + splitName + " revision code "
13395                                    + after.splitRevisionCodes[i] + " is older than current "
13396                                    + before.splitRevisionCodes[j]);
13397                        }
13398                    }
13399                }
13400            }
13401        }
13402    }
13403}
13404