PackageManagerService.java revision b84cb9e9719855d56ea74c2eb7afc49034c0e66f
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;
62import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
63
64import android.util.ArrayMap;
65
66import com.android.internal.R;
67import com.android.internal.app.IMediaContainerService;
68import com.android.internal.app.ResolverActivity;
69import com.android.internal.content.NativeLibraryHelper;
70import com.android.internal.content.PackageHelper;
71import com.android.internal.os.IParcelFileDescriptorFactory;
72import com.android.internal.util.ArrayUtils;
73import com.android.internal.util.FastPrintWriter;
74import com.android.internal.util.FastXmlSerializer;
75import com.android.internal.util.IndentingPrintWriter;
76import com.android.server.EventLogTags;
77import com.android.server.IntentResolver;
78import com.android.server.LocalServices;
79import com.android.server.ServiceThread;
80import com.android.server.SystemConfig;
81import com.android.server.Watchdog;
82import com.android.server.pm.Settings.DatabaseVersion;
83import com.android.server.storage.DeviceStorageMonitorInternal;
84
85import org.xmlpull.v1.XmlSerializer;
86
87import android.app.ActivityManager;
88import android.app.ActivityManagerNative;
89import android.app.AppGlobals;
90import android.app.IActivityManager;
91import android.app.admin.IDevicePolicyManager;
92import android.app.backup.IBackupManager;
93import android.app.usage.UsageStats;
94import android.app.usage.UsageStatsManager;
95import android.content.BroadcastReceiver;
96import android.content.ComponentName;
97import android.content.Context;
98import android.content.IIntentReceiver;
99import android.content.Intent;
100import android.content.IntentFilter;
101import android.content.IntentSender;
102import android.content.IntentSender.SendIntentException;
103import android.content.ServiceConnection;
104import android.content.pm.ActivityInfo;
105import android.content.pm.ApplicationInfo;
106import android.content.pm.FeatureInfo;
107import android.content.pm.IPackageDataObserver;
108import android.content.pm.IPackageDeleteObserver;
109import android.content.pm.IPackageDeleteObserver2;
110import android.content.pm.IPackageInstallObserver2;
111import android.content.pm.IPackageInstaller;
112import android.content.pm.IPackageManager;
113import android.content.pm.IPackageMoveObserver;
114import android.content.pm.IPackageStatsObserver;
115import android.content.pm.InstrumentationInfo;
116import android.content.pm.KeySet;
117import android.content.pm.ManifestDigest;
118import android.content.pm.PackageCleanItem;
119import android.content.pm.PackageInfo;
120import android.content.pm.PackageInfoLite;
121import android.content.pm.PackageInstaller;
122import android.content.pm.PackageManager;
123import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
124import android.content.pm.PackageParser.ActivityIntentInfo;
125import android.content.pm.PackageParser.PackageLite;
126import android.content.pm.PackageParser.PackageParserException;
127import android.content.pm.PackageParser;
128import android.content.pm.PackageStats;
129import android.content.pm.PackageUserState;
130import android.content.pm.ParceledListSlice;
131import android.content.pm.PermissionGroupInfo;
132import android.content.pm.PermissionInfo;
133import android.content.pm.ProviderInfo;
134import android.content.pm.ResolveInfo;
135import android.content.pm.ServiceInfo;
136import android.content.pm.Signature;
137import android.content.pm.UserInfo;
138import android.content.pm.VerificationParams;
139import android.content.pm.VerifierDeviceIdentity;
140import android.content.pm.VerifierInfo;
141import android.content.res.Resources;
142import android.hardware.display.DisplayManager;
143import android.net.Uri;
144import android.os.Binder;
145import android.os.Build;
146import android.os.Bundle;
147import android.os.Environment;
148import android.os.Environment.UserEnvironment;
149import android.os.storage.IMountService;
150import android.os.storage.StorageManager;
151import android.os.Debug;
152import android.os.FileUtils;
153import android.os.Handler;
154import android.os.IBinder;
155import android.os.Looper;
156import android.os.Message;
157import android.os.Parcel;
158import android.os.ParcelFileDescriptor;
159import android.os.Process;
160import android.os.RemoteException;
161import android.os.SELinux;
162import android.os.ServiceManager;
163import android.os.SystemClock;
164import android.os.SystemProperties;
165import android.os.UserHandle;
166import android.os.UserManager;
167import android.security.KeyStore;
168import android.security.SystemKeyStore;
169import android.system.ErrnoException;
170import android.system.Os;
171import android.system.StructStat;
172import android.text.TextUtils;
173import android.text.format.DateUtils;
174import android.util.ArraySet;
175import android.util.AtomicFile;
176import android.util.DisplayMetrics;
177import android.util.EventLog;
178import android.util.ExceptionUtils;
179import android.util.Log;
180import android.util.LogPrinter;
181import android.util.PrintStreamPrinter;
182import android.util.Slog;
183import android.util.SparseArray;
184import android.util.SparseBooleanArray;
185import android.view.Display;
186
187import java.io.BufferedInputStream;
188import java.io.BufferedOutputStream;
189import java.io.BufferedReader;
190import java.io.File;
191import java.io.FileDescriptor;
192import java.io.FileNotFoundException;
193import java.io.FileOutputStream;
194import java.io.FileReader;
195import java.io.FilenameFilter;
196import java.io.IOException;
197import java.io.InputStream;
198import java.io.PrintWriter;
199import java.nio.charset.StandardCharsets;
200import java.security.NoSuchAlgorithmException;
201import java.security.PublicKey;
202import java.security.cert.CertificateEncodingException;
203import java.security.cert.CertificateException;
204import java.text.SimpleDateFormat;
205import java.util.ArrayList;
206import java.util.Arrays;
207import java.util.Collection;
208import java.util.Collections;
209import java.util.Comparator;
210import java.util.Date;
211import java.util.Iterator;
212import java.util.List;
213import java.util.Map;
214import java.util.Objects;
215import java.util.Set;
216import java.util.concurrent.atomic.AtomicBoolean;
217import java.util.concurrent.atomic.AtomicLong;
218
219import dalvik.system.DexFile;
220import dalvik.system.VMRuntime;
221
222import libcore.io.IoUtils;
223import libcore.util.EmptyArray;
224
225/**
226 * Keep track of all those .apks everywhere.
227 *
228 * This is very central to the platform's security; please run the unit
229 * tests whenever making modifications here:
230 *
231mmm frameworks/base/tests/AndroidTests
232adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
233adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
234 *
235 * {@hide}
236 */
237public class PackageManagerService extends IPackageManager.Stub {
238    static final String TAG = "PackageManager";
239    static final boolean DEBUG_SETTINGS = false;
240    static final boolean DEBUG_PREFERRED = false;
241    static final boolean DEBUG_UPGRADE = false;
242    private static final boolean DEBUG_INSTALL = false;
243    private static final boolean DEBUG_REMOVE = false;
244    private static final boolean DEBUG_BROADCASTS = false;
245    private static final boolean DEBUG_SHOW_INFO = false;
246    private static final boolean DEBUG_PACKAGE_INFO = false;
247    private static final boolean DEBUG_INTENT_MATCHING = false;
248    private static final boolean DEBUG_PACKAGE_SCANNING = false;
249    private static final boolean DEBUG_VERIFY = false;
250    private static final boolean DEBUG_DEXOPT = false;
251    private static final boolean DEBUG_ABI_SELECTION = false;
252
253    private static final int RADIO_UID = Process.PHONE_UID;
254    private static final int LOG_UID = Process.LOG_UID;
255    private static final int NFC_UID = Process.NFC_UID;
256    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
257    private static final int SHELL_UID = Process.SHELL_UID;
258
259    // Cap the size of permission trees that 3rd party apps can define
260    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
261
262    // Suffix used during package installation when copying/moving
263    // package apks to install directory.
264    private static final String INSTALL_PACKAGE_SUFFIX = "-";
265
266    static final int SCAN_NO_DEX = 1<<1;
267    static final int SCAN_FORCE_DEX = 1<<2;
268    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
269    static final int SCAN_NEW_INSTALL = 1<<4;
270    static final int SCAN_NO_PATHS = 1<<5;
271    static final int SCAN_UPDATE_TIME = 1<<6;
272    static final int SCAN_DEFER_DEX = 1<<7;
273    static final int SCAN_BOOTING = 1<<8;
274    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
275    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
276    static final int SCAN_REPLACING = 1<<11;
277
278    static final int REMOVE_CHATTY = 1<<16;
279
280    /**
281     * Timeout (in milliseconds) after which the watchdog should declare that
282     * our handler thread is wedged.  The usual default for such things is one
283     * minute but we sometimes do very lengthy I/O operations on this thread,
284     * such as installing multi-gigabyte applications, so ours needs to be longer.
285     */
286    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
287
288    /**
289     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
290     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
291     * settings entry if available, otherwise we use the hardcoded default.  If it's been
292     * more than this long since the last fstrim, we force one during the boot sequence.
293     *
294     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
295     * one gets run at the next available charging+idle time.  This final mandatory
296     * no-fstrim check kicks in only of the other scheduling criteria is never met.
297     */
298    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
299
300    /**
301     * Whether verification is enabled by default.
302     */
303    private static final boolean DEFAULT_VERIFY_ENABLE = true;
304
305    /**
306     * The default maximum time to wait for the verification agent to return in
307     * milliseconds.
308     */
309    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
310
311    /**
312     * The default response for package verification timeout.
313     *
314     * This can be either PackageManager.VERIFICATION_ALLOW or
315     * PackageManager.VERIFICATION_REJECT.
316     */
317    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
318
319    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
320
321    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
322            DEFAULT_CONTAINER_PACKAGE,
323            "com.android.defcontainer.DefaultContainerService");
324
325    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
326
327    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
328
329    final ServiceThread mHandlerThread;
330
331    final PackageHandler mHandler;
332
333    /**
334     * Messages for {@link #mHandler} that need to wait for system ready before
335     * being dispatched.
336     */
337    private ArrayList<Message> mPostSystemReadyMessages;
338
339    final int mSdkVersion = Build.VERSION.SDK_INT;
340
341    final Context mContext;
342    final boolean mFactoryTest;
343    final boolean mOnlyCore;
344    final boolean mLazyDexOpt;
345    final long mDexOptLRUThresholdInMills;
346    final DisplayMetrics mMetrics;
347    final int mDefParseFlags;
348    final String[] mSeparateProcesses;
349    final boolean mIsUpgrade;
350
351    // This is where all application persistent data goes.
352    final File mAppDataDir;
353
354    // This is where all application persistent data goes for secondary users.
355    final File mUserAppDataDir;
356
357    /** The location for ASEC container files on internal storage. */
358    final String mAsecInternalPath;
359
360    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
361    // LOCK HELD.  Can be called with mInstallLock held.
362    final Installer mInstaller;
363
364    /** Directory where installed third-party apps stored */
365    final File mAppInstallDir;
366
367    /**
368     * Directory to which applications installed internally have their
369     * 32 bit native libraries copied.
370     */
371    private File mAppLib32InstallDir;
372
373    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
374    // apps.
375    final File mDrmAppPrivateInstallDir;
376
377    // ----------------------------------------------------------------
378
379    // Lock for state used when installing and doing other long running
380    // operations.  Methods that must be called with this lock held have
381    // the suffix "LI".
382    final Object mInstallLock = new Object();
383
384    // ----------------------------------------------------------------
385
386    // Keys are String (package name), values are Package.  This also serves
387    // as the lock for the global state.  Methods that must be called with
388    // this lock held have the prefix "LP".
389    final ArrayMap<String, PackageParser.Package> mPackages =
390            new ArrayMap<String, PackageParser.Package>();
391
392    // Tracks available target package names -> overlay package paths.
393    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
394        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
395
396    final Settings mSettings;
397    boolean mRestoredSettings;
398
399    // System configuration read by SystemConfig.
400    final int[] mGlobalGids;
401    final SparseArray<ArraySet<String>> mSystemPermissions;
402    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
403
404    // If mac_permissions.xml was found for seinfo labeling.
405    boolean mFoundPolicyFile;
406
407    // If a recursive restorecon of /data/data/<pkg> is needed.
408    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
409
410    public static final class SharedLibraryEntry {
411        public final String path;
412        public final String apk;
413
414        SharedLibraryEntry(String _path, String _apk) {
415            path = _path;
416            apk = _apk;
417        }
418    }
419
420    // Currently known shared libraries.
421    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
422            new ArrayMap<String, SharedLibraryEntry>();
423
424    // All available activities, for your resolving pleasure.
425    final ActivityIntentResolver mActivities =
426            new ActivityIntentResolver();
427
428    // All available receivers, for your resolving pleasure.
429    final ActivityIntentResolver mReceivers =
430            new ActivityIntentResolver();
431
432    // All available services, for your resolving pleasure.
433    final ServiceIntentResolver mServices = new ServiceIntentResolver();
434
435    // All available providers, for your resolving pleasure.
436    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
437
438    // Mapping from provider base names (first directory in content URI codePath)
439    // to the provider information.
440    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
441            new ArrayMap<String, PackageParser.Provider>();
442
443    // Mapping from instrumentation class names to info about them.
444    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
445            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
446
447    // Mapping from permission names to info about them.
448    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
449            new ArrayMap<String, PackageParser.PermissionGroup>();
450
451    // Packages whose data we have transfered into another package, thus
452    // should no longer exist.
453    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
454
455    // Broadcast actions that are only available to the system.
456    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
457
458    /** List of packages waiting for verification. */
459    final SparseArray<PackageVerificationState> mPendingVerification
460            = new SparseArray<PackageVerificationState>();
461
462    /** Set of packages associated with each app op permission. */
463    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
464
465    final PackageInstallerService mInstallerService;
466
467    private final PackageDexOptimizer mPackageDexOptimizer;
468    // Cache of users who need badging.
469    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
470
471    /** Token for keys in mPendingVerification. */
472    private int mPendingVerificationToken = 0;
473
474    volatile boolean mSystemReady;
475    volatile boolean mSafeMode;
476    volatile boolean mHasSystemUidErrors;
477
478    ApplicationInfo mAndroidApplication;
479    final ActivityInfo mResolveActivity = new ActivityInfo();
480    final ResolveInfo mResolveInfo = new ResolveInfo();
481    ComponentName mResolveComponentName;
482    PackageParser.Package mPlatformPackage;
483    ComponentName mCustomResolverComponentName;
484
485    boolean mResolverReplaced = false;
486
487    // Set of pending broadcasts for aggregating enable/disable of components.
488    static class PendingPackageBroadcasts {
489        // for each user id, a map of <package name -> components within that package>
490        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
491
492        public PendingPackageBroadcasts() {
493            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
494        }
495
496        public ArrayList<String> get(int userId, String packageName) {
497            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
498            return packages.get(packageName);
499        }
500
501        public void put(int userId, String packageName, ArrayList<String> components) {
502            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
503            packages.put(packageName, components);
504        }
505
506        public void remove(int userId, String packageName) {
507            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
508            if (packages != null) {
509                packages.remove(packageName);
510            }
511        }
512
513        public void remove(int userId) {
514            mUidMap.remove(userId);
515        }
516
517        public int userIdCount() {
518            return mUidMap.size();
519        }
520
521        public int userIdAt(int n) {
522            return mUidMap.keyAt(n);
523        }
524
525        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
526            return mUidMap.get(userId);
527        }
528
529        public int size() {
530            // total number of pending broadcast entries across all userIds
531            int num = 0;
532            for (int i = 0; i< mUidMap.size(); i++) {
533                num += mUidMap.valueAt(i).size();
534            }
535            return num;
536        }
537
538        public void clear() {
539            mUidMap.clear();
540        }
541
542        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
543            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
544            if (map == null) {
545                map = new ArrayMap<String, ArrayList<String>>();
546                mUidMap.put(userId, map);
547            }
548            return map;
549        }
550    }
551    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
552
553    // Service Connection to remote media container service to copy
554    // package uri's from external media onto secure containers
555    // or internal storage.
556    private IMediaContainerService mContainerService = null;
557
558    static final int SEND_PENDING_BROADCAST = 1;
559    static final int MCS_BOUND = 3;
560    static final int END_COPY = 4;
561    static final int INIT_COPY = 5;
562    static final int MCS_UNBIND = 6;
563    static final int START_CLEANING_PACKAGE = 7;
564    static final int FIND_INSTALL_LOC = 8;
565    static final int POST_INSTALL = 9;
566    static final int MCS_RECONNECT = 10;
567    static final int MCS_GIVE_UP = 11;
568    static final int UPDATED_MEDIA_STATUS = 12;
569    static final int WRITE_SETTINGS = 13;
570    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
571    static final int PACKAGE_VERIFIED = 15;
572    static final int CHECK_PENDING_VERIFICATION = 16;
573
574    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
575
576    // Delay time in millisecs
577    static final int BROADCAST_DELAY = 10 * 1000;
578
579    static UserManagerService sUserManager;
580
581    // Stores a list of users whose package restrictions file needs to be updated
582    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
583
584    final private DefaultContainerConnection mDefContainerConn =
585            new DefaultContainerConnection();
586    class DefaultContainerConnection implements ServiceConnection {
587        public void onServiceConnected(ComponentName name, IBinder service) {
588            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
589            IMediaContainerService imcs =
590                IMediaContainerService.Stub.asInterface(service);
591            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
592        }
593
594        public void onServiceDisconnected(ComponentName name) {
595            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
596        }
597    };
598
599    // Recordkeeping of restore-after-install operations that are currently in flight
600    // between the Package Manager and the Backup Manager
601    class PostInstallData {
602        public InstallArgs args;
603        public PackageInstalledInfo res;
604
605        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
606            args = _a;
607            res = _r;
608        }
609    };
610    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
611    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
612
613    private final String mRequiredVerifierPackage;
614
615    private final PackageUsage mPackageUsage = new PackageUsage();
616
617    private class PackageUsage {
618        private static final int WRITE_INTERVAL
619            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
620
621        private final Object mFileLock = new Object();
622        private final AtomicLong mLastWritten = new AtomicLong(0);
623        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
624
625        private boolean mIsHistoricalPackageUsageAvailable = true;
626
627        boolean isHistoricalPackageUsageAvailable() {
628            return mIsHistoricalPackageUsageAvailable;
629        }
630
631        void write(boolean force) {
632            if (force) {
633                writeInternal();
634                return;
635            }
636            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
637                && !DEBUG_DEXOPT) {
638                return;
639            }
640            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
641                new Thread("PackageUsage_DiskWriter") {
642                    @Override
643                    public void run() {
644                        try {
645                            writeInternal();
646                        } finally {
647                            mBackgroundWriteRunning.set(false);
648                        }
649                    }
650                }.start();
651            }
652        }
653
654        private void writeInternal() {
655            synchronized (mPackages) {
656                synchronized (mFileLock) {
657                    AtomicFile file = getFile();
658                    FileOutputStream f = null;
659                    try {
660                        f = file.startWrite();
661                        BufferedOutputStream out = new BufferedOutputStream(f);
662                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
663                        StringBuilder sb = new StringBuilder();
664                        for (PackageParser.Package pkg : mPackages.values()) {
665                            if (pkg.mLastPackageUsageTimeInMills == 0) {
666                                continue;
667                            }
668                            sb.setLength(0);
669                            sb.append(pkg.packageName);
670                            sb.append(' ');
671                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
672                            sb.append('\n');
673                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
674                        }
675                        out.flush();
676                        file.finishWrite(f);
677                    } catch (IOException e) {
678                        if (f != null) {
679                            file.failWrite(f);
680                        }
681                        Log.e(TAG, "Failed to write package usage times", e);
682                    }
683                }
684            }
685            mLastWritten.set(SystemClock.elapsedRealtime());
686        }
687
688        void readLP() {
689            synchronized (mFileLock) {
690                AtomicFile file = getFile();
691                BufferedInputStream in = null;
692                try {
693                    in = new BufferedInputStream(file.openRead());
694                    StringBuffer sb = new StringBuffer();
695                    while (true) {
696                        String packageName = readToken(in, sb, ' ');
697                        if (packageName == null) {
698                            break;
699                        }
700                        String timeInMillisString = readToken(in, sb, '\n');
701                        if (timeInMillisString == null) {
702                            throw new IOException("Failed to find last usage time for package "
703                                                  + packageName);
704                        }
705                        PackageParser.Package pkg = mPackages.get(packageName);
706                        if (pkg == null) {
707                            continue;
708                        }
709                        long timeInMillis;
710                        try {
711                            timeInMillis = Long.parseLong(timeInMillisString.toString());
712                        } catch (NumberFormatException e) {
713                            throw new IOException("Failed to parse " + timeInMillisString
714                                                  + " as a long.", e);
715                        }
716                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
717                    }
718                } catch (FileNotFoundException expected) {
719                    mIsHistoricalPackageUsageAvailable = false;
720                } catch (IOException e) {
721                    Log.w(TAG, "Failed to read package usage times", e);
722                } finally {
723                    IoUtils.closeQuietly(in);
724                }
725            }
726            mLastWritten.set(SystemClock.elapsedRealtime());
727        }
728
729        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
730                throws IOException {
731            sb.setLength(0);
732            while (true) {
733                int ch = in.read();
734                if (ch == -1) {
735                    if (sb.length() == 0) {
736                        return null;
737                    }
738                    throw new IOException("Unexpected EOF");
739                }
740                if (ch == endOfToken) {
741                    return sb.toString();
742                }
743                sb.append((char)ch);
744            }
745        }
746
747        private AtomicFile getFile() {
748            File dataDir = Environment.getDataDirectory();
749            File systemDir = new File(dataDir, "system");
750            File fname = new File(systemDir, "package-usage.list");
751            return new AtomicFile(fname);
752        }
753    }
754
755    class PackageHandler extends Handler {
756        private boolean mBound = false;
757        final ArrayList<HandlerParams> mPendingInstalls =
758            new ArrayList<HandlerParams>();
759
760        private boolean connectToService() {
761            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
762                    " DefaultContainerService");
763            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
764            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
765            if (mContext.bindServiceAsUser(service, mDefContainerConn,
766                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
767                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
768                mBound = true;
769                return true;
770            }
771            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
772            return false;
773        }
774
775        private void disconnectService() {
776            mContainerService = null;
777            mBound = false;
778            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
779            mContext.unbindService(mDefContainerConn);
780            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
781        }
782
783        PackageHandler(Looper looper) {
784            super(looper);
785        }
786
787        public void handleMessage(Message msg) {
788            try {
789                doHandleMessage(msg);
790            } finally {
791                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
792            }
793        }
794
795        void doHandleMessage(Message msg) {
796            switch (msg.what) {
797                case INIT_COPY: {
798                    HandlerParams params = (HandlerParams) msg.obj;
799                    int idx = mPendingInstalls.size();
800                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
801                    // If a bind was already initiated we dont really
802                    // need to do anything. The pending install
803                    // will be processed later on.
804                    if (!mBound) {
805                        // If this is the only one pending we might
806                        // have to bind to the service again.
807                        if (!connectToService()) {
808                            Slog.e(TAG, "Failed to bind to media container service");
809                            params.serviceError();
810                            return;
811                        } else {
812                            // Once we bind to the service, the first
813                            // pending request will be processed.
814                            mPendingInstalls.add(idx, params);
815                        }
816                    } else {
817                        mPendingInstalls.add(idx, params);
818                        // Already bound to the service. Just make
819                        // sure we trigger off processing the first request.
820                        if (idx == 0) {
821                            mHandler.sendEmptyMessage(MCS_BOUND);
822                        }
823                    }
824                    break;
825                }
826                case MCS_BOUND: {
827                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
828                    if (msg.obj != null) {
829                        mContainerService = (IMediaContainerService) msg.obj;
830                    }
831                    if (mContainerService == null) {
832                        // Something seriously wrong. Bail out
833                        Slog.e(TAG, "Cannot bind to media container service");
834                        for (HandlerParams params : mPendingInstalls) {
835                            // Indicate service bind error
836                            params.serviceError();
837                        }
838                        mPendingInstalls.clear();
839                    } else if (mPendingInstalls.size() > 0) {
840                        HandlerParams params = mPendingInstalls.get(0);
841                        if (params != null) {
842                            if (params.startCopy()) {
843                                // We are done...  look for more work or to
844                                // go idle.
845                                if (DEBUG_SD_INSTALL) Log.i(TAG,
846                                        "Checking for more work or unbind...");
847                                // Delete pending install
848                                if (mPendingInstalls.size() > 0) {
849                                    mPendingInstalls.remove(0);
850                                }
851                                if (mPendingInstalls.size() == 0) {
852                                    if (mBound) {
853                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
854                                                "Posting delayed MCS_UNBIND");
855                                        removeMessages(MCS_UNBIND);
856                                        Message ubmsg = obtainMessage(MCS_UNBIND);
857                                        // Unbind after a little delay, to avoid
858                                        // continual thrashing.
859                                        sendMessageDelayed(ubmsg, 10000);
860                                    }
861                                } else {
862                                    // There are more pending requests in queue.
863                                    // Just post MCS_BOUND message to trigger processing
864                                    // of next pending install.
865                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
866                                            "Posting MCS_BOUND for next work");
867                                    mHandler.sendEmptyMessage(MCS_BOUND);
868                                }
869                            }
870                        }
871                    } else {
872                        // Should never happen ideally.
873                        Slog.w(TAG, "Empty queue");
874                    }
875                    break;
876                }
877                case MCS_RECONNECT: {
878                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
879                    if (mPendingInstalls.size() > 0) {
880                        if (mBound) {
881                            disconnectService();
882                        }
883                        if (!connectToService()) {
884                            Slog.e(TAG, "Failed to bind to media container service");
885                            for (HandlerParams params : mPendingInstalls) {
886                                // Indicate service bind error
887                                params.serviceError();
888                            }
889                            mPendingInstalls.clear();
890                        }
891                    }
892                    break;
893                }
894                case MCS_UNBIND: {
895                    // If there is no actual work left, then time to unbind.
896                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
897
898                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
899                        if (mBound) {
900                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
901
902                            disconnectService();
903                        }
904                    } else if (mPendingInstalls.size() > 0) {
905                        // There are more pending requests in queue.
906                        // Just post MCS_BOUND message to trigger processing
907                        // of next pending install.
908                        mHandler.sendEmptyMessage(MCS_BOUND);
909                    }
910
911                    break;
912                }
913                case MCS_GIVE_UP: {
914                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
915                    mPendingInstalls.remove(0);
916                    break;
917                }
918                case SEND_PENDING_BROADCAST: {
919                    String packages[];
920                    ArrayList<String> components[];
921                    int size = 0;
922                    int uids[];
923                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
924                    synchronized (mPackages) {
925                        if (mPendingBroadcasts == null) {
926                            return;
927                        }
928                        size = mPendingBroadcasts.size();
929                        if (size <= 0) {
930                            // Nothing to be done. Just return
931                            return;
932                        }
933                        packages = new String[size];
934                        components = new ArrayList[size];
935                        uids = new int[size];
936                        int i = 0;  // filling out the above arrays
937
938                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
939                            int packageUserId = mPendingBroadcasts.userIdAt(n);
940                            Iterator<Map.Entry<String, ArrayList<String>>> it
941                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
942                                            .entrySet().iterator();
943                            while (it.hasNext() && i < size) {
944                                Map.Entry<String, ArrayList<String>> ent = it.next();
945                                packages[i] = ent.getKey();
946                                components[i] = ent.getValue();
947                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
948                                uids[i] = (ps != null)
949                                        ? UserHandle.getUid(packageUserId, ps.appId)
950                                        : -1;
951                                i++;
952                            }
953                        }
954                        size = i;
955                        mPendingBroadcasts.clear();
956                    }
957                    // Send broadcasts
958                    for (int i = 0; i < size; i++) {
959                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
960                    }
961                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
962                    break;
963                }
964                case START_CLEANING_PACKAGE: {
965                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
966                    final String packageName = (String)msg.obj;
967                    final int userId = msg.arg1;
968                    final boolean andCode = msg.arg2 != 0;
969                    synchronized (mPackages) {
970                        if (userId == UserHandle.USER_ALL) {
971                            int[] users = sUserManager.getUserIds();
972                            for (int user : users) {
973                                mSettings.addPackageToCleanLPw(
974                                        new PackageCleanItem(user, packageName, andCode));
975                            }
976                        } else {
977                            mSettings.addPackageToCleanLPw(
978                                    new PackageCleanItem(userId, packageName, andCode));
979                        }
980                    }
981                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
982                    startCleaningPackages();
983                } break;
984                case POST_INSTALL: {
985                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
986                    PostInstallData data = mRunningInstalls.get(msg.arg1);
987                    mRunningInstalls.delete(msg.arg1);
988                    boolean deleteOld = false;
989
990                    if (data != null) {
991                        InstallArgs args = data.args;
992                        PackageInstalledInfo res = data.res;
993
994                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
995                            res.removedInfo.sendBroadcast(false, true, false);
996                            Bundle extras = new Bundle(1);
997                            extras.putInt(Intent.EXTRA_UID, res.uid);
998                            // Determine the set of users who are adding this
999                            // package for the first time vs. those who are seeing
1000                            // an update.
1001                            int[] firstUsers;
1002                            int[] updateUsers = new int[0];
1003                            if (res.origUsers == null || res.origUsers.length == 0) {
1004                                firstUsers = res.newUsers;
1005                            } else {
1006                                firstUsers = new int[0];
1007                                for (int i=0; i<res.newUsers.length; i++) {
1008                                    int user = res.newUsers[i];
1009                                    boolean isNew = true;
1010                                    for (int j=0; j<res.origUsers.length; j++) {
1011                                        if (res.origUsers[j] == user) {
1012                                            isNew = false;
1013                                            break;
1014                                        }
1015                                    }
1016                                    if (isNew) {
1017                                        int[] newFirst = new int[firstUsers.length+1];
1018                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1019                                                firstUsers.length);
1020                                        newFirst[firstUsers.length] = user;
1021                                        firstUsers = newFirst;
1022                                    } else {
1023                                        int[] newUpdate = new int[updateUsers.length+1];
1024                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1025                                                updateUsers.length);
1026                                        newUpdate[updateUsers.length] = user;
1027                                        updateUsers = newUpdate;
1028                                    }
1029                                }
1030                            }
1031                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1032                                    res.pkg.applicationInfo.packageName,
1033                                    extras, null, null, firstUsers);
1034                            final boolean update = res.removedInfo.removedPackage != null;
1035                            if (update) {
1036                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1037                            }
1038                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1039                                    res.pkg.applicationInfo.packageName,
1040                                    extras, null, null, updateUsers);
1041                            if (update) {
1042                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1043                                        res.pkg.applicationInfo.packageName,
1044                                        extras, null, null, updateUsers);
1045                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1046                                        null, null,
1047                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1048
1049                                // treat asec-hosted packages like removable media on upgrade
1050                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1051                                    if (DEBUG_INSTALL) {
1052                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1053                                                + " is ASEC-hosted -> AVAILABLE");
1054                                    }
1055                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1056                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1057                                    pkgList.add(res.pkg.applicationInfo.packageName);
1058                                    sendResourcesChangedBroadcast(true, true,
1059                                            pkgList,uidArray, null);
1060                                }
1061                            }
1062                            if (res.removedInfo.args != null) {
1063                                // Remove the replaced package's older resources safely now
1064                                deleteOld = true;
1065                            }
1066
1067                            // Log current value of "unknown sources" setting
1068                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1069                                getUnknownSourcesSettings());
1070                        }
1071                        // Force a gc to clear up things
1072                        Runtime.getRuntime().gc();
1073                        // We delete after a gc for applications  on sdcard.
1074                        if (deleteOld) {
1075                            synchronized (mInstallLock) {
1076                                res.removedInfo.args.doPostDeleteLI(true);
1077                            }
1078                        }
1079                        if (args.observer != null) {
1080                            try {
1081                                Bundle extras = extrasForInstallResult(res);
1082                                args.observer.onPackageInstalled(res.name, res.returnCode,
1083                                        res.returnMsg, extras);
1084                            } catch (RemoteException e) {
1085                                Slog.i(TAG, "Observer no longer exists.");
1086                            }
1087                        }
1088                    } else {
1089                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1090                    }
1091                } break;
1092                case UPDATED_MEDIA_STATUS: {
1093                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1094                    boolean reportStatus = msg.arg1 == 1;
1095                    boolean doGc = msg.arg2 == 1;
1096                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1097                    if (doGc) {
1098                        // Force a gc to clear up stale containers.
1099                        Runtime.getRuntime().gc();
1100                    }
1101                    if (msg.obj != null) {
1102                        @SuppressWarnings("unchecked")
1103                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1104                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1105                        // Unload containers
1106                        unloadAllContainers(args);
1107                    }
1108                    if (reportStatus) {
1109                        try {
1110                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1111                            PackageHelper.getMountService().finishMediaUpdate();
1112                        } catch (RemoteException e) {
1113                            Log.e(TAG, "MountService not running?");
1114                        }
1115                    }
1116                } break;
1117                case WRITE_SETTINGS: {
1118                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1119                    synchronized (mPackages) {
1120                        removeMessages(WRITE_SETTINGS);
1121                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1122                        mSettings.writeLPr();
1123                        mDirtyUsers.clear();
1124                    }
1125                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1126                } break;
1127                case WRITE_PACKAGE_RESTRICTIONS: {
1128                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1129                    synchronized (mPackages) {
1130                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1131                        for (int userId : mDirtyUsers) {
1132                            mSettings.writePackageRestrictionsLPr(userId);
1133                        }
1134                        mDirtyUsers.clear();
1135                    }
1136                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1137                } break;
1138                case CHECK_PENDING_VERIFICATION: {
1139                    final int verificationId = msg.arg1;
1140                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1141
1142                    if ((state != null) && !state.timeoutExtended()) {
1143                        final InstallArgs args = state.getInstallArgs();
1144                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1145
1146                        Slog.i(TAG, "Verification timed out for " + originUri);
1147                        mPendingVerification.remove(verificationId);
1148
1149                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1150
1151                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1152                            Slog.i(TAG, "Continuing with installation of " + originUri);
1153                            state.setVerifierResponse(Binder.getCallingUid(),
1154                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1155                            broadcastPackageVerified(verificationId, originUri,
1156                                    PackageManager.VERIFICATION_ALLOW,
1157                                    state.getInstallArgs().getUser());
1158                            try {
1159                                ret = args.copyApk(mContainerService, true);
1160                            } catch (RemoteException e) {
1161                                Slog.e(TAG, "Could not contact the ContainerService");
1162                            }
1163                        } else {
1164                            broadcastPackageVerified(verificationId, originUri,
1165                                    PackageManager.VERIFICATION_REJECT,
1166                                    state.getInstallArgs().getUser());
1167                        }
1168
1169                        processPendingInstall(args, ret);
1170                        mHandler.sendEmptyMessage(MCS_UNBIND);
1171                    }
1172                    break;
1173                }
1174                case PACKAGE_VERIFIED: {
1175                    final int verificationId = msg.arg1;
1176
1177                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1178                    if (state == null) {
1179                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1180                        break;
1181                    }
1182
1183                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1184
1185                    state.setVerifierResponse(response.callerUid, response.code);
1186
1187                    if (state.isVerificationComplete()) {
1188                        mPendingVerification.remove(verificationId);
1189
1190                        final InstallArgs args = state.getInstallArgs();
1191                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1192
1193                        int ret;
1194                        if (state.isInstallAllowed()) {
1195                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1196                            broadcastPackageVerified(verificationId, originUri,
1197                                    response.code, state.getInstallArgs().getUser());
1198                            try {
1199                                ret = args.copyApk(mContainerService, true);
1200                            } catch (RemoteException e) {
1201                                Slog.e(TAG, "Could not contact the ContainerService");
1202                            }
1203                        } else {
1204                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1205                        }
1206
1207                        processPendingInstall(args, ret);
1208
1209                        mHandler.sendEmptyMessage(MCS_UNBIND);
1210                    }
1211
1212                    break;
1213                }
1214            }
1215        }
1216    }
1217
1218    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1219        Bundle extras = null;
1220        switch (res.returnCode) {
1221            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1222                extras = new Bundle();
1223                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1224                        res.origPermission);
1225                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1226                        res.origPackage);
1227                break;
1228            }
1229        }
1230        return extras;
1231    }
1232
1233    void scheduleWriteSettingsLocked() {
1234        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1235            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1236        }
1237    }
1238
1239    void scheduleWritePackageRestrictionsLocked(int userId) {
1240        if (!sUserManager.exists(userId)) return;
1241        mDirtyUsers.add(userId);
1242        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1243            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1244        }
1245    }
1246
1247    public static final PackageManagerService main(Context context, Installer installer,
1248            boolean factoryTest, boolean onlyCore) {
1249        PackageManagerService m = new PackageManagerService(context, installer,
1250                factoryTest, onlyCore);
1251        ServiceManager.addService("package", m);
1252        return m;
1253    }
1254
1255    static String[] splitString(String str, char sep) {
1256        int count = 1;
1257        int i = 0;
1258        while ((i=str.indexOf(sep, i)) >= 0) {
1259            count++;
1260            i++;
1261        }
1262
1263        String[] res = new String[count];
1264        i=0;
1265        count = 0;
1266        int lastI=0;
1267        while ((i=str.indexOf(sep, i)) >= 0) {
1268            res[count] = str.substring(lastI, i);
1269            count++;
1270            i++;
1271            lastI = i;
1272        }
1273        res[count] = str.substring(lastI, str.length());
1274        return res;
1275    }
1276
1277    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1278        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1279                Context.DISPLAY_SERVICE);
1280        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1281    }
1282
1283    public PackageManagerService(Context context, Installer installer,
1284            boolean factoryTest, boolean onlyCore) {
1285        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1286                SystemClock.uptimeMillis());
1287
1288        if (mSdkVersion <= 0) {
1289            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1290        }
1291
1292        mContext = context;
1293        mFactoryTest = factoryTest;
1294        mOnlyCore = onlyCore;
1295        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1296        mMetrics = new DisplayMetrics();
1297        mSettings = new Settings(context);
1298        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1299                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1300        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1301                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1302        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1303                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1304        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1305                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1306        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1307                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1308        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1309                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1310
1311        // TODO: add a property to control this?
1312        long dexOptLRUThresholdInMinutes;
1313        if (mLazyDexOpt) {
1314            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1315        } else {
1316            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1317        }
1318        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1319
1320        String separateProcesses = SystemProperties.get("debug.separate_processes");
1321        if (separateProcesses != null && separateProcesses.length() > 0) {
1322            if ("*".equals(separateProcesses)) {
1323                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1324                mSeparateProcesses = null;
1325                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1326            } else {
1327                mDefParseFlags = 0;
1328                mSeparateProcesses = separateProcesses.split(",");
1329                Slog.w(TAG, "Running with debug.separate_processes: "
1330                        + separateProcesses);
1331            }
1332        } else {
1333            mDefParseFlags = 0;
1334            mSeparateProcesses = null;
1335        }
1336
1337        mInstaller = installer;
1338        mPackageDexOptimizer = new PackageDexOptimizer(this);
1339
1340        getDefaultDisplayMetrics(context, mMetrics);
1341
1342        SystemConfig systemConfig = SystemConfig.getInstance();
1343        mGlobalGids = systemConfig.getGlobalGids();
1344        mSystemPermissions = systemConfig.getSystemPermissions();
1345        mAvailableFeatures = systemConfig.getAvailableFeatures();
1346
1347        synchronized (mInstallLock) {
1348        // writer
1349        synchronized (mPackages) {
1350            mHandlerThread = new ServiceThread(TAG,
1351                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1352            mHandlerThread.start();
1353            mHandler = new PackageHandler(mHandlerThread.getLooper());
1354            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1355
1356            File dataDir = Environment.getDataDirectory();
1357            mAppDataDir = new File(dataDir, "data");
1358            mAppInstallDir = new File(dataDir, "app");
1359            mAppLib32InstallDir = new File(dataDir, "app-lib");
1360            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1361            mUserAppDataDir = new File(dataDir, "user");
1362            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1363
1364            sUserManager = new UserManagerService(context, this,
1365                    mInstallLock, mPackages);
1366
1367            // Propagate permission configuration in to package manager.
1368            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1369                    = systemConfig.getPermissions();
1370            for (int i=0; i<permConfig.size(); i++) {
1371                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1372                BasePermission bp = mSettings.mPermissions.get(perm.name);
1373                if (bp == null) {
1374                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1375                    mSettings.mPermissions.put(perm.name, bp);
1376                }
1377                if (perm.gids != null) {
1378                    bp.gids = appendInts(bp.gids, perm.gids);
1379                }
1380            }
1381
1382            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1383            for (int i=0; i<libConfig.size(); i++) {
1384                mSharedLibraries.put(libConfig.keyAt(i),
1385                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1386            }
1387
1388            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1389
1390            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1391                    mSdkVersion, mOnlyCore);
1392
1393            String customResolverActivity = Resources.getSystem().getString(
1394                    R.string.config_customResolverActivity);
1395            if (TextUtils.isEmpty(customResolverActivity)) {
1396                customResolverActivity = null;
1397            } else {
1398                mCustomResolverComponentName = ComponentName.unflattenFromString(
1399                        customResolverActivity);
1400            }
1401
1402            long startTime = SystemClock.uptimeMillis();
1403
1404            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1405                    startTime);
1406
1407            // Set flag to monitor and not change apk file paths when
1408            // scanning install directories.
1409            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1410
1411            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1412
1413            /**
1414             * Add everything in the in the boot class path to the
1415             * list of process files because dexopt will have been run
1416             * if necessary during zygote startup.
1417             */
1418            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1419            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1420
1421            if (bootClassPath != null) {
1422                String[] bootClassPathElements = splitString(bootClassPath, ':');
1423                for (String element : bootClassPathElements) {
1424                    alreadyDexOpted.add(element);
1425                }
1426            } else {
1427                Slog.w(TAG, "No BOOTCLASSPATH found!");
1428            }
1429
1430            if (systemServerClassPath != null) {
1431                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1432                for (String element : systemServerClassPathElements) {
1433                    alreadyDexOpted.add(element);
1434                }
1435            } else {
1436                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1437            }
1438
1439            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1440            final String[] dexCodeInstructionSets =
1441                    getDexCodeInstructionSets(
1442                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1443
1444            /**
1445             * Ensure all external libraries have had dexopt run on them.
1446             */
1447            if (mSharedLibraries.size() > 0) {
1448                // NOTE: For now, we're compiling these system "shared libraries"
1449                // (and framework jars) into all available architectures. It's possible
1450                // to compile them only when we come across an app that uses them (there's
1451                // already logic for that in scanPackageLI) but that adds some complexity.
1452                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1453                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1454                        final String lib = libEntry.path;
1455                        if (lib == null) {
1456                            continue;
1457                        }
1458
1459                        try {
1460                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1461                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1462                                alreadyDexOpted.add(lib);
1463                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1464                            }
1465                        } catch (FileNotFoundException e) {
1466                            Slog.w(TAG, "Library not found: " + lib);
1467                        } catch (IOException e) {
1468                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1469                                    + e.getMessage());
1470                        }
1471                    }
1472                }
1473            }
1474
1475            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1476
1477            // Gross hack for now: we know this file doesn't contain any
1478            // code, so don't dexopt it to avoid the resulting log spew.
1479            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1480
1481            // Gross hack for now: we know this file is only part of
1482            // the boot class path for art, so don't dexopt it to
1483            // avoid the resulting log spew.
1484            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1485
1486            /**
1487             * And there are a number of commands implemented in Java, which
1488             * we currently need to do the dexopt on so that they can be
1489             * run from a non-root shell.
1490             */
1491            String[] frameworkFiles = frameworkDir.list();
1492            if (frameworkFiles != null) {
1493                // TODO: We could compile these only for the most preferred ABI. We should
1494                // first double check that the dex files for these commands are not referenced
1495                // by other system apps.
1496                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1497                    for (int i=0; i<frameworkFiles.length; i++) {
1498                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1499                        String path = libPath.getPath();
1500                        // Skip the file if we already did it.
1501                        if (alreadyDexOpted.contains(path)) {
1502                            continue;
1503                        }
1504                        // Skip the file if it is not a type we want to dexopt.
1505                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1506                            continue;
1507                        }
1508                        try {
1509                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1510                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1511                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1512                            }
1513                        } catch (FileNotFoundException e) {
1514                            Slog.w(TAG, "Jar not found: " + path);
1515                        } catch (IOException e) {
1516                            Slog.w(TAG, "Exception reading jar: " + path, e);
1517                        }
1518                    }
1519                }
1520            }
1521
1522            // Collect vendor overlay packages.
1523            // (Do this before scanning any apps.)
1524            // For security and version matching reason, only consider
1525            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1526            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1527            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1528                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1529
1530            // Find base frameworks (resource packages without code).
1531            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1532                    | PackageParser.PARSE_IS_SYSTEM_DIR
1533                    | PackageParser.PARSE_IS_PRIVILEGED,
1534                    scanFlags | SCAN_NO_DEX, 0);
1535
1536            // Collected privileged system packages.
1537            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1538            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1539                    | PackageParser.PARSE_IS_SYSTEM_DIR
1540                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1541
1542            // Collect ordinary system packages.
1543            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1544            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1545                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1546
1547            // Collect all vendor packages.
1548            File vendorAppDir = new File("/vendor/app");
1549            try {
1550                vendorAppDir = vendorAppDir.getCanonicalFile();
1551            } catch (IOException e) {
1552                // failed to look up canonical path, continue with original one
1553            }
1554            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1555                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1556
1557            // Collect all OEM packages.
1558            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1559            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1560                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1561
1562            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1563            mInstaller.moveFiles();
1564
1565            // Prune any system packages that no longer exist.
1566            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1567            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1568            if (!mOnlyCore) {
1569                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1570                while (psit.hasNext()) {
1571                    PackageSetting ps = psit.next();
1572
1573                    /*
1574                     * If this is not a system app, it can't be a
1575                     * disable system app.
1576                     */
1577                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1578                        continue;
1579                    }
1580
1581                    /*
1582                     * If the package is scanned, it's not erased.
1583                     */
1584                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1585                    if (scannedPkg != null) {
1586                        /*
1587                         * If the system app is both scanned and in the
1588                         * disabled packages list, then it must have been
1589                         * added via OTA. Remove it from the currently
1590                         * scanned package so the previously user-installed
1591                         * application can be scanned.
1592                         */
1593                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1594                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1595                                    + ps.name + "; removing system app.  Last known codePath="
1596                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1597                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1598                                    + scannedPkg.mVersionCode);
1599                            removePackageLI(ps, true);
1600                            expectingBetter.put(ps.name, ps.codePath);
1601                        }
1602
1603                        continue;
1604                    }
1605
1606                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1607                        psit.remove();
1608                        logCriticalInfo(Log.WARN, "System package " + ps.name
1609                                + " no longer exists; wiping its data");
1610                        removeDataDirsLI(ps.name);
1611                    } else {
1612                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1613                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1614                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1615                        }
1616                    }
1617                }
1618            }
1619
1620            //look for any incomplete package installations
1621            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1622            //clean up list
1623            for(int i = 0; i < deletePkgsList.size(); i++) {
1624                //clean up here
1625                cleanupInstallFailedPackage(deletePkgsList.get(i));
1626            }
1627            //delete tmp files
1628            deleteTempPackageFiles();
1629
1630            // Remove any shared userIDs that have no associated packages
1631            mSettings.pruneSharedUsersLPw();
1632
1633            if (!mOnlyCore) {
1634                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1635                        SystemClock.uptimeMillis());
1636                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1637
1638                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1639                        scanFlags, 0);
1640
1641                /**
1642                 * Remove disable package settings for any updated system
1643                 * apps that were removed via an OTA. If they're not a
1644                 * previously-updated app, remove them completely.
1645                 * Otherwise, just revoke their system-level permissions.
1646                 */
1647                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1648                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1649                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1650
1651                    String msg;
1652                    if (deletedPkg == null) {
1653                        msg = "Updated system package " + deletedAppName
1654                                + " no longer exists; wiping its data";
1655                        removeDataDirsLI(deletedAppName);
1656                    } else {
1657                        msg = "Updated system app + " + deletedAppName
1658                                + " no longer present; removing system privileges for "
1659                                + deletedAppName;
1660
1661                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1662
1663                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1664                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1665                    }
1666                    logCriticalInfo(Log.WARN, msg);
1667                }
1668
1669                /**
1670                 * Make sure all system apps that we expected to appear on
1671                 * the userdata partition actually showed up. If they never
1672                 * appeared, crawl back and revive the system version.
1673                 */
1674                for (int i = 0; i < expectingBetter.size(); i++) {
1675                    final String packageName = expectingBetter.keyAt(i);
1676                    if (!mPackages.containsKey(packageName)) {
1677                        final File scanFile = expectingBetter.valueAt(i);
1678
1679                        logCriticalInfo(Log.WARN, "Expected better " + packageName
1680                                + " but never showed up; reverting to system");
1681
1682                        final int reparseFlags;
1683                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
1684                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1685                                    | PackageParser.PARSE_IS_SYSTEM_DIR
1686                                    | PackageParser.PARSE_IS_PRIVILEGED;
1687                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
1688                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1689                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1690                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
1691                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1692                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1693                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
1694                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1695                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1696                        } else {
1697                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
1698                            continue;
1699                        }
1700
1701                        mSettings.enableSystemPackageLPw(packageName);
1702
1703                        try {
1704                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
1705                        } catch (PackageManagerException e) {
1706                            Slog.e(TAG, "Failed to parse original system package: "
1707                                    + e.getMessage());
1708                        }
1709                    }
1710                }
1711            }
1712
1713            // Now that we know all of the shared libraries, update all clients to have
1714            // the correct library paths.
1715            updateAllSharedLibrariesLPw();
1716
1717            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1718                // NOTE: We ignore potential failures here during a system scan (like
1719                // the rest of the commands above) because there's precious little we
1720                // can do about it. A settings error is reported, though.
1721                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1722                        false /* force dexopt */, false /* defer dexopt */);
1723            }
1724
1725            // Now that we know all the packages we are keeping,
1726            // read and update their last usage times.
1727            mPackageUsage.readLP();
1728
1729            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1730                    SystemClock.uptimeMillis());
1731            Slog.i(TAG, "Time to scan packages: "
1732                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1733                    + " seconds");
1734
1735            // If the platform SDK has changed since the last time we booted,
1736            // we need to re-grant app permission to catch any new ones that
1737            // appear.  This is really a hack, and means that apps can in some
1738            // cases get permissions that the user didn't initially explicitly
1739            // allow...  it would be nice to have some better way to handle
1740            // this situation.
1741            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1742                    != mSdkVersion;
1743            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1744                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1745                    + "; regranting permissions for internal storage");
1746            mSettings.mInternalSdkPlatform = mSdkVersion;
1747
1748            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1749                    | (regrantPermissions
1750                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1751                            : 0));
1752
1753            // If this is the first boot, and it is a normal boot, then
1754            // we need to initialize the default preferred apps.
1755            if (!mRestoredSettings && !onlyCore) {
1756                mSettings.readDefaultPreferredAppsLPw(this, 0);
1757            }
1758
1759            // If this is first boot after an OTA, and a normal boot, then
1760            // we need to clear code cache directories.
1761            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
1762            if (mIsUpgrade && !onlyCore) {
1763                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1764                for (String pkgName : mSettings.mPackages.keySet()) {
1765                    deleteCodeCacheDirsLI(pkgName);
1766                }
1767                mSettings.mFingerprint = Build.FINGERPRINT;
1768            }
1769
1770            // All the changes are done during package scanning.
1771            mSettings.updateInternalDatabaseVersion();
1772
1773            // can downgrade to reader
1774            mSettings.writeLPr();
1775
1776            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1777                    SystemClock.uptimeMillis());
1778
1779
1780            mRequiredVerifierPackage = getRequiredVerifierLPr();
1781        } // synchronized (mPackages)
1782        } // synchronized (mInstallLock)
1783
1784        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1785
1786        // Now after opening every single application zip, make sure they
1787        // are all flushed.  Not really needed, but keeps things nice and
1788        // tidy.
1789        Runtime.getRuntime().gc();
1790    }
1791
1792    @Override
1793    public boolean isFirstBoot() {
1794        return !mRestoredSettings;
1795    }
1796
1797    @Override
1798    public boolean isOnlyCoreApps() {
1799        return mOnlyCore;
1800    }
1801
1802    @Override
1803    public boolean isUpgrade() {
1804        return mIsUpgrade;
1805    }
1806
1807    private String getRequiredVerifierLPr() {
1808        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1809        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1810                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1811
1812        String requiredVerifier = null;
1813
1814        final int N = receivers.size();
1815        for (int i = 0; i < N; i++) {
1816            final ResolveInfo info = receivers.get(i);
1817
1818            if (info.activityInfo == null) {
1819                continue;
1820            }
1821
1822            final String packageName = info.activityInfo.packageName;
1823
1824            final PackageSetting ps = mSettings.mPackages.get(packageName);
1825            if (ps == null) {
1826                continue;
1827            }
1828
1829            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1830            if (!gp.grantedPermissions
1831                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1832                continue;
1833            }
1834
1835            if (requiredVerifier != null) {
1836                throw new RuntimeException("There can be only one required verifier");
1837            }
1838
1839            requiredVerifier = packageName;
1840        }
1841
1842        return requiredVerifier;
1843    }
1844
1845    @Override
1846    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1847            throws RemoteException {
1848        try {
1849            return super.onTransact(code, data, reply, flags);
1850        } catch (RuntimeException e) {
1851            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1852                Slog.wtf(TAG, "Package Manager Crash", e);
1853            }
1854            throw e;
1855        }
1856    }
1857
1858    void cleanupInstallFailedPackage(PackageSetting ps) {
1859        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
1860
1861        removeDataDirsLI(ps.name);
1862        if (ps.codePath != null) {
1863            if (ps.codePath.isDirectory()) {
1864                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
1865            } else {
1866                ps.codePath.delete();
1867            }
1868        }
1869        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1870            if (ps.resourcePath.isDirectory()) {
1871                FileUtils.deleteContents(ps.resourcePath);
1872            }
1873            ps.resourcePath.delete();
1874        }
1875        mSettings.removePackageLPw(ps.name);
1876    }
1877
1878    static int[] appendInts(int[] cur, int[] add) {
1879        if (add == null) return cur;
1880        if (cur == null) return add;
1881        final int N = add.length;
1882        for (int i=0; i<N; i++) {
1883            cur = appendInt(cur, add[i]);
1884        }
1885        return cur;
1886    }
1887
1888    static int[] removeInts(int[] cur, int[] rem) {
1889        if (rem == null) return cur;
1890        if (cur == null) return cur;
1891        final int N = rem.length;
1892        for (int i=0; i<N; i++) {
1893            cur = removeInt(cur, rem[i]);
1894        }
1895        return cur;
1896    }
1897
1898    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1899        if (!sUserManager.exists(userId)) return null;
1900        final PackageSetting ps = (PackageSetting) p.mExtras;
1901        if (ps == null) {
1902            return null;
1903        }
1904        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1905        final PackageUserState state = ps.readUserState(userId);
1906        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1907                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1908                state, userId);
1909    }
1910
1911    @Override
1912    public boolean isPackageAvailable(String packageName, int userId) {
1913        if (!sUserManager.exists(userId)) return false;
1914        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
1915        synchronized (mPackages) {
1916            PackageParser.Package p = mPackages.get(packageName);
1917            if (p != null) {
1918                final PackageSetting ps = (PackageSetting) p.mExtras;
1919                if (ps != null) {
1920                    final PackageUserState state = ps.readUserState(userId);
1921                    if (state != null) {
1922                        return PackageParser.isAvailable(state);
1923                    }
1924                }
1925            }
1926        }
1927        return false;
1928    }
1929
1930    @Override
1931    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1932        if (!sUserManager.exists(userId)) return null;
1933        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
1934        // reader
1935        synchronized (mPackages) {
1936            PackageParser.Package p = mPackages.get(packageName);
1937            if (DEBUG_PACKAGE_INFO)
1938                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1939            if (p != null) {
1940                return generatePackageInfo(p, flags, userId);
1941            }
1942            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1943                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1944            }
1945        }
1946        return null;
1947    }
1948
1949    @Override
1950    public String[] currentToCanonicalPackageNames(String[] names) {
1951        String[] out = new String[names.length];
1952        // reader
1953        synchronized (mPackages) {
1954            for (int i=names.length-1; i>=0; i--) {
1955                PackageSetting ps = mSettings.mPackages.get(names[i]);
1956                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1957            }
1958        }
1959        return out;
1960    }
1961
1962    @Override
1963    public String[] canonicalToCurrentPackageNames(String[] names) {
1964        String[] out = new String[names.length];
1965        // reader
1966        synchronized (mPackages) {
1967            for (int i=names.length-1; i>=0; i--) {
1968                String cur = mSettings.mRenamedPackages.get(names[i]);
1969                out[i] = cur != null ? cur : names[i];
1970            }
1971        }
1972        return out;
1973    }
1974
1975    @Override
1976    public int getPackageUid(String packageName, int userId) {
1977        if (!sUserManager.exists(userId)) return -1;
1978        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
1979        // reader
1980        synchronized (mPackages) {
1981            PackageParser.Package p = mPackages.get(packageName);
1982            if(p != null) {
1983                return UserHandle.getUid(userId, p.applicationInfo.uid);
1984            }
1985            PackageSetting ps = mSettings.mPackages.get(packageName);
1986            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1987                return -1;
1988            }
1989            p = ps.pkg;
1990            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1991        }
1992    }
1993
1994    @Override
1995    public int[] getPackageGids(String packageName) {
1996        // reader
1997        synchronized (mPackages) {
1998            PackageParser.Package p = mPackages.get(packageName);
1999            if (DEBUG_PACKAGE_INFO)
2000                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2001            if (p != null) {
2002                final PackageSetting ps = (PackageSetting)p.mExtras;
2003                return ps.getGids();
2004            }
2005        }
2006        // stupid thing to indicate an error.
2007        return new int[0];
2008    }
2009
2010    static final PermissionInfo generatePermissionInfo(
2011            BasePermission bp, int flags) {
2012        if (bp.perm != null) {
2013            return PackageParser.generatePermissionInfo(bp.perm, flags);
2014        }
2015        PermissionInfo pi = new PermissionInfo();
2016        pi.name = bp.name;
2017        pi.packageName = bp.sourcePackage;
2018        pi.nonLocalizedLabel = bp.name;
2019        pi.protectionLevel = bp.protectionLevel;
2020        return pi;
2021    }
2022
2023    @Override
2024    public PermissionInfo getPermissionInfo(String name, int flags) {
2025        // reader
2026        synchronized (mPackages) {
2027            final BasePermission p = mSettings.mPermissions.get(name);
2028            if (p != null) {
2029                return generatePermissionInfo(p, flags);
2030            }
2031            return null;
2032        }
2033    }
2034
2035    @Override
2036    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2037        // reader
2038        synchronized (mPackages) {
2039            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2040            for (BasePermission p : mSettings.mPermissions.values()) {
2041                if (group == null) {
2042                    if (p.perm == null || p.perm.info.group == null) {
2043                        out.add(generatePermissionInfo(p, flags));
2044                    }
2045                } else {
2046                    if (p.perm != null && group.equals(p.perm.info.group)) {
2047                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2048                    }
2049                }
2050            }
2051
2052            if (out.size() > 0) {
2053                return out;
2054            }
2055            return mPermissionGroups.containsKey(group) ? out : null;
2056        }
2057    }
2058
2059    @Override
2060    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2061        // reader
2062        synchronized (mPackages) {
2063            return PackageParser.generatePermissionGroupInfo(
2064                    mPermissionGroups.get(name), flags);
2065        }
2066    }
2067
2068    @Override
2069    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2070        // reader
2071        synchronized (mPackages) {
2072            final int N = mPermissionGroups.size();
2073            ArrayList<PermissionGroupInfo> out
2074                    = new ArrayList<PermissionGroupInfo>(N);
2075            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2076                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2077            }
2078            return out;
2079        }
2080    }
2081
2082    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2083            int userId) {
2084        if (!sUserManager.exists(userId)) return null;
2085        PackageSetting ps = mSettings.mPackages.get(packageName);
2086        if (ps != null) {
2087            if (ps.pkg == null) {
2088                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2089                        flags, userId);
2090                if (pInfo != null) {
2091                    return pInfo.applicationInfo;
2092                }
2093                return null;
2094            }
2095            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2096                    ps.readUserState(userId), userId);
2097        }
2098        return null;
2099    }
2100
2101    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2102            int userId) {
2103        if (!sUserManager.exists(userId)) return null;
2104        PackageSetting ps = mSettings.mPackages.get(packageName);
2105        if (ps != null) {
2106            PackageParser.Package pkg = ps.pkg;
2107            if (pkg == null) {
2108                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2109                    return null;
2110                }
2111                // Only data remains, so we aren't worried about code paths
2112                pkg = new PackageParser.Package(packageName);
2113                pkg.applicationInfo.packageName = packageName;
2114                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2115                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2116                pkg.applicationInfo.dataDir =
2117                        getDataPathForPackage(packageName, 0).getPath();
2118                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2119                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2120            }
2121            return generatePackageInfo(pkg, flags, userId);
2122        }
2123        return null;
2124    }
2125
2126    @Override
2127    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2128        if (!sUserManager.exists(userId)) return null;
2129        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2130        // writer
2131        synchronized (mPackages) {
2132            PackageParser.Package p = mPackages.get(packageName);
2133            if (DEBUG_PACKAGE_INFO) Log.v(
2134                    TAG, "getApplicationInfo " + packageName
2135                    + ": " + p);
2136            if (p != null) {
2137                PackageSetting ps = mSettings.mPackages.get(packageName);
2138                if (ps == null) return null;
2139                // Note: isEnabledLP() does not apply here - always return info
2140                return PackageParser.generateApplicationInfo(
2141                        p, flags, ps.readUserState(userId), userId);
2142            }
2143            if ("android".equals(packageName)||"system".equals(packageName)) {
2144                return mAndroidApplication;
2145            }
2146            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2147                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2148            }
2149        }
2150        return null;
2151    }
2152
2153
2154    @Override
2155    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2156        mContext.enforceCallingOrSelfPermission(
2157                android.Manifest.permission.CLEAR_APP_CACHE, null);
2158        // Queue up an async operation since clearing cache may take a little while.
2159        mHandler.post(new Runnable() {
2160            public void run() {
2161                mHandler.removeCallbacks(this);
2162                int retCode = -1;
2163                synchronized (mInstallLock) {
2164                    retCode = mInstaller.freeCache(freeStorageSize);
2165                    if (retCode < 0) {
2166                        Slog.w(TAG, "Couldn't clear application caches");
2167                    }
2168                }
2169                if (observer != null) {
2170                    try {
2171                        observer.onRemoveCompleted(null, (retCode >= 0));
2172                    } catch (RemoteException e) {
2173                        Slog.w(TAG, "RemoveException when invoking call back");
2174                    }
2175                }
2176            }
2177        });
2178    }
2179
2180    @Override
2181    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2182        mContext.enforceCallingOrSelfPermission(
2183                android.Manifest.permission.CLEAR_APP_CACHE, null);
2184        // Queue up an async operation since clearing cache may take a little while.
2185        mHandler.post(new Runnable() {
2186            public void run() {
2187                mHandler.removeCallbacks(this);
2188                int retCode = -1;
2189                synchronized (mInstallLock) {
2190                    retCode = mInstaller.freeCache(freeStorageSize);
2191                    if (retCode < 0) {
2192                        Slog.w(TAG, "Couldn't clear application caches");
2193                    }
2194                }
2195                if(pi != null) {
2196                    try {
2197                        // Callback via pending intent
2198                        int code = (retCode >= 0) ? 1 : 0;
2199                        pi.sendIntent(null, code, null,
2200                                null, null);
2201                    } catch (SendIntentException e1) {
2202                        Slog.i(TAG, "Failed to send pending intent");
2203                    }
2204                }
2205            }
2206        });
2207    }
2208
2209    void freeStorage(long freeStorageSize) throws IOException {
2210        synchronized (mInstallLock) {
2211            if (mInstaller.freeCache(freeStorageSize) < 0) {
2212                throw new IOException("Failed to free enough space");
2213            }
2214        }
2215    }
2216
2217    @Override
2218    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2219        if (!sUserManager.exists(userId)) return null;
2220        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2221        synchronized (mPackages) {
2222            PackageParser.Activity a = mActivities.mActivities.get(component);
2223
2224            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2225            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2226                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2227                if (ps == null) return null;
2228                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2229                        userId);
2230            }
2231            if (mResolveComponentName.equals(component)) {
2232                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2233                        new PackageUserState(), userId);
2234            }
2235        }
2236        return null;
2237    }
2238
2239    @Override
2240    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2241            String resolvedType) {
2242        synchronized (mPackages) {
2243            PackageParser.Activity a = mActivities.mActivities.get(component);
2244            if (a == null) {
2245                return false;
2246            }
2247            for (int i=0; i<a.intents.size(); i++) {
2248                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2249                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2250                    return true;
2251                }
2252            }
2253            return false;
2254        }
2255    }
2256
2257    @Override
2258    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2259        if (!sUserManager.exists(userId)) return null;
2260        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2261        synchronized (mPackages) {
2262            PackageParser.Activity a = mReceivers.mActivities.get(component);
2263            if (DEBUG_PACKAGE_INFO) Log.v(
2264                TAG, "getReceiverInfo " + component + ": " + a);
2265            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2266                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2267                if (ps == null) return null;
2268                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2269                        userId);
2270            }
2271        }
2272        return null;
2273    }
2274
2275    @Override
2276    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2277        if (!sUserManager.exists(userId)) return null;
2278        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2279        synchronized (mPackages) {
2280            PackageParser.Service s = mServices.mServices.get(component);
2281            if (DEBUG_PACKAGE_INFO) Log.v(
2282                TAG, "getServiceInfo " + component + ": " + s);
2283            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2284                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2285                if (ps == null) return null;
2286                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2287                        userId);
2288            }
2289        }
2290        return null;
2291    }
2292
2293    @Override
2294    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2295        if (!sUserManager.exists(userId)) return null;
2296        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2297        synchronized (mPackages) {
2298            PackageParser.Provider p = mProviders.mProviders.get(component);
2299            if (DEBUG_PACKAGE_INFO) Log.v(
2300                TAG, "getProviderInfo " + component + ": " + p);
2301            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2302                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2303                if (ps == null) return null;
2304                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2305                        userId);
2306            }
2307        }
2308        return null;
2309    }
2310
2311    @Override
2312    public String[] getSystemSharedLibraryNames() {
2313        Set<String> libSet;
2314        synchronized (mPackages) {
2315            libSet = mSharedLibraries.keySet();
2316            int size = libSet.size();
2317            if (size > 0) {
2318                String[] libs = new String[size];
2319                libSet.toArray(libs);
2320                return libs;
2321            }
2322        }
2323        return null;
2324    }
2325
2326    /**
2327     * @hide
2328     */
2329    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2330        synchronized (mPackages) {
2331            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2332            if (lib != null && lib.apk != null) {
2333                return mPackages.get(lib.apk);
2334            }
2335        }
2336        return null;
2337    }
2338
2339    @Override
2340    public FeatureInfo[] getSystemAvailableFeatures() {
2341        Collection<FeatureInfo> featSet;
2342        synchronized (mPackages) {
2343            featSet = mAvailableFeatures.values();
2344            int size = featSet.size();
2345            if (size > 0) {
2346                FeatureInfo[] features = new FeatureInfo[size+1];
2347                featSet.toArray(features);
2348                FeatureInfo fi = new FeatureInfo();
2349                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2350                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2351                features[size] = fi;
2352                return features;
2353            }
2354        }
2355        return null;
2356    }
2357
2358    @Override
2359    public boolean hasSystemFeature(String name) {
2360        synchronized (mPackages) {
2361            return mAvailableFeatures.containsKey(name);
2362        }
2363    }
2364
2365    private void checkValidCaller(int uid, int userId) {
2366        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2367            return;
2368
2369        throw new SecurityException("Caller uid=" + uid
2370                + " is not privileged to communicate with user=" + userId);
2371    }
2372
2373    @Override
2374    public int checkPermission(String permName, String pkgName) {
2375        synchronized (mPackages) {
2376            PackageParser.Package p = mPackages.get(pkgName);
2377            if (p != null && p.mExtras != null) {
2378                PackageSetting ps = (PackageSetting)p.mExtras;
2379                if (ps.sharedUser != null) {
2380                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2381                        return PackageManager.PERMISSION_GRANTED;
2382                    }
2383                } else if (ps.grantedPermissions.contains(permName)) {
2384                    return PackageManager.PERMISSION_GRANTED;
2385                }
2386            }
2387        }
2388        return PackageManager.PERMISSION_DENIED;
2389    }
2390
2391    @Override
2392    public int checkUidPermission(String permName, int uid) {
2393        synchronized (mPackages) {
2394            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2395            if (obj != null) {
2396                GrantedPermissions gp = (GrantedPermissions)obj;
2397                if (gp.grantedPermissions.contains(permName)) {
2398                    return PackageManager.PERMISSION_GRANTED;
2399                }
2400            } else {
2401                ArraySet<String> perms = mSystemPermissions.get(uid);
2402                if (perms != null && perms.contains(permName)) {
2403                    return PackageManager.PERMISSION_GRANTED;
2404                }
2405            }
2406        }
2407        return PackageManager.PERMISSION_DENIED;
2408    }
2409
2410    /**
2411     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2412     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2413     * @param checkShell TODO(yamasani):
2414     * @param message the message to log on security exception
2415     */
2416    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2417            boolean checkShell, String message) {
2418        if (userId < 0) {
2419            throw new IllegalArgumentException("Invalid userId " + userId);
2420        }
2421        if (checkShell) {
2422            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2423        }
2424        if (userId == UserHandle.getUserId(callingUid)) return;
2425        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2426            if (requireFullPermission) {
2427                mContext.enforceCallingOrSelfPermission(
2428                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2429            } else {
2430                try {
2431                    mContext.enforceCallingOrSelfPermission(
2432                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2433                } catch (SecurityException se) {
2434                    mContext.enforceCallingOrSelfPermission(
2435                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2436                }
2437            }
2438        }
2439    }
2440
2441    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2442        if (callingUid == Process.SHELL_UID) {
2443            if (userHandle >= 0
2444                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2445                throw new SecurityException("Shell does not have permission to access user "
2446                        + userHandle);
2447            } else if (userHandle < 0) {
2448                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2449                        + Debug.getCallers(3));
2450            }
2451        }
2452    }
2453
2454    private BasePermission findPermissionTreeLP(String permName) {
2455        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2456            if (permName.startsWith(bp.name) &&
2457                    permName.length() > bp.name.length() &&
2458                    permName.charAt(bp.name.length()) == '.') {
2459                return bp;
2460            }
2461        }
2462        return null;
2463    }
2464
2465    private BasePermission checkPermissionTreeLP(String permName) {
2466        if (permName != null) {
2467            BasePermission bp = findPermissionTreeLP(permName);
2468            if (bp != null) {
2469                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2470                    return bp;
2471                }
2472                throw new SecurityException("Calling uid "
2473                        + Binder.getCallingUid()
2474                        + " is not allowed to add to permission tree "
2475                        + bp.name + " owned by uid " + bp.uid);
2476            }
2477        }
2478        throw new SecurityException("No permission tree found for " + permName);
2479    }
2480
2481    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2482        if (s1 == null) {
2483            return s2 == null;
2484        }
2485        if (s2 == null) {
2486            return false;
2487        }
2488        if (s1.getClass() != s2.getClass()) {
2489            return false;
2490        }
2491        return s1.equals(s2);
2492    }
2493
2494    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2495        if (pi1.icon != pi2.icon) return false;
2496        if (pi1.logo != pi2.logo) return false;
2497        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2498        if (!compareStrings(pi1.name, pi2.name)) return false;
2499        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2500        // We'll take care of setting this one.
2501        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2502        // These are not currently stored in settings.
2503        //if (!compareStrings(pi1.group, pi2.group)) return false;
2504        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2505        //if (pi1.labelRes != pi2.labelRes) return false;
2506        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2507        return true;
2508    }
2509
2510    int permissionInfoFootprint(PermissionInfo info) {
2511        int size = info.name.length();
2512        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2513        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2514        return size;
2515    }
2516
2517    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2518        int size = 0;
2519        for (BasePermission perm : mSettings.mPermissions.values()) {
2520            if (perm.uid == tree.uid) {
2521                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2522            }
2523        }
2524        return size;
2525    }
2526
2527    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2528        // We calculate the max size of permissions defined by this uid and throw
2529        // if that plus the size of 'info' would exceed our stated maximum.
2530        if (tree.uid != Process.SYSTEM_UID) {
2531            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2532            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2533                throw new SecurityException("Permission tree size cap exceeded");
2534            }
2535        }
2536    }
2537
2538    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2539        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2540            throw new SecurityException("Label must be specified in permission");
2541        }
2542        BasePermission tree = checkPermissionTreeLP(info.name);
2543        BasePermission bp = mSettings.mPermissions.get(info.name);
2544        boolean added = bp == null;
2545        boolean changed = true;
2546        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2547        if (added) {
2548            enforcePermissionCapLocked(info, tree);
2549            bp = new BasePermission(info.name, tree.sourcePackage,
2550                    BasePermission.TYPE_DYNAMIC);
2551        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2552            throw new SecurityException(
2553                    "Not allowed to modify non-dynamic permission "
2554                    + info.name);
2555        } else {
2556            if (bp.protectionLevel == fixedLevel
2557                    && bp.perm.owner.equals(tree.perm.owner)
2558                    && bp.uid == tree.uid
2559                    && comparePermissionInfos(bp.perm.info, info)) {
2560                changed = false;
2561            }
2562        }
2563        bp.protectionLevel = fixedLevel;
2564        info = new PermissionInfo(info);
2565        info.protectionLevel = fixedLevel;
2566        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2567        bp.perm.info.packageName = tree.perm.info.packageName;
2568        bp.uid = tree.uid;
2569        if (added) {
2570            mSettings.mPermissions.put(info.name, bp);
2571        }
2572        if (changed) {
2573            if (!async) {
2574                mSettings.writeLPr();
2575            } else {
2576                scheduleWriteSettingsLocked();
2577            }
2578        }
2579        return added;
2580    }
2581
2582    @Override
2583    public boolean addPermission(PermissionInfo info) {
2584        synchronized (mPackages) {
2585            return addPermissionLocked(info, false);
2586        }
2587    }
2588
2589    @Override
2590    public boolean addPermissionAsync(PermissionInfo info) {
2591        synchronized (mPackages) {
2592            return addPermissionLocked(info, true);
2593        }
2594    }
2595
2596    @Override
2597    public void removePermission(String name) {
2598        synchronized (mPackages) {
2599            checkPermissionTreeLP(name);
2600            BasePermission bp = mSettings.mPermissions.get(name);
2601            if (bp != null) {
2602                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2603                    throw new SecurityException(
2604                            "Not allowed to modify non-dynamic permission "
2605                            + name);
2606                }
2607                mSettings.mPermissions.remove(name);
2608                mSettings.writeLPr();
2609            }
2610        }
2611    }
2612
2613    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2614        int index = pkg.requestedPermissions.indexOf(bp.name);
2615        if (index == -1) {
2616            throw new SecurityException("Package " + pkg.packageName
2617                    + " has not requested permission " + bp.name);
2618        }
2619        boolean isNormal =
2620                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2621                        == PermissionInfo.PROTECTION_NORMAL);
2622        boolean isDangerous =
2623                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2624                        == PermissionInfo.PROTECTION_DANGEROUS);
2625        boolean isDevelopment =
2626                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2627
2628        if (!isNormal && !isDangerous && !isDevelopment) {
2629            throw new SecurityException("Permission " + bp.name
2630                    + " is not a changeable permission type");
2631        }
2632
2633        if (isNormal || isDangerous) {
2634            if (pkg.requestedPermissionsRequired.get(index)) {
2635                throw new SecurityException("Can't change " + bp.name
2636                        + ". It is required by the application");
2637            }
2638        }
2639    }
2640
2641    @Override
2642    public void grantPermission(String packageName, String permissionName) {
2643        mContext.enforceCallingOrSelfPermission(
2644                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2645        synchronized (mPackages) {
2646            final PackageParser.Package pkg = mPackages.get(packageName);
2647            if (pkg == null) {
2648                throw new IllegalArgumentException("Unknown package: " + packageName);
2649            }
2650            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2651            if (bp == null) {
2652                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2653            }
2654
2655            checkGrantRevokePermissions(pkg, bp);
2656
2657            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2658            if (ps == null) {
2659                return;
2660            }
2661            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2662            if (gp.grantedPermissions.add(permissionName)) {
2663                if (ps.haveGids) {
2664                    gp.gids = appendInts(gp.gids, bp.gids);
2665                }
2666                mSettings.writeLPr();
2667            }
2668        }
2669    }
2670
2671    @Override
2672    public void revokePermission(String packageName, String permissionName) {
2673        int changedAppId = -1;
2674
2675        synchronized (mPackages) {
2676            final PackageParser.Package pkg = mPackages.get(packageName);
2677            if (pkg == null) {
2678                throw new IllegalArgumentException("Unknown package: " + packageName);
2679            }
2680            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2681                mContext.enforceCallingOrSelfPermission(
2682                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2683            }
2684            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2685            if (bp == null) {
2686                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2687            }
2688
2689            checkGrantRevokePermissions(pkg, bp);
2690
2691            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2692            if (ps == null) {
2693                return;
2694            }
2695            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2696            if (gp.grantedPermissions.remove(permissionName)) {
2697                gp.grantedPermissions.remove(permissionName);
2698                if (ps.haveGids) {
2699                    gp.gids = removeInts(gp.gids, bp.gids);
2700                }
2701                mSettings.writeLPr();
2702                changedAppId = ps.appId;
2703            }
2704        }
2705
2706        if (changedAppId >= 0) {
2707            // We changed the perm on someone, kill its processes.
2708            IActivityManager am = ActivityManagerNative.getDefault();
2709            if (am != null) {
2710                final int callingUserId = UserHandle.getCallingUserId();
2711                final long ident = Binder.clearCallingIdentity();
2712                try {
2713                    //XXX we should only revoke for the calling user's app permissions,
2714                    // but for now we impact all users.
2715                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2716                    //        "revoke " + permissionName);
2717                    int[] users = sUserManager.getUserIds();
2718                    for (int user : users) {
2719                        am.killUid(UserHandle.getUid(user, changedAppId),
2720                                "revoke " + permissionName);
2721                    }
2722                } catch (RemoteException e) {
2723                } finally {
2724                    Binder.restoreCallingIdentity(ident);
2725                }
2726            }
2727        }
2728    }
2729
2730    @Override
2731    public boolean isProtectedBroadcast(String actionName) {
2732        synchronized (mPackages) {
2733            return mProtectedBroadcasts.contains(actionName);
2734        }
2735    }
2736
2737    @Override
2738    public int checkSignatures(String pkg1, String pkg2) {
2739        synchronized (mPackages) {
2740            final PackageParser.Package p1 = mPackages.get(pkg1);
2741            final PackageParser.Package p2 = mPackages.get(pkg2);
2742            if (p1 == null || p1.mExtras == null
2743                    || p2 == null || p2.mExtras == null) {
2744                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2745            }
2746            return compareSignatures(p1.mSignatures, p2.mSignatures);
2747        }
2748    }
2749
2750    @Override
2751    public int checkUidSignatures(int uid1, int uid2) {
2752        // Map to base uids.
2753        uid1 = UserHandle.getAppId(uid1);
2754        uid2 = UserHandle.getAppId(uid2);
2755        // reader
2756        synchronized (mPackages) {
2757            Signature[] s1;
2758            Signature[] s2;
2759            Object obj = mSettings.getUserIdLPr(uid1);
2760            if (obj != null) {
2761                if (obj instanceof SharedUserSetting) {
2762                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2763                } else if (obj instanceof PackageSetting) {
2764                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2765                } else {
2766                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2767                }
2768            } else {
2769                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2770            }
2771            obj = mSettings.getUserIdLPr(uid2);
2772            if (obj != null) {
2773                if (obj instanceof SharedUserSetting) {
2774                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2775                } else if (obj instanceof PackageSetting) {
2776                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2777                } else {
2778                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2779                }
2780            } else {
2781                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2782            }
2783            return compareSignatures(s1, s2);
2784        }
2785    }
2786
2787    /**
2788     * Compares two sets of signatures. Returns:
2789     * <br />
2790     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2791     * <br />
2792     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2793     * <br />
2794     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2795     * <br />
2796     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2797     * <br />
2798     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2799     */
2800    static int compareSignatures(Signature[] s1, Signature[] s2) {
2801        if (s1 == null) {
2802            return s2 == null
2803                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2804                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2805        }
2806
2807        if (s2 == null) {
2808            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2809        }
2810
2811        if (s1.length != s2.length) {
2812            return PackageManager.SIGNATURE_NO_MATCH;
2813        }
2814
2815        // Since both signature sets are of size 1, we can compare without HashSets.
2816        if (s1.length == 1) {
2817            return s1[0].equals(s2[0]) ?
2818                    PackageManager.SIGNATURE_MATCH :
2819                    PackageManager.SIGNATURE_NO_MATCH;
2820        }
2821
2822        ArraySet<Signature> set1 = new ArraySet<Signature>();
2823        for (Signature sig : s1) {
2824            set1.add(sig);
2825        }
2826        ArraySet<Signature> set2 = new ArraySet<Signature>();
2827        for (Signature sig : s2) {
2828            set2.add(sig);
2829        }
2830        // Make sure s2 contains all signatures in s1.
2831        if (set1.equals(set2)) {
2832            return PackageManager.SIGNATURE_MATCH;
2833        }
2834        return PackageManager.SIGNATURE_NO_MATCH;
2835    }
2836
2837    /**
2838     * If the database version for this type of package (internal storage or
2839     * external storage) is less than the version where package signatures
2840     * were updated, return true.
2841     */
2842    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2843        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2844                DatabaseVersion.SIGNATURE_END_ENTITY))
2845                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2846                        DatabaseVersion.SIGNATURE_END_ENTITY));
2847    }
2848
2849    /**
2850     * Used for backward compatibility to make sure any packages with
2851     * certificate chains get upgraded to the new style. {@code existingSigs}
2852     * will be in the old format (since they were stored on disk from before the
2853     * system upgrade) and {@code scannedSigs} will be in the newer format.
2854     */
2855    private int compareSignaturesCompat(PackageSignatures existingSigs,
2856            PackageParser.Package scannedPkg) {
2857        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2858            return PackageManager.SIGNATURE_NO_MATCH;
2859        }
2860
2861        ArraySet<Signature> existingSet = new ArraySet<Signature>();
2862        for (Signature sig : existingSigs.mSignatures) {
2863            existingSet.add(sig);
2864        }
2865        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
2866        for (Signature sig : scannedPkg.mSignatures) {
2867            try {
2868                Signature[] chainSignatures = sig.getChainSignatures();
2869                for (Signature chainSig : chainSignatures) {
2870                    scannedCompatSet.add(chainSig);
2871                }
2872            } catch (CertificateEncodingException e) {
2873                scannedCompatSet.add(sig);
2874            }
2875        }
2876        /*
2877         * Make sure the expanded scanned set contains all signatures in the
2878         * existing one.
2879         */
2880        if (scannedCompatSet.equals(existingSet)) {
2881            // Migrate the old signatures to the new scheme.
2882            existingSigs.assignSignatures(scannedPkg.mSignatures);
2883            // The new KeySets will be re-added later in the scanning process.
2884            synchronized (mPackages) {
2885                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2886            }
2887            return PackageManager.SIGNATURE_MATCH;
2888        }
2889        return PackageManager.SIGNATURE_NO_MATCH;
2890    }
2891
2892    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2893        if (isExternal(scannedPkg)) {
2894            return mSettings.isExternalDatabaseVersionOlderThan(
2895                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
2896        } else {
2897            return mSettings.isInternalDatabaseVersionOlderThan(
2898                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
2899        }
2900    }
2901
2902    private int compareSignaturesRecover(PackageSignatures existingSigs,
2903            PackageParser.Package scannedPkg) {
2904        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
2905            return PackageManager.SIGNATURE_NO_MATCH;
2906        }
2907
2908        String msg = null;
2909        try {
2910            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
2911                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
2912                        + scannedPkg.packageName);
2913                return PackageManager.SIGNATURE_MATCH;
2914            }
2915        } catch (CertificateException e) {
2916            msg = e.getMessage();
2917        }
2918
2919        logCriticalInfo(Log.INFO,
2920                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
2921        return PackageManager.SIGNATURE_NO_MATCH;
2922    }
2923
2924    @Override
2925    public String[] getPackagesForUid(int uid) {
2926        uid = UserHandle.getAppId(uid);
2927        // reader
2928        synchronized (mPackages) {
2929            Object obj = mSettings.getUserIdLPr(uid);
2930            if (obj instanceof SharedUserSetting) {
2931                final SharedUserSetting sus = (SharedUserSetting) obj;
2932                final int N = sus.packages.size();
2933                final String[] res = new String[N];
2934                final Iterator<PackageSetting> it = sus.packages.iterator();
2935                int i = 0;
2936                while (it.hasNext()) {
2937                    res[i++] = it.next().name;
2938                }
2939                return res;
2940            } else if (obj instanceof PackageSetting) {
2941                final PackageSetting ps = (PackageSetting) obj;
2942                return new String[] { ps.name };
2943            }
2944        }
2945        return null;
2946    }
2947
2948    @Override
2949    public String getNameForUid(int uid) {
2950        // reader
2951        synchronized (mPackages) {
2952            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2953            if (obj instanceof SharedUserSetting) {
2954                final SharedUserSetting sus = (SharedUserSetting) obj;
2955                return sus.name + ":" + sus.userId;
2956            } else if (obj instanceof PackageSetting) {
2957                final PackageSetting ps = (PackageSetting) obj;
2958                return ps.name;
2959            }
2960        }
2961        return null;
2962    }
2963
2964    @Override
2965    public int getUidForSharedUser(String sharedUserName) {
2966        if(sharedUserName == null) {
2967            return -1;
2968        }
2969        // reader
2970        synchronized (mPackages) {
2971            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
2972            if (suid == null) {
2973                return -1;
2974            }
2975            return suid.userId;
2976        }
2977    }
2978
2979    @Override
2980    public int getFlagsForUid(int uid) {
2981        synchronized (mPackages) {
2982            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2983            if (obj instanceof SharedUserSetting) {
2984                final SharedUserSetting sus = (SharedUserSetting) obj;
2985                return sus.pkgFlags;
2986            } else if (obj instanceof PackageSetting) {
2987                final PackageSetting ps = (PackageSetting) obj;
2988                return ps.pkgFlags;
2989            }
2990        }
2991        return 0;
2992    }
2993
2994    @Override
2995    public int getPrivateFlagsForUid(int uid) {
2996        synchronized (mPackages) {
2997            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2998            if (obj instanceof SharedUserSetting) {
2999                final SharedUserSetting sus = (SharedUserSetting) obj;
3000                return sus.pkgPrivateFlags;
3001            } else if (obj instanceof PackageSetting) {
3002                final PackageSetting ps = (PackageSetting) obj;
3003                return ps.pkgPrivateFlags;
3004            }
3005        }
3006        return 0;
3007    }
3008
3009    @Override
3010    public boolean isUidPrivileged(int uid) {
3011        uid = UserHandle.getAppId(uid);
3012        // reader
3013        synchronized (mPackages) {
3014            Object obj = mSettings.getUserIdLPr(uid);
3015            if (obj instanceof SharedUserSetting) {
3016                final SharedUserSetting sus = (SharedUserSetting) obj;
3017                final Iterator<PackageSetting> it = sus.packages.iterator();
3018                while (it.hasNext()) {
3019                    if (it.next().isPrivileged()) {
3020                        return true;
3021                    }
3022                }
3023            } else if (obj instanceof PackageSetting) {
3024                final PackageSetting ps = (PackageSetting) obj;
3025                return ps.isPrivileged();
3026            }
3027        }
3028        return false;
3029    }
3030
3031    @Override
3032    public String[] getAppOpPermissionPackages(String permissionName) {
3033        synchronized (mPackages) {
3034            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3035            if (pkgs == null) {
3036                return null;
3037            }
3038            return pkgs.toArray(new String[pkgs.size()]);
3039        }
3040    }
3041
3042    @Override
3043    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3044            int flags, int userId) {
3045        if (!sUserManager.exists(userId)) return null;
3046        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3047        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3048        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3049    }
3050
3051    @Override
3052    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3053            IntentFilter filter, int match, ComponentName activity) {
3054        final int userId = UserHandle.getCallingUserId();
3055        if (DEBUG_PREFERRED) {
3056            Log.v(TAG, "setLastChosenActivity intent=" + intent
3057                + " resolvedType=" + resolvedType
3058                + " flags=" + flags
3059                + " filter=" + filter
3060                + " match=" + match
3061                + " activity=" + activity);
3062            filter.dump(new PrintStreamPrinter(System.out), "    ");
3063        }
3064        intent.setComponent(null);
3065        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3066        // Find any earlier preferred or last chosen entries and nuke them
3067        findPreferredActivity(intent, resolvedType,
3068                flags, query, 0, false, true, false, userId);
3069        // Add the new activity as the last chosen for this filter
3070        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3071                "Setting last chosen");
3072    }
3073
3074    @Override
3075    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3076        final int userId = UserHandle.getCallingUserId();
3077        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3078        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3079        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3080                false, false, false, userId);
3081    }
3082
3083    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3084            int flags, List<ResolveInfo> query, int userId) {
3085        if (query != null) {
3086            final int N = query.size();
3087            if (N == 1) {
3088                return query.get(0);
3089            } else if (N > 1) {
3090                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3091                // If there is more than one activity with the same priority,
3092                // then let the user decide between them.
3093                ResolveInfo r0 = query.get(0);
3094                ResolveInfo r1 = query.get(1);
3095                if (DEBUG_INTENT_MATCHING || debug) {
3096                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3097                            + r1.activityInfo.name + "=" + r1.priority);
3098                }
3099                // If the first activity has a higher priority, or a different
3100                // default, then it is always desireable to pick it.
3101                if (r0.priority != r1.priority
3102                        || r0.preferredOrder != r1.preferredOrder
3103                        || r0.isDefault != r1.isDefault) {
3104                    return query.get(0);
3105                }
3106                // If we have saved a preference for a preferred activity for
3107                // this Intent, use that.
3108                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3109                        flags, query, r0.priority, true, false, debug, userId);
3110                if (ri != null) {
3111                    return ri;
3112                }
3113                if (userId != 0) {
3114                    ri = new ResolveInfo(mResolveInfo);
3115                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3116                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3117                            ri.activityInfo.applicationInfo);
3118                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3119                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3120                    return ri;
3121                }
3122                return mResolveInfo;
3123            }
3124        }
3125        return null;
3126    }
3127
3128    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3129            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3130        final int N = query.size();
3131        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3132                .get(userId);
3133        // Get the list of persistent preferred activities that handle the intent
3134        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3135        List<PersistentPreferredActivity> pprefs = ppir != null
3136                ? ppir.queryIntent(intent, resolvedType,
3137                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3138                : null;
3139        if (pprefs != null && pprefs.size() > 0) {
3140            final int M = pprefs.size();
3141            for (int i=0; i<M; i++) {
3142                final PersistentPreferredActivity ppa = pprefs.get(i);
3143                if (DEBUG_PREFERRED || debug) {
3144                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3145                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3146                            + "\n  component=" + ppa.mComponent);
3147                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3148                }
3149                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3150                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3151                if (DEBUG_PREFERRED || debug) {
3152                    Slog.v(TAG, "Found persistent preferred activity:");
3153                    if (ai != null) {
3154                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3155                    } else {
3156                        Slog.v(TAG, "  null");
3157                    }
3158                }
3159                if (ai == null) {
3160                    // This previously registered persistent preferred activity
3161                    // component is no longer known. Ignore it and do NOT remove it.
3162                    continue;
3163                }
3164                for (int j=0; j<N; j++) {
3165                    final ResolveInfo ri = query.get(j);
3166                    if (!ri.activityInfo.applicationInfo.packageName
3167                            .equals(ai.applicationInfo.packageName)) {
3168                        continue;
3169                    }
3170                    if (!ri.activityInfo.name.equals(ai.name)) {
3171                        continue;
3172                    }
3173                    //  Found a persistent preference that can handle the intent.
3174                    if (DEBUG_PREFERRED || debug) {
3175                        Slog.v(TAG, "Returning persistent preferred activity: " +
3176                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3177                    }
3178                    return ri;
3179                }
3180            }
3181        }
3182        return null;
3183    }
3184
3185    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3186            List<ResolveInfo> query, int priority, boolean always,
3187            boolean removeMatches, boolean debug, int userId) {
3188        if (!sUserManager.exists(userId)) return null;
3189        // writer
3190        synchronized (mPackages) {
3191            if (intent.getSelector() != null) {
3192                intent = intent.getSelector();
3193            }
3194            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3195
3196            // Try to find a matching persistent preferred activity.
3197            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3198                    debug, userId);
3199
3200            // If a persistent preferred activity matched, use it.
3201            if (pri != null) {
3202                return pri;
3203            }
3204
3205            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3206            // Get the list of preferred activities that handle the intent
3207            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3208            List<PreferredActivity> prefs = pir != null
3209                    ? pir.queryIntent(intent, resolvedType,
3210                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3211                    : null;
3212            if (prefs != null && prefs.size() > 0) {
3213                boolean changed = false;
3214                try {
3215                    // First figure out how good the original match set is.
3216                    // We will only allow preferred activities that came
3217                    // from the same match quality.
3218                    int match = 0;
3219
3220                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3221
3222                    final int N = query.size();
3223                    for (int j=0; j<N; j++) {
3224                        final ResolveInfo ri = query.get(j);
3225                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3226                                + ": 0x" + Integer.toHexString(match));
3227                        if (ri.match > match) {
3228                            match = ri.match;
3229                        }
3230                    }
3231
3232                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3233                            + Integer.toHexString(match));
3234
3235                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3236                    final int M = prefs.size();
3237                    for (int i=0; i<M; i++) {
3238                        final PreferredActivity pa = prefs.get(i);
3239                        if (DEBUG_PREFERRED || debug) {
3240                            Slog.v(TAG, "Checking PreferredActivity ds="
3241                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3242                                    + "\n  component=" + pa.mPref.mComponent);
3243                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3244                        }
3245                        if (pa.mPref.mMatch != match) {
3246                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3247                                    + Integer.toHexString(pa.mPref.mMatch));
3248                            continue;
3249                        }
3250                        // If it's not an "always" type preferred activity and that's what we're
3251                        // looking for, skip it.
3252                        if (always && !pa.mPref.mAlways) {
3253                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3254                            continue;
3255                        }
3256                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3257                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3258                        if (DEBUG_PREFERRED || debug) {
3259                            Slog.v(TAG, "Found preferred activity:");
3260                            if (ai != null) {
3261                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3262                            } else {
3263                                Slog.v(TAG, "  null");
3264                            }
3265                        }
3266                        if (ai == null) {
3267                            // This previously registered preferred activity
3268                            // component is no longer known.  Most likely an update
3269                            // to the app was installed and in the new version this
3270                            // component no longer exists.  Clean it up by removing
3271                            // it from the preferred activities list, and skip it.
3272                            Slog.w(TAG, "Removing dangling preferred activity: "
3273                                    + pa.mPref.mComponent);
3274                            pir.removeFilter(pa);
3275                            changed = true;
3276                            continue;
3277                        }
3278                        for (int j=0; j<N; j++) {
3279                            final ResolveInfo ri = query.get(j);
3280                            if (!ri.activityInfo.applicationInfo.packageName
3281                                    .equals(ai.applicationInfo.packageName)) {
3282                                continue;
3283                            }
3284                            if (!ri.activityInfo.name.equals(ai.name)) {
3285                                continue;
3286                            }
3287
3288                            if (removeMatches) {
3289                                pir.removeFilter(pa);
3290                                changed = true;
3291                                if (DEBUG_PREFERRED) {
3292                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3293                                }
3294                                break;
3295                            }
3296
3297                            // Okay we found a previously set preferred or last chosen app.
3298                            // If the result set is different from when this
3299                            // was created, we need to clear it and re-ask the
3300                            // user their preference, if we're looking for an "always" type entry.
3301                            if (always && !pa.mPref.sameSet(query)) {
3302                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3303                                        + intent + " type " + resolvedType);
3304                                if (DEBUG_PREFERRED) {
3305                                    Slog.v(TAG, "Removing preferred activity since set changed "
3306                                            + pa.mPref.mComponent);
3307                                }
3308                                pir.removeFilter(pa);
3309                                // Re-add the filter as a "last chosen" entry (!always)
3310                                PreferredActivity lastChosen = new PreferredActivity(
3311                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3312                                pir.addFilter(lastChosen);
3313                                changed = true;
3314                                return null;
3315                            }
3316
3317                            // Yay! Either the set matched or we're looking for the last chosen
3318                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3319                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3320                            return ri;
3321                        }
3322                    }
3323                } finally {
3324                    if (changed) {
3325                        if (DEBUG_PREFERRED) {
3326                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3327                        }
3328                        scheduleWritePackageRestrictionsLocked(userId);
3329                    }
3330                }
3331            }
3332        }
3333        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3334        return null;
3335    }
3336
3337    /*
3338     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3339     */
3340    @Override
3341    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3342            int targetUserId) {
3343        mContext.enforceCallingOrSelfPermission(
3344                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3345        List<CrossProfileIntentFilter> matches =
3346                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3347        if (matches != null) {
3348            int size = matches.size();
3349            for (int i = 0; i < size; i++) {
3350                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3351            }
3352        }
3353        return false;
3354    }
3355
3356    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3357            String resolvedType, int userId) {
3358        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3359        if (resolver != null) {
3360            return resolver.queryIntent(intent, resolvedType, false, userId);
3361        }
3362        return null;
3363    }
3364
3365    @Override
3366    public List<ResolveInfo> queryIntentActivities(Intent intent,
3367            String resolvedType, int flags, int userId) {
3368        if (!sUserManager.exists(userId)) return Collections.emptyList();
3369        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3370        ComponentName comp = intent.getComponent();
3371        if (comp == null) {
3372            if (intent.getSelector() != null) {
3373                intent = intent.getSelector();
3374                comp = intent.getComponent();
3375            }
3376        }
3377
3378        if (comp != null) {
3379            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3380            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3381            if (ai != null) {
3382                final ResolveInfo ri = new ResolveInfo();
3383                ri.activityInfo = ai;
3384                list.add(ri);
3385            }
3386            return list;
3387        }
3388
3389        // reader
3390        synchronized (mPackages) {
3391            final String pkgName = intent.getPackage();
3392            if (pkgName == null) {
3393                List<CrossProfileIntentFilter> matchingFilters =
3394                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3395                // Check for results that need to skip the current profile.
3396                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3397                        resolvedType, flags, userId);
3398                if (resolveInfo != null) {
3399                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3400                    result.add(resolveInfo);
3401                    return result;
3402                }
3403                // Check for cross profile results.
3404                resolveInfo = queryCrossProfileIntents(
3405                        matchingFilters, intent, resolvedType, flags, userId);
3406
3407                // Check for results in the current profile.
3408                List<ResolveInfo> result = mActivities.queryIntent(
3409                        intent, resolvedType, flags, userId);
3410                if (resolveInfo != null) {
3411                    result.add(resolveInfo);
3412                    Collections.sort(result, mResolvePrioritySorter);
3413                }
3414                return result;
3415            }
3416            final PackageParser.Package pkg = mPackages.get(pkgName);
3417            if (pkg != null) {
3418                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3419                        pkg.activities, userId);
3420            }
3421            return new ArrayList<ResolveInfo>();
3422        }
3423    }
3424
3425    private ResolveInfo querySkipCurrentProfileIntents(
3426            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3427            int flags, int sourceUserId) {
3428        if (matchingFilters != null) {
3429            int size = matchingFilters.size();
3430            for (int i = 0; i < size; i ++) {
3431                CrossProfileIntentFilter filter = matchingFilters.get(i);
3432                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3433                    // Checking if there are activities in the target user that can handle the
3434                    // intent.
3435                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3436                            flags, sourceUserId);
3437                    if (resolveInfo != null) {
3438                        return resolveInfo;
3439                    }
3440                }
3441            }
3442        }
3443        return null;
3444    }
3445
3446    // Return matching ResolveInfo if any for skip current profile intent filters.
3447    private ResolveInfo queryCrossProfileIntents(
3448            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3449            int flags, int sourceUserId) {
3450        if (matchingFilters != null) {
3451            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3452            // match the same intent. For performance reasons, it is better not to
3453            // run queryIntent twice for the same userId
3454            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3455            int size = matchingFilters.size();
3456            for (int i = 0; i < size; i++) {
3457                CrossProfileIntentFilter filter = matchingFilters.get(i);
3458                int targetUserId = filter.getTargetUserId();
3459                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3460                        && !alreadyTriedUserIds.get(targetUserId)) {
3461                    // Checking if there are activities in the target user that can handle the
3462                    // intent.
3463                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3464                            flags, sourceUserId);
3465                    if (resolveInfo != null) return resolveInfo;
3466                    alreadyTriedUserIds.put(targetUserId, true);
3467                }
3468            }
3469        }
3470        return null;
3471    }
3472
3473    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3474            String resolvedType, int flags, int sourceUserId) {
3475        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3476                resolvedType, flags, filter.getTargetUserId());
3477        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3478            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3479        }
3480        return null;
3481    }
3482
3483    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3484            int sourceUserId, int targetUserId) {
3485        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3486        String className;
3487        if (targetUserId == UserHandle.USER_OWNER) {
3488            className = FORWARD_INTENT_TO_USER_OWNER;
3489        } else {
3490            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3491        }
3492        ComponentName forwardingActivityComponentName = new ComponentName(
3493                mAndroidApplication.packageName, className);
3494        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3495                sourceUserId);
3496        if (targetUserId == UserHandle.USER_OWNER) {
3497            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3498            forwardingResolveInfo.noResourceId = true;
3499        }
3500        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3501        forwardingResolveInfo.priority = 0;
3502        forwardingResolveInfo.preferredOrder = 0;
3503        forwardingResolveInfo.match = 0;
3504        forwardingResolveInfo.isDefault = true;
3505        forwardingResolveInfo.filter = filter;
3506        forwardingResolveInfo.targetUserId = targetUserId;
3507        return forwardingResolveInfo;
3508    }
3509
3510    @Override
3511    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3512            Intent[] specifics, String[] specificTypes, Intent intent,
3513            String resolvedType, int flags, int userId) {
3514        if (!sUserManager.exists(userId)) return Collections.emptyList();
3515        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3516                false, "query intent activity options");
3517        final String resultsAction = intent.getAction();
3518
3519        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3520                | PackageManager.GET_RESOLVED_FILTER, userId);
3521
3522        if (DEBUG_INTENT_MATCHING) {
3523            Log.v(TAG, "Query " + intent + ": " + results);
3524        }
3525
3526        int specificsPos = 0;
3527        int N;
3528
3529        // todo: note that the algorithm used here is O(N^2).  This
3530        // isn't a problem in our current environment, but if we start running
3531        // into situations where we have more than 5 or 10 matches then this
3532        // should probably be changed to something smarter...
3533
3534        // First we go through and resolve each of the specific items
3535        // that were supplied, taking care of removing any corresponding
3536        // duplicate items in the generic resolve list.
3537        if (specifics != null) {
3538            for (int i=0; i<specifics.length; i++) {
3539                final Intent sintent = specifics[i];
3540                if (sintent == null) {
3541                    continue;
3542                }
3543
3544                if (DEBUG_INTENT_MATCHING) {
3545                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3546                }
3547
3548                String action = sintent.getAction();
3549                if (resultsAction != null && resultsAction.equals(action)) {
3550                    // If this action was explicitly requested, then don't
3551                    // remove things that have it.
3552                    action = null;
3553                }
3554
3555                ResolveInfo ri = null;
3556                ActivityInfo ai = null;
3557
3558                ComponentName comp = sintent.getComponent();
3559                if (comp == null) {
3560                    ri = resolveIntent(
3561                        sintent,
3562                        specificTypes != null ? specificTypes[i] : null,
3563                            flags, userId);
3564                    if (ri == null) {
3565                        continue;
3566                    }
3567                    if (ri == mResolveInfo) {
3568                        // ACK!  Must do something better with this.
3569                    }
3570                    ai = ri.activityInfo;
3571                    comp = new ComponentName(ai.applicationInfo.packageName,
3572                            ai.name);
3573                } else {
3574                    ai = getActivityInfo(comp, flags, userId);
3575                    if (ai == null) {
3576                        continue;
3577                    }
3578                }
3579
3580                // Look for any generic query activities that are duplicates
3581                // of this specific one, and remove them from the results.
3582                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3583                N = results.size();
3584                int j;
3585                for (j=specificsPos; j<N; j++) {
3586                    ResolveInfo sri = results.get(j);
3587                    if ((sri.activityInfo.name.equals(comp.getClassName())
3588                            && sri.activityInfo.applicationInfo.packageName.equals(
3589                                    comp.getPackageName()))
3590                        || (action != null && sri.filter.matchAction(action))) {
3591                        results.remove(j);
3592                        if (DEBUG_INTENT_MATCHING) Log.v(
3593                            TAG, "Removing duplicate item from " + j
3594                            + " due to specific " + specificsPos);
3595                        if (ri == null) {
3596                            ri = sri;
3597                        }
3598                        j--;
3599                        N--;
3600                    }
3601                }
3602
3603                // Add this specific item to its proper place.
3604                if (ri == null) {
3605                    ri = new ResolveInfo();
3606                    ri.activityInfo = ai;
3607                }
3608                results.add(specificsPos, ri);
3609                ri.specificIndex = i;
3610                specificsPos++;
3611            }
3612        }
3613
3614        // Now we go through the remaining generic results and remove any
3615        // duplicate actions that are found here.
3616        N = results.size();
3617        for (int i=specificsPos; i<N-1; i++) {
3618            final ResolveInfo rii = results.get(i);
3619            if (rii.filter == null) {
3620                continue;
3621            }
3622
3623            // Iterate over all of the actions of this result's intent
3624            // filter...  typically this should be just one.
3625            final Iterator<String> it = rii.filter.actionsIterator();
3626            if (it == null) {
3627                continue;
3628            }
3629            while (it.hasNext()) {
3630                final String action = it.next();
3631                if (resultsAction != null && resultsAction.equals(action)) {
3632                    // If this action was explicitly requested, then don't
3633                    // remove things that have it.
3634                    continue;
3635                }
3636                for (int j=i+1; j<N; j++) {
3637                    final ResolveInfo rij = results.get(j);
3638                    if (rij.filter != null && rij.filter.hasAction(action)) {
3639                        results.remove(j);
3640                        if (DEBUG_INTENT_MATCHING) Log.v(
3641                            TAG, "Removing duplicate item from " + j
3642                            + " due to action " + action + " at " + i);
3643                        j--;
3644                        N--;
3645                    }
3646                }
3647            }
3648
3649            // If the caller didn't request filter information, drop it now
3650            // so we don't have to marshall/unmarshall it.
3651            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3652                rii.filter = null;
3653            }
3654        }
3655
3656        // Filter out the caller activity if so requested.
3657        if (caller != null) {
3658            N = results.size();
3659            for (int i=0; i<N; i++) {
3660                ActivityInfo ainfo = results.get(i).activityInfo;
3661                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3662                        && caller.getClassName().equals(ainfo.name)) {
3663                    results.remove(i);
3664                    break;
3665                }
3666            }
3667        }
3668
3669        // If the caller didn't request filter information,
3670        // drop them now so we don't have to
3671        // marshall/unmarshall it.
3672        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3673            N = results.size();
3674            for (int i=0; i<N; i++) {
3675                results.get(i).filter = null;
3676            }
3677        }
3678
3679        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3680        return results;
3681    }
3682
3683    @Override
3684    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3685            int userId) {
3686        if (!sUserManager.exists(userId)) return Collections.emptyList();
3687        ComponentName comp = intent.getComponent();
3688        if (comp == null) {
3689            if (intent.getSelector() != null) {
3690                intent = intent.getSelector();
3691                comp = intent.getComponent();
3692            }
3693        }
3694        if (comp != null) {
3695            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3696            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3697            if (ai != null) {
3698                ResolveInfo ri = new ResolveInfo();
3699                ri.activityInfo = ai;
3700                list.add(ri);
3701            }
3702            return list;
3703        }
3704
3705        // reader
3706        synchronized (mPackages) {
3707            String pkgName = intent.getPackage();
3708            if (pkgName == null) {
3709                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3710            }
3711            final PackageParser.Package pkg = mPackages.get(pkgName);
3712            if (pkg != null) {
3713                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3714                        userId);
3715            }
3716            return null;
3717        }
3718    }
3719
3720    @Override
3721    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3722        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3723        if (!sUserManager.exists(userId)) return null;
3724        if (query != null) {
3725            if (query.size() >= 1) {
3726                // If there is more than one service with the same priority,
3727                // just arbitrarily pick the first one.
3728                return query.get(0);
3729            }
3730        }
3731        return null;
3732    }
3733
3734    @Override
3735    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3736            int userId) {
3737        if (!sUserManager.exists(userId)) return Collections.emptyList();
3738        ComponentName comp = intent.getComponent();
3739        if (comp == null) {
3740            if (intent.getSelector() != null) {
3741                intent = intent.getSelector();
3742                comp = intent.getComponent();
3743            }
3744        }
3745        if (comp != null) {
3746            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3747            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3748            if (si != null) {
3749                final ResolveInfo ri = new ResolveInfo();
3750                ri.serviceInfo = si;
3751                list.add(ri);
3752            }
3753            return list;
3754        }
3755
3756        // reader
3757        synchronized (mPackages) {
3758            String pkgName = intent.getPackage();
3759            if (pkgName == null) {
3760                return mServices.queryIntent(intent, resolvedType, flags, userId);
3761            }
3762            final PackageParser.Package pkg = mPackages.get(pkgName);
3763            if (pkg != null) {
3764                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3765                        userId);
3766            }
3767            return null;
3768        }
3769    }
3770
3771    @Override
3772    public List<ResolveInfo> queryIntentContentProviders(
3773            Intent intent, String resolvedType, int flags, int userId) {
3774        if (!sUserManager.exists(userId)) return Collections.emptyList();
3775        ComponentName comp = intent.getComponent();
3776        if (comp == null) {
3777            if (intent.getSelector() != null) {
3778                intent = intent.getSelector();
3779                comp = intent.getComponent();
3780            }
3781        }
3782        if (comp != null) {
3783            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3784            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3785            if (pi != null) {
3786                final ResolveInfo ri = new ResolveInfo();
3787                ri.providerInfo = pi;
3788                list.add(ri);
3789            }
3790            return list;
3791        }
3792
3793        // reader
3794        synchronized (mPackages) {
3795            String pkgName = intent.getPackage();
3796            if (pkgName == null) {
3797                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3798            }
3799            final PackageParser.Package pkg = mPackages.get(pkgName);
3800            if (pkg != null) {
3801                return mProviders.queryIntentForPackage(
3802                        intent, resolvedType, flags, pkg.providers, userId);
3803            }
3804            return null;
3805        }
3806    }
3807
3808    @Override
3809    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3810        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3811
3812        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3813
3814        // writer
3815        synchronized (mPackages) {
3816            ArrayList<PackageInfo> list;
3817            if (listUninstalled) {
3818                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3819                for (PackageSetting ps : mSettings.mPackages.values()) {
3820                    PackageInfo pi;
3821                    if (ps.pkg != null) {
3822                        pi = generatePackageInfo(ps.pkg, flags, userId);
3823                    } else {
3824                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3825                    }
3826                    if (pi != null) {
3827                        list.add(pi);
3828                    }
3829                }
3830            } else {
3831                list = new ArrayList<PackageInfo>(mPackages.size());
3832                for (PackageParser.Package p : mPackages.values()) {
3833                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3834                    if (pi != null) {
3835                        list.add(pi);
3836                    }
3837                }
3838            }
3839
3840            return new ParceledListSlice<PackageInfo>(list);
3841        }
3842    }
3843
3844    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3845            String[] permissions, boolean[] tmp, int flags, int userId) {
3846        int numMatch = 0;
3847        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3848        for (int i=0; i<permissions.length; i++) {
3849            if (gp.grantedPermissions.contains(permissions[i])) {
3850                tmp[i] = true;
3851                numMatch++;
3852            } else {
3853                tmp[i] = false;
3854            }
3855        }
3856        if (numMatch == 0) {
3857            return;
3858        }
3859        PackageInfo pi;
3860        if (ps.pkg != null) {
3861            pi = generatePackageInfo(ps.pkg, flags, userId);
3862        } else {
3863            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3864        }
3865        // The above might return null in cases of uninstalled apps or install-state
3866        // skew across users/profiles.
3867        if (pi != null) {
3868            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3869                if (numMatch == permissions.length) {
3870                    pi.requestedPermissions = permissions;
3871                } else {
3872                    pi.requestedPermissions = new String[numMatch];
3873                    numMatch = 0;
3874                    for (int i=0; i<permissions.length; i++) {
3875                        if (tmp[i]) {
3876                            pi.requestedPermissions[numMatch] = permissions[i];
3877                            numMatch++;
3878                        }
3879                    }
3880                }
3881            }
3882            list.add(pi);
3883        }
3884    }
3885
3886    @Override
3887    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3888            String[] permissions, int flags, int userId) {
3889        if (!sUserManager.exists(userId)) return null;
3890        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3891
3892        // writer
3893        synchronized (mPackages) {
3894            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3895            boolean[] tmpBools = new boolean[permissions.length];
3896            if (listUninstalled) {
3897                for (PackageSetting ps : mSettings.mPackages.values()) {
3898                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3899                }
3900            } else {
3901                for (PackageParser.Package pkg : mPackages.values()) {
3902                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3903                    if (ps != null) {
3904                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3905                                userId);
3906                    }
3907                }
3908            }
3909
3910            return new ParceledListSlice<PackageInfo>(list);
3911        }
3912    }
3913
3914    @Override
3915    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3916        if (!sUserManager.exists(userId)) return null;
3917        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3918
3919        // writer
3920        synchronized (mPackages) {
3921            ArrayList<ApplicationInfo> list;
3922            if (listUninstalled) {
3923                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3924                for (PackageSetting ps : mSettings.mPackages.values()) {
3925                    ApplicationInfo ai;
3926                    if (ps.pkg != null) {
3927                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3928                                ps.readUserState(userId), userId);
3929                    } else {
3930                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3931                    }
3932                    if (ai != null) {
3933                        list.add(ai);
3934                    }
3935                }
3936            } else {
3937                list = new ArrayList<ApplicationInfo>(mPackages.size());
3938                for (PackageParser.Package p : mPackages.values()) {
3939                    if (p.mExtras != null) {
3940                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3941                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3942                        if (ai != null) {
3943                            list.add(ai);
3944                        }
3945                    }
3946                }
3947            }
3948
3949            return new ParceledListSlice<ApplicationInfo>(list);
3950        }
3951    }
3952
3953    public List<ApplicationInfo> getPersistentApplications(int flags) {
3954        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3955
3956        // reader
3957        synchronized (mPackages) {
3958            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3959            final int userId = UserHandle.getCallingUserId();
3960            while (i.hasNext()) {
3961                final PackageParser.Package p = i.next();
3962                if (p.applicationInfo != null
3963                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3964                        && (!mSafeMode || isSystemApp(p))) {
3965                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3966                    if (ps != null) {
3967                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3968                                ps.readUserState(userId), userId);
3969                        if (ai != null) {
3970                            finalList.add(ai);
3971                        }
3972                    }
3973                }
3974            }
3975        }
3976
3977        return finalList;
3978    }
3979
3980    @Override
3981    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3982        if (!sUserManager.exists(userId)) return null;
3983        // reader
3984        synchronized (mPackages) {
3985            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3986            PackageSetting ps = provider != null
3987                    ? mSettings.mPackages.get(provider.owner.packageName)
3988                    : null;
3989            return ps != null
3990                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3991                    && (!mSafeMode || (provider.info.applicationInfo.flags
3992                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3993                    ? PackageParser.generateProviderInfo(provider, flags,
3994                            ps.readUserState(userId), userId)
3995                    : null;
3996        }
3997    }
3998
3999    /**
4000     * @deprecated
4001     */
4002    @Deprecated
4003    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4004        // reader
4005        synchronized (mPackages) {
4006            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4007                    .entrySet().iterator();
4008            final int userId = UserHandle.getCallingUserId();
4009            while (i.hasNext()) {
4010                Map.Entry<String, PackageParser.Provider> entry = i.next();
4011                PackageParser.Provider p = entry.getValue();
4012                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4013
4014                if (ps != null && p.syncable
4015                        && (!mSafeMode || (p.info.applicationInfo.flags
4016                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4017                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4018                            ps.readUserState(userId), userId);
4019                    if (info != null) {
4020                        outNames.add(entry.getKey());
4021                        outInfo.add(info);
4022                    }
4023                }
4024            }
4025        }
4026    }
4027
4028    @Override
4029    public List<ProviderInfo> queryContentProviders(String processName,
4030            int uid, int flags) {
4031        ArrayList<ProviderInfo> finalList = null;
4032        // reader
4033        synchronized (mPackages) {
4034            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4035            final int userId = processName != null ?
4036                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4037            while (i.hasNext()) {
4038                final PackageParser.Provider p = i.next();
4039                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4040                if (ps != null && p.info.authority != null
4041                        && (processName == null
4042                                || (p.info.processName.equals(processName)
4043                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4044                        && mSettings.isEnabledLPr(p.info, flags, userId)
4045                        && (!mSafeMode
4046                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4047                    if (finalList == null) {
4048                        finalList = new ArrayList<ProviderInfo>(3);
4049                    }
4050                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4051                            ps.readUserState(userId), userId);
4052                    if (info != null) {
4053                        finalList.add(info);
4054                    }
4055                }
4056            }
4057        }
4058
4059        if (finalList != null) {
4060            Collections.sort(finalList, mProviderInitOrderSorter);
4061        }
4062
4063        return finalList;
4064    }
4065
4066    @Override
4067    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4068            int flags) {
4069        // reader
4070        synchronized (mPackages) {
4071            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4072            return PackageParser.generateInstrumentationInfo(i, flags);
4073        }
4074    }
4075
4076    @Override
4077    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4078            int flags) {
4079        ArrayList<InstrumentationInfo> finalList =
4080            new ArrayList<InstrumentationInfo>();
4081
4082        // reader
4083        synchronized (mPackages) {
4084            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4085            while (i.hasNext()) {
4086                final PackageParser.Instrumentation p = i.next();
4087                if (targetPackage == null
4088                        || targetPackage.equals(p.info.targetPackage)) {
4089                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4090                            flags);
4091                    if (ii != null) {
4092                        finalList.add(ii);
4093                    }
4094                }
4095            }
4096        }
4097
4098        return finalList;
4099    }
4100
4101    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4102        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4103        if (overlays == null) {
4104            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4105            return;
4106        }
4107        for (PackageParser.Package opkg : overlays.values()) {
4108            // Not much to do if idmap fails: we already logged the error
4109            // and we certainly don't want to abort installation of pkg simply
4110            // because an overlay didn't fit properly. For these reasons,
4111            // ignore the return value of createIdmapForPackagePairLI.
4112            createIdmapForPackagePairLI(pkg, opkg);
4113        }
4114    }
4115
4116    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4117            PackageParser.Package opkg) {
4118        if (!opkg.mTrustedOverlay) {
4119            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4120                    opkg.baseCodePath + ": overlay not trusted");
4121            return false;
4122        }
4123        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4124        if (overlaySet == null) {
4125            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4126                    opkg.baseCodePath + " but target package has no known overlays");
4127            return false;
4128        }
4129        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4130        // TODO: generate idmap for split APKs
4131        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4132            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4133                    + opkg.baseCodePath);
4134            return false;
4135        }
4136        PackageParser.Package[] overlayArray =
4137            overlaySet.values().toArray(new PackageParser.Package[0]);
4138        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4139            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4140                return p1.mOverlayPriority - p2.mOverlayPriority;
4141            }
4142        };
4143        Arrays.sort(overlayArray, cmp);
4144
4145        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4146        int i = 0;
4147        for (PackageParser.Package p : overlayArray) {
4148            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4149        }
4150        return true;
4151    }
4152
4153    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4154        final File[] files = dir.listFiles();
4155        if (ArrayUtils.isEmpty(files)) {
4156            Log.d(TAG, "No files in app dir " + dir);
4157            return;
4158        }
4159
4160        if (DEBUG_PACKAGE_SCANNING) {
4161            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4162                    + " flags=0x" + Integer.toHexString(parseFlags));
4163        }
4164
4165        for (File file : files) {
4166            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4167                    && !PackageInstallerService.isStageName(file.getName());
4168            if (!isPackage) {
4169                // Ignore entries which are not packages
4170                continue;
4171            }
4172            try {
4173                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4174                        scanFlags, currentTime, null);
4175            } catch (PackageManagerException e) {
4176                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4177
4178                // Delete invalid userdata apps
4179                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4180                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4181                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4182                    if (file.isDirectory()) {
4183                        mInstaller.rmPackageDir(file.getAbsolutePath());
4184                    } else {
4185                        file.delete();
4186                    }
4187                }
4188            }
4189        }
4190    }
4191
4192    private static File getSettingsProblemFile() {
4193        File dataDir = Environment.getDataDirectory();
4194        File systemDir = new File(dataDir, "system");
4195        File fname = new File(systemDir, "uiderrors.txt");
4196        return fname;
4197    }
4198
4199    static void reportSettingsProblem(int priority, String msg) {
4200        logCriticalInfo(priority, msg);
4201    }
4202
4203    static void logCriticalInfo(int priority, String msg) {
4204        Slog.println(priority, TAG, msg);
4205        EventLogTags.writePmCriticalInfo(msg);
4206        try {
4207            File fname = getSettingsProblemFile();
4208            FileOutputStream out = new FileOutputStream(fname, true);
4209            PrintWriter pw = new FastPrintWriter(out);
4210            SimpleDateFormat formatter = new SimpleDateFormat();
4211            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4212            pw.println(dateString + ": " + msg);
4213            pw.close();
4214            FileUtils.setPermissions(
4215                    fname.toString(),
4216                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4217                    -1, -1);
4218        } catch (java.io.IOException e) {
4219        }
4220    }
4221
4222    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4223            PackageParser.Package pkg, File srcFile, int parseFlags)
4224            throws PackageManagerException {
4225        if (ps != null
4226                && ps.codePath.equals(srcFile)
4227                && ps.timeStamp == srcFile.lastModified()
4228                && !isCompatSignatureUpdateNeeded(pkg)
4229                && !isRecoverSignatureUpdateNeeded(pkg)) {
4230            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4231            if (ps.signatures.mSignatures != null
4232                    && ps.signatures.mSignatures.length != 0
4233                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4234                // Optimization: reuse the existing cached certificates
4235                // if the package appears to be unchanged.
4236                pkg.mSignatures = ps.signatures.mSignatures;
4237                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4238                synchronized (mPackages) {
4239                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4240                }
4241                return;
4242            }
4243
4244            Slog.w(TAG, "PackageSetting for " + ps.name
4245                    + " is missing signatures.  Collecting certs again to recover them.");
4246        } else {
4247            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4248        }
4249
4250        try {
4251            pp.collectCertificates(pkg, parseFlags);
4252            pp.collectManifestDigest(pkg);
4253        } catch (PackageParserException e) {
4254            throw PackageManagerException.from(e);
4255        }
4256    }
4257
4258    /*
4259     *  Scan a package and return the newly parsed package.
4260     *  Returns null in case of errors and the error code is stored in mLastScanError
4261     */
4262    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4263            long currentTime, UserHandle user) throws PackageManagerException {
4264        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4265        parseFlags |= mDefParseFlags;
4266        PackageParser pp = new PackageParser();
4267        pp.setSeparateProcesses(mSeparateProcesses);
4268        pp.setOnlyCoreApps(mOnlyCore);
4269        pp.setDisplayMetrics(mMetrics);
4270
4271        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4272            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4273        }
4274
4275        final PackageParser.Package pkg;
4276        try {
4277            pkg = pp.parsePackage(scanFile, parseFlags);
4278        } catch (PackageParserException e) {
4279            throw PackageManagerException.from(e);
4280        }
4281
4282        PackageSetting ps = null;
4283        PackageSetting updatedPkg;
4284        // reader
4285        synchronized (mPackages) {
4286            // Look to see if we already know about this package.
4287            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4288            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4289                // This package has been renamed to its original name.  Let's
4290                // use that.
4291                ps = mSettings.peekPackageLPr(oldName);
4292            }
4293            // If there was no original package, see one for the real package name.
4294            if (ps == null) {
4295                ps = mSettings.peekPackageLPr(pkg.packageName);
4296            }
4297            // Check to see if this package could be hiding/updating a system
4298            // package.  Must look for it either under the original or real
4299            // package name depending on our state.
4300            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4301            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4302        }
4303        boolean updatedPkgBetter = false;
4304        // First check if this is a system package that may involve an update
4305        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4306            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
4307            // it needs to drop FLAG_PRIVILEGED.
4308            if (locationIsPrivileged(scanFile)) {
4309                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4310            } else {
4311                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4312            }
4313
4314            if (ps != null && !ps.codePath.equals(scanFile)) {
4315                // The path has changed from what was last scanned...  check the
4316                // version of the new path against what we have stored to determine
4317                // what to do.
4318                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4319                if (pkg.mVersionCode <= ps.versionCode) {
4320                    // The system package has been updated and the code path does not match
4321                    // Ignore entry. Skip it.
4322                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
4323                            + " ignored: updated version " + ps.versionCode
4324                            + " better than this " + pkg.mVersionCode);
4325                    if (!updatedPkg.codePath.equals(scanFile)) {
4326                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4327                                + ps.name + " changing from " + updatedPkg.codePathString
4328                                + " to " + scanFile);
4329                        updatedPkg.codePath = scanFile;
4330                        updatedPkg.codePathString = scanFile.toString();
4331                        updatedPkg.resourcePath = scanFile;
4332                        updatedPkg.resourcePathString = scanFile.toString();
4333                    }
4334                    updatedPkg.pkg = pkg;
4335                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4336                } else {
4337                    // The current app on the system partition is better than
4338                    // what we have updated to on the data partition; switch
4339                    // back to the system partition version.
4340                    // At this point, its safely assumed that package installation for
4341                    // apps in system partition will go through. If not there won't be a working
4342                    // version of the app
4343                    // writer
4344                    synchronized (mPackages) {
4345                        // Just remove the loaded entries from package lists.
4346                        mPackages.remove(ps.name);
4347                    }
4348
4349                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4350                            + " reverting from " + ps.codePathString
4351                            + ": new version " + pkg.mVersionCode
4352                            + " better than installed " + ps.versionCode);
4353
4354                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4355                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4356                            getAppDexInstructionSets(ps));
4357                    synchronized (mInstallLock) {
4358                        args.cleanUpResourcesLI();
4359                    }
4360                    synchronized (mPackages) {
4361                        mSettings.enableSystemPackageLPw(ps.name);
4362                    }
4363                    updatedPkgBetter = true;
4364                }
4365            }
4366        }
4367
4368        if (updatedPkg != null) {
4369            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4370            // initially
4371            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4372
4373            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4374            // flag set initially
4375            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
4376                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4377            }
4378        }
4379
4380        // Verify certificates against what was last scanned
4381        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4382
4383        /*
4384         * A new system app appeared, but we already had a non-system one of the
4385         * same name installed earlier.
4386         */
4387        boolean shouldHideSystemApp = false;
4388        if (updatedPkg == null && ps != null
4389                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4390            /*
4391             * Check to make sure the signatures match first. If they don't,
4392             * wipe the installed application and its data.
4393             */
4394            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4395                    != PackageManager.SIGNATURE_MATCH) {
4396                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
4397                        + " signatures don't match existing userdata copy; removing");
4398                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4399                ps = null;
4400            } else {
4401                /*
4402                 * If the newly-added system app is an older version than the
4403                 * already installed version, hide it. It will be scanned later
4404                 * and re-added like an update.
4405                 */
4406                if (pkg.mVersionCode <= ps.versionCode) {
4407                    shouldHideSystemApp = true;
4408                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
4409                            + " but new version " + pkg.mVersionCode + " better than installed "
4410                            + ps.versionCode + "; hiding system");
4411                } else {
4412                    /*
4413                     * The newly found system app is a newer version that the
4414                     * one previously installed. Simply remove the
4415                     * already-installed application and replace it with our own
4416                     * while keeping the application data.
4417                     */
4418                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4419                            + " reverting from " + ps.codePathString + ": new version "
4420                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
4421                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4422                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4423                            getAppDexInstructionSets(ps));
4424                    synchronized (mInstallLock) {
4425                        args.cleanUpResourcesLI();
4426                    }
4427                }
4428            }
4429        }
4430
4431        // The apk is forward locked (not public) if its code and resources
4432        // are kept in different files. (except for app in either system or
4433        // vendor path).
4434        // TODO grab this value from PackageSettings
4435        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4436            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4437                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4438            }
4439        }
4440
4441        // TODO: extend to support forward-locked splits
4442        String resourcePath = null;
4443        String baseResourcePath = null;
4444        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4445            if (ps != null && ps.resourcePathString != null) {
4446                resourcePath = ps.resourcePathString;
4447                baseResourcePath = ps.resourcePathString;
4448            } else {
4449                // Should not happen at all. Just log an error.
4450                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4451            }
4452        } else {
4453            resourcePath = pkg.codePath;
4454            baseResourcePath = pkg.baseCodePath;
4455        }
4456
4457        // Set application objects path explicitly.
4458        pkg.applicationInfo.setCodePath(pkg.codePath);
4459        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4460        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4461        pkg.applicationInfo.setResourcePath(resourcePath);
4462        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4463        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4464
4465        // Note that we invoke the following method only if we are about to unpack an application
4466        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4467                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4468
4469        /*
4470         * If the system app should be overridden by a previously installed
4471         * data, hide the system app now and let the /data/app scan pick it up
4472         * again.
4473         */
4474        if (shouldHideSystemApp) {
4475            synchronized (mPackages) {
4476                /*
4477                 * We have to grant systems permissions before we hide, because
4478                 * grantPermissions will assume the package update is trying to
4479                 * expand its permissions.
4480                 */
4481                grantPermissionsLPw(pkg, true, pkg.packageName);
4482                mSettings.disableSystemPackageLPw(pkg.packageName);
4483            }
4484        }
4485
4486        return scannedPkg;
4487    }
4488
4489    private static String fixProcessName(String defProcessName,
4490            String processName, int uid) {
4491        if (processName == null) {
4492            return defProcessName;
4493        }
4494        return processName;
4495    }
4496
4497    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4498            throws PackageManagerException {
4499        if (pkgSetting.signatures.mSignatures != null) {
4500            // Already existing package. Make sure signatures match
4501            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4502                    == PackageManager.SIGNATURE_MATCH;
4503            if (!match) {
4504                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4505                        == PackageManager.SIGNATURE_MATCH;
4506            }
4507            if (!match) {
4508                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
4509                        == PackageManager.SIGNATURE_MATCH;
4510            }
4511            if (!match) {
4512                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4513                        + pkg.packageName + " signatures do not match the "
4514                        + "previously installed version; ignoring!");
4515            }
4516        }
4517
4518        // Check for shared user signatures
4519        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4520            // Already existing package. Make sure signatures match
4521            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4522                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4523            if (!match) {
4524                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4525                        == PackageManager.SIGNATURE_MATCH;
4526            }
4527            if (!match) {
4528                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
4529                        == PackageManager.SIGNATURE_MATCH;
4530            }
4531            if (!match) {
4532                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4533                        "Package " + pkg.packageName
4534                        + " has no signatures that match those in shared user "
4535                        + pkgSetting.sharedUser.name + "; ignoring!");
4536            }
4537        }
4538    }
4539
4540    /**
4541     * Enforces that only the system UID or root's UID can call a method exposed
4542     * via Binder.
4543     *
4544     * @param message used as message if SecurityException is thrown
4545     * @throws SecurityException if the caller is not system or root
4546     */
4547    private static final void enforceSystemOrRoot(String message) {
4548        final int uid = Binder.getCallingUid();
4549        if (uid != Process.SYSTEM_UID && uid != 0) {
4550            throw new SecurityException(message);
4551        }
4552    }
4553
4554    @Override
4555    public void performBootDexOpt() {
4556        enforceSystemOrRoot("Only the system can request dexopt be performed");
4557
4558        // Before everything else, see whether we need to fstrim.
4559        try {
4560            IMountService ms = PackageHelper.getMountService();
4561            if (ms != null) {
4562                final boolean isUpgrade = isUpgrade();
4563                boolean doTrim = isUpgrade;
4564                if (doTrim) {
4565                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
4566                } else {
4567                    final long interval = android.provider.Settings.Global.getLong(
4568                            mContext.getContentResolver(),
4569                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
4570                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
4571                    if (interval > 0) {
4572                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
4573                        if (timeSinceLast > interval) {
4574                            doTrim = true;
4575                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
4576                                    + "; running immediately");
4577                        }
4578                    }
4579                }
4580                if (doTrim) {
4581                    if (!isFirstBoot()) {
4582                        try {
4583                            ActivityManagerNative.getDefault().showBootMessage(
4584                                    mContext.getResources().getString(
4585                                            R.string.android_upgrading_fstrim), true);
4586                        } catch (RemoteException e) {
4587                        }
4588                    }
4589                    ms.runMaintenance();
4590                }
4591            } else {
4592                Slog.e(TAG, "Mount service unavailable!");
4593            }
4594        } catch (RemoteException e) {
4595            // Can't happen; MountService is local
4596        }
4597
4598        final ArraySet<PackageParser.Package> pkgs;
4599        synchronized (mPackages) {
4600            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
4601        }
4602
4603        if (pkgs != null) {
4604            // Sort apps by importance for dexopt ordering. Important apps are given more priority
4605            // in case the device runs out of space.
4606            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
4607            // Give priority to core apps.
4608            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4609                PackageParser.Package pkg = it.next();
4610                if (pkg.coreApp) {
4611                    if (DEBUG_DEXOPT) {
4612                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
4613                    }
4614                    sortedPkgs.add(pkg);
4615                    it.remove();
4616                }
4617            }
4618            // Give priority to system apps that listen for pre boot complete.
4619            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
4620            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
4621            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4622                PackageParser.Package pkg = it.next();
4623                if (pkgNames.contains(pkg.packageName)) {
4624                    if (DEBUG_DEXOPT) {
4625                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
4626                    }
4627                    sortedPkgs.add(pkg);
4628                    it.remove();
4629                }
4630            }
4631            // Filter out packages that aren't recently used.
4632            filterRecentlyUsedApps(pkgs);
4633            // Add all remaining apps.
4634            for (PackageParser.Package pkg : pkgs) {
4635                if (DEBUG_DEXOPT) {
4636                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
4637                }
4638                sortedPkgs.add(pkg);
4639            }
4640
4641            // If we want to be lazy, filter everything that wasn't recently used.
4642            if (mLazyDexOpt) {
4643                filterRecentlyUsedApps(sortedPkgs);
4644            }
4645
4646            int i = 0;
4647            int total = sortedPkgs.size();
4648            File dataDir = Environment.getDataDirectory();
4649            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
4650            if (lowThreshold == 0) {
4651                throw new IllegalStateException("Invalid low memory threshold");
4652            }
4653            for (PackageParser.Package pkg : sortedPkgs) {
4654                long usableSpace = dataDir.getUsableSpace();
4655                if (usableSpace < lowThreshold) {
4656                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
4657                    break;
4658                }
4659                performBootDexOpt(pkg, ++i, total);
4660            }
4661        }
4662    }
4663
4664    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
4665        // Filter out packages that aren't recently used.
4666        //
4667        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4668        // should do a full dexopt.
4669        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4670            int total = pkgs.size();
4671            int skipped = 0;
4672            long now = System.currentTimeMillis();
4673            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4674                PackageParser.Package pkg = i.next();
4675                long then = pkg.mLastPackageUsageTimeInMills;
4676                if (then + mDexOptLRUThresholdInMills < now) {
4677                    if (DEBUG_DEXOPT) {
4678                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4679                              ((then == 0) ? "never" : new Date(then)));
4680                    }
4681                    i.remove();
4682                    skipped++;
4683                }
4684            }
4685            if (DEBUG_DEXOPT) {
4686                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4687            }
4688        }
4689    }
4690
4691    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
4692        List<ResolveInfo> ris = null;
4693        try {
4694            ris = AppGlobals.getPackageManager().queryIntentReceivers(
4695                    intent, null, 0, UserHandle.USER_OWNER);
4696        } catch (RemoteException e) {
4697        }
4698        ArraySet<String> pkgNames = new ArraySet<String>();
4699        if (ris != null) {
4700            for (ResolveInfo ri : ris) {
4701                pkgNames.add(ri.activityInfo.packageName);
4702            }
4703        }
4704        return pkgNames;
4705    }
4706
4707    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
4708        if (DEBUG_DEXOPT) {
4709            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
4710        }
4711        if (!isFirstBoot()) {
4712            try {
4713                ActivityManagerNative.getDefault().showBootMessage(
4714                        mContext.getResources().getString(R.string.android_upgrading_apk,
4715                                curr, total), true);
4716            } catch (RemoteException e) {
4717            }
4718        }
4719        PackageParser.Package p = pkg;
4720        synchronized (mInstallLock) {
4721            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
4722                    false /* force dex */, false /* defer */, true /* include dependencies */);
4723        }
4724    }
4725
4726    @Override
4727    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4728        return performDexOpt(packageName, instructionSet, false);
4729    }
4730
4731    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4732        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4733        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4734        if (!dexopt && !updateUsage) {
4735            // We aren't going to dexopt or update usage, so bail early.
4736            return false;
4737        }
4738        PackageParser.Package p;
4739        final String targetInstructionSet;
4740        synchronized (mPackages) {
4741            p = mPackages.get(packageName);
4742            if (p == null) {
4743                return false;
4744            }
4745            if (updateUsage) {
4746                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4747            }
4748            mPackageUsage.write(false);
4749            if (!dexopt) {
4750                // We aren't going to dexopt, so bail early.
4751                return false;
4752            }
4753
4754            targetInstructionSet = instructionSet != null ? instructionSet :
4755                    getPrimaryInstructionSet(p.applicationInfo);
4756            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4757                return false;
4758            }
4759        }
4760
4761        synchronized (mInstallLock) {
4762            final String[] instructionSets = new String[] { targetInstructionSet };
4763            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
4764                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
4765            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
4766        }
4767    }
4768
4769    public ArraySet<String> getPackagesThatNeedDexOpt() {
4770        ArraySet<String> pkgs = null;
4771        synchronized (mPackages) {
4772            for (PackageParser.Package p : mPackages.values()) {
4773                if (DEBUG_DEXOPT) {
4774                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4775                }
4776                if (!p.mDexOptPerformed.isEmpty()) {
4777                    continue;
4778                }
4779                if (pkgs == null) {
4780                    pkgs = new ArraySet<String>();
4781                }
4782                pkgs.add(p.packageName);
4783            }
4784        }
4785        return pkgs;
4786    }
4787
4788    public void shutdown() {
4789        mPackageUsage.write(true);
4790    }
4791
4792    @Override
4793    public void forceDexOpt(String packageName) {
4794        enforceSystemOrRoot("forceDexOpt");
4795
4796        PackageParser.Package pkg;
4797        synchronized (mPackages) {
4798            pkg = mPackages.get(packageName);
4799            if (pkg == null) {
4800                throw new IllegalArgumentException("Missing package: " + packageName);
4801            }
4802        }
4803
4804        synchronized (mInstallLock) {
4805            final String[] instructionSets = new String[] {
4806                    getPrimaryInstructionSet(pkg.applicationInfo) };
4807            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
4808                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
4809            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
4810                throw new IllegalStateException("Failed to dexopt: " + res);
4811            }
4812        }
4813    }
4814
4815    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4816        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4817            Slog.w(TAG, "Unable to update from " + oldPkg.name
4818                    + " to " + newPkg.packageName
4819                    + ": old package not in system partition");
4820            return false;
4821        } else if (mPackages.get(oldPkg.name) != null) {
4822            Slog.w(TAG, "Unable to update from " + oldPkg.name
4823                    + " to " + newPkg.packageName
4824                    + ": old package still exists");
4825            return false;
4826        }
4827        return true;
4828    }
4829
4830    private File getDataPathForPackage(String packageName, int userId) {
4831        /*
4832         * Until we fully support multiple users, return the directory we
4833         * previously would have. The PackageManagerTests will need to be
4834         * revised when this is changed back..
4835         */
4836        if (userId == 0) {
4837            return new File(mAppDataDir, packageName);
4838        } else {
4839            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4840                + File.separator + packageName);
4841        }
4842    }
4843
4844    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4845        int[] users = sUserManager.getUserIds();
4846        int res = mInstaller.install(packageName, uid, uid, seinfo);
4847        if (res < 0) {
4848            return res;
4849        }
4850        for (int user : users) {
4851            if (user != 0) {
4852                res = mInstaller.createUserData(packageName,
4853                        UserHandle.getUid(user, uid), user, seinfo);
4854                if (res < 0) {
4855                    return res;
4856                }
4857            }
4858        }
4859        return res;
4860    }
4861
4862    private int removeDataDirsLI(String packageName) {
4863        int[] users = sUserManager.getUserIds();
4864        int res = 0;
4865        for (int user : users) {
4866            int resInner = mInstaller.remove(packageName, user);
4867            if (resInner < 0) {
4868                res = resInner;
4869            }
4870        }
4871
4872        return res;
4873    }
4874
4875    private int deleteCodeCacheDirsLI(String packageName) {
4876        int[] users = sUserManager.getUserIds();
4877        int res = 0;
4878        for (int user : users) {
4879            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4880            if (resInner < 0) {
4881                res = resInner;
4882            }
4883        }
4884        return res;
4885    }
4886
4887    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4888            PackageParser.Package changingLib) {
4889        if (file.path != null) {
4890            usesLibraryFiles.add(file.path);
4891            return;
4892        }
4893        PackageParser.Package p = mPackages.get(file.apk);
4894        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4895            // If we are doing this while in the middle of updating a library apk,
4896            // then we need to make sure to use that new apk for determining the
4897            // dependencies here.  (We haven't yet finished committing the new apk
4898            // to the package manager state.)
4899            if (p == null || p.packageName.equals(changingLib.packageName)) {
4900                p = changingLib;
4901            }
4902        }
4903        if (p != null) {
4904            usesLibraryFiles.addAll(p.getAllCodePaths());
4905        }
4906    }
4907
4908    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4909            PackageParser.Package changingLib) throws PackageManagerException {
4910        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4911            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4912            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4913            for (int i=0; i<N; i++) {
4914                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4915                if (file == null) {
4916                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4917                            "Package " + pkg.packageName + " requires unavailable shared library "
4918                            + pkg.usesLibraries.get(i) + "; failing!");
4919                }
4920                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4921            }
4922            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4923            for (int i=0; i<N; i++) {
4924                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4925                if (file == null) {
4926                    Slog.w(TAG, "Package " + pkg.packageName
4927                            + " desires unavailable shared library "
4928                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4929                } else {
4930                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4931                }
4932            }
4933            N = usesLibraryFiles.size();
4934            if (N > 0) {
4935                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4936            } else {
4937                pkg.usesLibraryFiles = null;
4938            }
4939        }
4940    }
4941
4942    private static boolean hasString(List<String> list, List<String> which) {
4943        if (list == null) {
4944            return false;
4945        }
4946        for (int i=list.size()-1; i>=0; i--) {
4947            for (int j=which.size()-1; j>=0; j--) {
4948                if (which.get(j).equals(list.get(i))) {
4949                    return true;
4950                }
4951            }
4952        }
4953        return false;
4954    }
4955
4956    private void updateAllSharedLibrariesLPw() {
4957        for (PackageParser.Package pkg : mPackages.values()) {
4958            try {
4959                updateSharedLibrariesLPw(pkg, null);
4960            } catch (PackageManagerException e) {
4961                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4962            }
4963        }
4964    }
4965
4966    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4967            PackageParser.Package changingPkg) {
4968        ArrayList<PackageParser.Package> res = null;
4969        for (PackageParser.Package pkg : mPackages.values()) {
4970            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4971                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4972                if (res == null) {
4973                    res = new ArrayList<PackageParser.Package>();
4974                }
4975                res.add(pkg);
4976                try {
4977                    updateSharedLibrariesLPw(pkg, changingPkg);
4978                } catch (PackageManagerException e) {
4979                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4980                }
4981            }
4982        }
4983        return res;
4984    }
4985
4986    /**
4987     * Derive the value of the {@code cpuAbiOverride} based on the provided
4988     * value and an optional stored value from the package settings.
4989     */
4990    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
4991        String cpuAbiOverride = null;
4992
4993        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
4994            cpuAbiOverride = null;
4995        } else if (abiOverride != null) {
4996            cpuAbiOverride = abiOverride;
4997        } else if (settings != null) {
4998            cpuAbiOverride = settings.cpuAbiOverrideString;
4999        }
5000
5001        return cpuAbiOverride;
5002    }
5003
5004    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5005            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5006        boolean success = false;
5007        try {
5008            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5009                    currentTime, user);
5010            success = true;
5011            return res;
5012        } finally {
5013            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5014                removeDataDirsLI(pkg.packageName);
5015            }
5016        }
5017    }
5018
5019    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5020            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5021        final File scanFile = new File(pkg.codePath);
5022        if (pkg.applicationInfo.getCodePath() == null ||
5023                pkg.applicationInfo.getResourcePath() == null) {
5024            // Bail out. The resource and code paths haven't been set.
5025            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5026                    "Code and resource paths haven't been set correctly");
5027        }
5028
5029        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5030            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5031        } else {
5032            // Only allow system apps to be flagged as core apps.
5033            pkg.coreApp = false;
5034        }
5035
5036        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5037            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5038        }
5039
5040        if (mCustomResolverComponentName != null &&
5041                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5042            setUpCustomResolverActivity(pkg);
5043        }
5044
5045        if (pkg.packageName.equals("android")) {
5046            synchronized (mPackages) {
5047                if (mAndroidApplication != null) {
5048                    Slog.w(TAG, "*************************************************");
5049                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5050                    Slog.w(TAG, " file=" + scanFile);
5051                    Slog.w(TAG, "*************************************************");
5052                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5053                            "Core android package being redefined.  Skipping.");
5054                }
5055
5056                // Set up information for our fall-back user intent resolution activity.
5057                mPlatformPackage = pkg;
5058                pkg.mVersionCode = mSdkVersion;
5059                mAndroidApplication = pkg.applicationInfo;
5060
5061                if (!mResolverReplaced) {
5062                    mResolveActivity.applicationInfo = mAndroidApplication;
5063                    mResolveActivity.name = ResolverActivity.class.getName();
5064                    mResolveActivity.packageName = mAndroidApplication.packageName;
5065                    mResolveActivity.processName = "system:ui";
5066                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5067                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5068                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5069                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5070                    mResolveActivity.exported = true;
5071                    mResolveActivity.enabled = true;
5072                    mResolveInfo.activityInfo = mResolveActivity;
5073                    mResolveInfo.priority = 0;
5074                    mResolveInfo.preferredOrder = 0;
5075                    mResolveInfo.match = 0;
5076                    mResolveComponentName = new ComponentName(
5077                            mAndroidApplication.packageName, mResolveActivity.name);
5078                }
5079            }
5080        }
5081
5082        if (DEBUG_PACKAGE_SCANNING) {
5083            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5084                Log.d(TAG, "Scanning package " + pkg.packageName);
5085        }
5086
5087        if (mPackages.containsKey(pkg.packageName)
5088                || mSharedLibraries.containsKey(pkg.packageName)) {
5089            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5090                    "Application package " + pkg.packageName
5091                    + " already installed.  Skipping duplicate.");
5092        }
5093
5094        // Initialize package source and resource directories
5095        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5096        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5097
5098        SharedUserSetting suid = null;
5099        PackageSetting pkgSetting = null;
5100
5101        if (!isSystemApp(pkg)) {
5102            // Only system apps can use these features.
5103            pkg.mOriginalPackages = null;
5104            pkg.mRealPackage = null;
5105            pkg.mAdoptPermissions = null;
5106        }
5107
5108        // writer
5109        synchronized (mPackages) {
5110            if (pkg.mSharedUserId != null) {
5111                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5112                if (suid == null) {
5113                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5114                            "Creating application package " + pkg.packageName
5115                            + " for shared user failed");
5116                }
5117                if (DEBUG_PACKAGE_SCANNING) {
5118                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5119                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5120                                + "): packages=" + suid.packages);
5121                }
5122            }
5123
5124            // Check if we are renaming from an original package name.
5125            PackageSetting origPackage = null;
5126            String realName = null;
5127            if (pkg.mOriginalPackages != null) {
5128                // This package may need to be renamed to a previously
5129                // installed name.  Let's check on that...
5130                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5131                if (pkg.mOriginalPackages.contains(renamed)) {
5132                    // This package had originally been installed as the
5133                    // original name, and we have already taken care of
5134                    // transitioning to the new one.  Just update the new
5135                    // one to continue using the old name.
5136                    realName = pkg.mRealPackage;
5137                    if (!pkg.packageName.equals(renamed)) {
5138                        // Callers into this function may have already taken
5139                        // care of renaming the package; only do it here if
5140                        // it is not already done.
5141                        pkg.setPackageName(renamed);
5142                    }
5143
5144                } else {
5145                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5146                        if ((origPackage = mSettings.peekPackageLPr(
5147                                pkg.mOriginalPackages.get(i))) != null) {
5148                            // We do have the package already installed under its
5149                            // original name...  should we use it?
5150                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5151                                // New package is not compatible with original.
5152                                origPackage = null;
5153                                continue;
5154                            } else if (origPackage.sharedUser != null) {
5155                                // Make sure uid is compatible between packages.
5156                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5157                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5158                                            + " to " + pkg.packageName + ": old uid "
5159                                            + origPackage.sharedUser.name
5160                                            + " differs from " + pkg.mSharedUserId);
5161                                    origPackage = null;
5162                                    continue;
5163                                }
5164                            } else {
5165                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5166                                        + pkg.packageName + " to old name " + origPackage.name);
5167                            }
5168                            break;
5169                        }
5170                    }
5171                }
5172            }
5173
5174            if (mTransferedPackages.contains(pkg.packageName)) {
5175                Slog.w(TAG, "Package " + pkg.packageName
5176                        + " was transferred to another, but its .apk remains");
5177            }
5178
5179            // Just create the setting, don't add it yet. For already existing packages
5180            // the PkgSetting exists already and doesn't have to be created.
5181            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5182                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5183                    pkg.applicationInfo.primaryCpuAbi,
5184                    pkg.applicationInfo.secondaryCpuAbi,
5185                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
5186                    user, false);
5187            if (pkgSetting == null) {
5188                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5189                        "Creating application package " + pkg.packageName + " failed");
5190            }
5191
5192            if (pkgSetting.origPackage != null) {
5193                // If we are first transitioning from an original package,
5194                // fix up the new package's name now.  We need to do this after
5195                // looking up the package under its new name, so getPackageLP
5196                // can take care of fiddling things correctly.
5197                pkg.setPackageName(origPackage.name);
5198
5199                // File a report about this.
5200                String msg = "New package " + pkgSetting.realName
5201                        + " renamed to replace old package " + pkgSetting.name;
5202                reportSettingsProblem(Log.WARN, msg);
5203
5204                // Make a note of it.
5205                mTransferedPackages.add(origPackage.name);
5206
5207                // No longer need to retain this.
5208                pkgSetting.origPackage = null;
5209            }
5210
5211            if (realName != null) {
5212                // Make a note of it.
5213                mTransferedPackages.add(pkg.packageName);
5214            }
5215
5216            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5217                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5218            }
5219
5220            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5221                // Check all shared libraries and map to their actual file path.
5222                // We only do this here for apps not on a system dir, because those
5223                // are the only ones that can fail an install due to this.  We
5224                // will take care of the system apps by updating all of their
5225                // library paths after the scan is done.
5226                updateSharedLibrariesLPw(pkg, null);
5227            }
5228
5229            if (mFoundPolicyFile) {
5230                SELinuxMMAC.assignSeinfoValue(pkg);
5231            }
5232
5233            pkg.applicationInfo.uid = pkgSetting.appId;
5234            pkg.mExtras = pkgSetting;
5235            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5236                try {
5237                    verifySignaturesLP(pkgSetting, pkg);
5238                    // We just determined the app is signed correctly, so bring
5239                    // over the latest parsed certs.
5240                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5241                } catch (PackageManagerException e) {
5242                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5243                        throw e;
5244                    }
5245                    // The signature has changed, but this package is in the system
5246                    // image...  let's recover!
5247                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5248                    // However...  if this package is part of a shared user, but it
5249                    // doesn't match the signature of the shared user, let's fail.
5250                    // What this means is that you can't change the signatures
5251                    // associated with an overall shared user, which doesn't seem all
5252                    // that unreasonable.
5253                    if (pkgSetting.sharedUser != null) {
5254                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5255                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5256                            throw new PackageManagerException(
5257                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5258                                            "Signature mismatch for shared user : "
5259                                            + pkgSetting.sharedUser);
5260                        }
5261                    }
5262                    // File a report about this.
5263                    String msg = "System package " + pkg.packageName
5264                        + " signature changed; retaining data.";
5265                    reportSettingsProblem(Log.WARN, msg);
5266                }
5267            } else {
5268                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5269                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5270                            + pkg.packageName + " upgrade keys do not match the "
5271                            + "previously installed version");
5272                } else {
5273                    // We just determined the app is signed correctly, so bring
5274                    // over the latest parsed certs.
5275                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5276                }
5277            }
5278            // Verify that this new package doesn't have any content providers
5279            // that conflict with existing packages.  Only do this if the
5280            // package isn't already installed, since we don't want to break
5281            // things that are installed.
5282            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5283                final int N = pkg.providers.size();
5284                int i;
5285                for (i=0; i<N; i++) {
5286                    PackageParser.Provider p = pkg.providers.get(i);
5287                    if (p.info.authority != null) {
5288                        String names[] = p.info.authority.split(";");
5289                        for (int j = 0; j < names.length; j++) {
5290                            if (mProvidersByAuthority.containsKey(names[j])) {
5291                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5292                                final String otherPackageName =
5293                                        ((other != null && other.getComponentName() != null) ?
5294                                                other.getComponentName().getPackageName() : "?");
5295                                throw new PackageManagerException(
5296                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5297                                                "Can't install because provider name " + names[j]
5298                                                + " (in package " + pkg.applicationInfo.packageName
5299                                                + ") is already used by " + otherPackageName);
5300                            }
5301                        }
5302                    }
5303                }
5304            }
5305
5306            if (pkg.mAdoptPermissions != null) {
5307                // This package wants to adopt ownership of permissions from
5308                // another package.
5309                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5310                    final String origName = pkg.mAdoptPermissions.get(i);
5311                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5312                    if (orig != null) {
5313                        if (verifyPackageUpdateLPr(orig, pkg)) {
5314                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5315                                    + pkg.packageName);
5316                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5317                        }
5318                    }
5319                }
5320            }
5321        }
5322
5323        final String pkgName = pkg.packageName;
5324
5325        final long scanFileTime = scanFile.lastModified();
5326        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5327        pkg.applicationInfo.processName = fixProcessName(
5328                pkg.applicationInfo.packageName,
5329                pkg.applicationInfo.processName,
5330                pkg.applicationInfo.uid);
5331
5332        File dataPath;
5333        if (mPlatformPackage == pkg) {
5334            // The system package is special.
5335            dataPath = new File(Environment.getDataDirectory(), "system");
5336
5337            pkg.applicationInfo.dataDir = dataPath.getPath();
5338
5339        } else {
5340            // This is a normal package, need to make its data directory.
5341            dataPath = getDataPathForPackage(pkg.packageName, 0);
5342
5343            boolean uidError = false;
5344            if (dataPath.exists()) {
5345                int currentUid = 0;
5346                try {
5347                    StructStat stat = Os.stat(dataPath.getPath());
5348                    currentUid = stat.st_uid;
5349                } catch (ErrnoException e) {
5350                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5351                }
5352
5353                // If we have mismatched owners for the data path, we have a problem.
5354                if (currentUid != pkg.applicationInfo.uid) {
5355                    boolean recovered = false;
5356                    if (currentUid == 0) {
5357                        // The directory somehow became owned by root.  Wow.
5358                        // This is probably because the system was stopped while
5359                        // installd was in the middle of messing with its libs
5360                        // directory.  Ask installd to fix that.
5361                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5362                                pkg.applicationInfo.uid);
5363                        if (ret >= 0) {
5364                            recovered = true;
5365                            String msg = "Package " + pkg.packageName
5366                                    + " unexpectedly changed to uid 0; recovered to " +
5367                                    + pkg.applicationInfo.uid;
5368                            reportSettingsProblem(Log.WARN, msg);
5369                        }
5370                    }
5371                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5372                            || (scanFlags&SCAN_BOOTING) != 0)) {
5373                        // If this is a system app, we can at least delete its
5374                        // current data so the application will still work.
5375                        int ret = removeDataDirsLI(pkgName);
5376                        if (ret >= 0) {
5377                            // TODO: Kill the processes first
5378                            // Old data gone!
5379                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5380                                    ? "System package " : "Third party package ";
5381                            String msg = prefix + pkg.packageName
5382                                    + " has changed from uid: "
5383                                    + currentUid + " to "
5384                                    + pkg.applicationInfo.uid + "; old data erased";
5385                            reportSettingsProblem(Log.WARN, msg);
5386                            recovered = true;
5387
5388                            // And now re-install the app.
5389                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5390                                                   pkg.applicationInfo.seinfo);
5391                            if (ret == -1) {
5392                                // Ack should not happen!
5393                                msg = prefix + pkg.packageName
5394                                        + " could not have data directory re-created after delete.";
5395                                reportSettingsProblem(Log.WARN, msg);
5396                                throw new PackageManagerException(
5397                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5398                            }
5399                        }
5400                        if (!recovered) {
5401                            mHasSystemUidErrors = true;
5402                        }
5403                    } else if (!recovered) {
5404                        // If we allow this install to proceed, we will be broken.
5405                        // Abort, abort!
5406                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5407                                "scanPackageLI");
5408                    }
5409                    if (!recovered) {
5410                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5411                            + pkg.applicationInfo.uid + "/fs_"
5412                            + currentUid;
5413                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5414                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5415                        String msg = "Package " + pkg.packageName
5416                                + " has mismatched uid: "
5417                                + currentUid + " on disk, "
5418                                + pkg.applicationInfo.uid + " in settings";
5419                        // writer
5420                        synchronized (mPackages) {
5421                            mSettings.mReadMessages.append(msg);
5422                            mSettings.mReadMessages.append('\n');
5423                            uidError = true;
5424                            if (!pkgSetting.uidError) {
5425                                reportSettingsProblem(Log.ERROR, msg);
5426                            }
5427                        }
5428                    }
5429                }
5430                pkg.applicationInfo.dataDir = dataPath.getPath();
5431                if (mShouldRestoreconData) {
5432                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5433                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5434                                pkg.applicationInfo.uid);
5435                }
5436            } else {
5437                if (DEBUG_PACKAGE_SCANNING) {
5438                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5439                        Log.v(TAG, "Want this data dir: " + dataPath);
5440                }
5441                //invoke installer to do the actual installation
5442                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5443                                           pkg.applicationInfo.seinfo);
5444                if (ret < 0) {
5445                    // Error from installer
5446                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5447                            "Unable to create data dirs [errorCode=" + ret + "]");
5448                }
5449
5450                if (dataPath.exists()) {
5451                    pkg.applicationInfo.dataDir = dataPath.getPath();
5452                } else {
5453                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5454                    pkg.applicationInfo.dataDir = null;
5455                }
5456            }
5457
5458            pkgSetting.uidError = uidError;
5459        }
5460
5461        final String path = scanFile.getPath();
5462        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5463        if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5464            setBundledAppAbisAndRoots(pkg, pkgSetting);
5465
5466            // If we haven't found any native libraries for the app, check if it has
5467            // renderscript code. We'll need to force the app to 32 bit if it has
5468            // renderscript bitcode.
5469            if (pkg.applicationInfo.primaryCpuAbi == null
5470                    && pkg.applicationInfo.secondaryCpuAbi == null
5471                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5472                NativeLibraryHelper.Handle handle = null;
5473                try {
5474                    handle = NativeLibraryHelper.Handle.create(scanFile);
5475                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5476                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5477                    }
5478                } catch (IOException ioe) {
5479                    Slog.w(TAG, "Error scanning system app : " + ioe);
5480                } finally {
5481                    IoUtils.closeQuietly(handle);
5482                }
5483            }
5484
5485            setNativeLibraryPaths(pkg);
5486        } else {
5487            if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
5488                deriveNonSystemPackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
5489            } else {
5490                // TODO: We need this second call to derive in two cases :
5491                //
5492                // - To update the native library paths based on the final install location.
5493                // - We don't call dexopt when moving packages, and so we have to scan again.
5494                //
5495                // We can simplify this and avoid having to scan the package again by letting
5496                // scanPackageLI know if the current install was a move (and deriving things only
5497                // in that case) and by "reparenting" the native lib directory in the case of
5498                // a normal (non-move) install.
5499                deriveNonSystemPackageAbi(pkg, scanFile, cpuAbiOverride, false /* extract libs */);
5500            }
5501
5502            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5503            final int[] userIds = sUserManager.getUserIds();
5504            synchronized (mInstallLock) {
5505                // Create a native library symlink only if we have native libraries
5506                // and if the native libraries are 32 bit libraries. We do not provide
5507                // this symlink for 64 bit libraries.
5508                if (pkg.applicationInfo.primaryCpuAbi != null &&
5509                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5510                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5511                    for (int userId : userIds) {
5512                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5513                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5514                                    "Failed linking native library dir (user=" + userId + ")");
5515                        }
5516                    }
5517                }
5518            }
5519        }
5520
5521        // This is a special case for the "system" package, where the ABI is
5522        // dictated by the zygote configuration (and init.rc). We should keep track
5523        // of this ABI so that we can deal with "normal" applications that run under
5524        // the same UID correctly.
5525        if (mPlatformPackage == pkg) {
5526            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5527                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5528        }
5529
5530        // If there's a mismatch between the abi-override in the package setting
5531        // and the abiOverride specified for the install. Warn about this because we
5532        // would've already compiled the app without taking the package setting into
5533        // account.
5534        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
5535            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
5536                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
5537                        " for package: " + pkg.packageName);
5538            }
5539        }
5540
5541        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5542        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5543        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5544
5545        // Copy the derived override back to the parsed package, so that we can
5546        // update the package settings accordingly.
5547        pkg.cpuAbiOverride = cpuAbiOverride;
5548
5549        if (DEBUG_ABI_SELECTION) {
5550            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5551                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5552                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5553        }
5554
5555        // Push the derived path down into PackageSettings so we know what to
5556        // clean up at uninstall time.
5557        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5558
5559        if (DEBUG_ABI_SELECTION) {
5560            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5561                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5562                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5563        }
5564
5565        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5566            // We don't do this here during boot because we can do it all
5567            // at once after scanning all existing packages.
5568            //
5569            // We also do this *before* we perform dexopt on this package, so that
5570            // we can avoid redundant dexopts, and also to make sure we've got the
5571            // code and package path correct.
5572            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5573                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5574        }
5575
5576        if ((scanFlags & SCAN_NO_DEX) == 0) {
5577            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
5578                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
5579            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
5580                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5581            }
5582        }
5583        if (mFactoryTest && pkg.requestedPermissions.contains(
5584                android.Manifest.permission.FACTORY_TEST)) {
5585            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5586        }
5587
5588        ArrayList<PackageParser.Package> clientLibPkgs = null;
5589
5590        // writer
5591        synchronized (mPackages) {
5592            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5593                // Only system apps can add new shared libraries.
5594                if (pkg.libraryNames != null) {
5595                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5596                        String name = pkg.libraryNames.get(i);
5597                        boolean allowed = false;
5598                        if (pkg.isUpdatedSystemApp()) {
5599                            // New library entries can only be added through the
5600                            // system image.  This is important to get rid of a lot
5601                            // of nasty edge cases: for example if we allowed a non-
5602                            // system update of the app to add a library, then uninstalling
5603                            // the update would make the library go away, and assumptions
5604                            // we made such as through app install filtering would now
5605                            // have allowed apps on the device which aren't compatible
5606                            // with it.  Better to just have the restriction here, be
5607                            // conservative, and create many fewer cases that can negatively
5608                            // impact the user experience.
5609                            final PackageSetting sysPs = mSettings
5610                                    .getDisabledSystemPkgLPr(pkg.packageName);
5611                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5612                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5613                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5614                                        allowed = true;
5615                                        allowed = true;
5616                                        break;
5617                                    }
5618                                }
5619                            }
5620                        } else {
5621                            allowed = true;
5622                        }
5623                        if (allowed) {
5624                            if (!mSharedLibraries.containsKey(name)) {
5625                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5626                            } else if (!name.equals(pkg.packageName)) {
5627                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5628                                        + name + " already exists; skipping");
5629                            }
5630                        } else {
5631                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5632                                    + name + " that is not declared on system image; skipping");
5633                        }
5634                    }
5635                    if ((scanFlags&SCAN_BOOTING) == 0) {
5636                        // If we are not booting, we need to update any applications
5637                        // that are clients of our shared library.  If we are booting,
5638                        // this will all be done once the scan is complete.
5639                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5640                    }
5641                }
5642            }
5643        }
5644
5645        // We also need to dexopt any apps that are dependent on this library.  Note that
5646        // if these fail, we should abort the install since installing the library will
5647        // result in some apps being broken.
5648        if (clientLibPkgs != null) {
5649            if ((scanFlags & SCAN_NO_DEX) == 0) {
5650                for (int i = 0; i < clientLibPkgs.size(); i++) {
5651                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5652                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
5653                            null /* instruction sets */, forceDex,
5654                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
5655                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
5656                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5657                                "scanPackageLI failed to dexopt clientLibPkgs");
5658                    }
5659                }
5660            }
5661        }
5662
5663        // Request the ActivityManager to kill the process(only for existing packages)
5664        // so that we do not end up in a confused state while the user is still using the older
5665        // version of the application while the new one gets installed.
5666        if ((scanFlags & SCAN_REPLACING) != 0) {
5667            killApplication(pkg.applicationInfo.packageName,
5668                        pkg.applicationInfo.uid, "update pkg");
5669        }
5670
5671        // Also need to kill any apps that are dependent on the library.
5672        if (clientLibPkgs != null) {
5673            for (int i=0; i<clientLibPkgs.size(); i++) {
5674                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5675                killApplication(clientPkg.applicationInfo.packageName,
5676                        clientPkg.applicationInfo.uid, "update lib");
5677            }
5678        }
5679
5680        // writer
5681        synchronized (mPackages) {
5682            // We don't expect installation to fail beyond this point
5683
5684            // Add the new setting to mSettings
5685            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5686            // Add the new setting to mPackages
5687            mPackages.put(pkg.applicationInfo.packageName, pkg);
5688            // Make sure we don't accidentally delete its data.
5689            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5690            while (iter.hasNext()) {
5691                PackageCleanItem item = iter.next();
5692                if (pkgName.equals(item.packageName)) {
5693                    iter.remove();
5694                }
5695            }
5696
5697            // Take care of first install / last update times.
5698            if (currentTime != 0) {
5699                if (pkgSetting.firstInstallTime == 0) {
5700                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5701                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5702                    pkgSetting.lastUpdateTime = currentTime;
5703                }
5704            } else if (pkgSetting.firstInstallTime == 0) {
5705                // We need *something*.  Take time time stamp of the file.
5706                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5707            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5708                if (scanFileTime != pkgSetting.timeStamp) {
5709                    // A package on the system image has changed; consider this
5710                    // to be an update.
5711                    pkgSetting.lastUpdateTime = scanFileTime;
5712                }
5713            }
5714
5715            // Add the package's KeySets to the global KeySetManagerService
5716            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5717            try {
5718                // Old KeySetData no longer valid.
5719                ksms.removeAppKeySetDataLPw(pkg.packageName);
5720                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5721                if (pkg.mKeySetMapping != null) {
5722                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5723                            pkg.mKeySetMapping.entrySet()) {
5724                        if (entry.getValue() != null) {
5725                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5726                                                          entry.getValue(), entry.getKey());
5727                        }
5728                    }
5729                    if (pkg.mUpgradeKeySets != null) {
5730                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5731                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5732                        }
5733                    }
5734                }
5735            } catch (NullPointerException e) {
5736                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5737            } catch (IllegalArgumentException e) {
5738                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5739            }
5740
5741            int N = pkg.providers.size();
5742            StringBuilder r = null;
5743            int i;
5744            for (i=0; i<N; i++) {
5745                PackageParser.Provider p = pkg.providers.get(i);
5746                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5747                        p.info.processName, pkg.applicationInfo.uid);
5748                mProviders.addProvider(p);
5749                p.syncable = p.info.isSyncable;
5750                if (p.info.authority != null) {
5751                    String names[] = p.info.authority.split(";");
5752                    p.info.authority = null;
5753                    for (int j = 0; j < names.length; j++) {
5754                        if (j == 1 && p.syncable) {
5755                            // We only want the first authority for a provider to possibly be
5756                            // syncable, so if we already added this provider using a different
5757                            // authority clear the syncable flag. We copy the provider before
5758                            // changing it because the mProviders object contains a reference
5759                            // to a provider that we don't want to change.
5760                            // Only do this for the second authority since the resulting provider
5761                            // object can be the same for all future authorities for this provider.
5762                            p = new PackageParser.Provider(p);
5763                            p.syncable = false;
5764                        }
5765                        if (!mProvidersByAuthority.containsKey(names[j])) {
5766                            mProvidersByAuthority.put(names[j], p);
5767                            if (p.info.authority == null) {
5768                                p.info.authority = names[j];
5769                            } else {
5770                                p.info.authority = p.info.authority + ";" + names[j];
5771                            }
5772                            if (DEBUG_PACKAGE_SCANNING) {
5773                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5774                                    Log.d(TAG, "Registered content provider: " + names[j]
5775                                            + ", className = " + p.info.name + ", isSyncable = "
5776                                            + p.info.isSyncable);
5777                            }
5778                        } else {
5779                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5780                            Slog.w(TAG, "Skipping provider name " + names[j] +
5781                                    " (in package " + pkg.applicationInfo.packageName +
5782                                    "): name already used by "
5783                                    + ((other != null && other.getComponentName() != null)
5784                                            ? other.getComponentName().getPackageName() : "?"));
5785                        }
5786                    }
5787                }
5788                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5789                    if (r == null) {
5790                        r = new StringBuilder(256);
5791                    } else {
5792                        r.append(' ');
5793                    }
5794                    r.append(p.info.name);
5795                }
5796            }
5797            if (r != null) {
5798                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5799            }
5800
5801            N = pkg.services.size();
5802            r = null;
5803            for (i=0; i<N; i++) {
5804                PackageParser.Service s = pkg.services.get(i);
5805                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5806                        s.info.processName, pkg.applicationInfo.uid);
5807                mServices.addService(s);
5808                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5809                    if (r == null) {
5810                        r = new StringBuilder(256);
5811                    } else {
5812                        r.append(' ');
5813                    }
5814                    r.append(s.info.name);
5815                }
5816            }
5817            if (r != null) {
5818                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5819            }
5820
5821            N = pkg.receivers.size();
5822            r = null;
5823            for (i=0; i<N; i++) {
5824                PackageParser.Activity a = pkg.receivers.get(i);
5825                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5826                        a.info.processName, pkg.applicationInfo.uid);
5827                mReceivers.addActivity(a, "receiver");
5828                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5829                    if (r == null) {
5830                        r = new StringBuilder(256);
5831                    } else {
5832                        r.append(' ');
5833                    }
5834                    r.append(a.info.name);
5835                }
5836            }
5837            if (r != null) {
5838                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5839            }
5840
5841            N = pkg.activities.size();
5842            r = null;
5843            for (i=0; i<N; i++) {
5844                PackageParser.Activity a = pkg.activities.get(i);
5845                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5846                        a.info.processName, pkg.applicationInfo.uid);
5847                mActivities.addActivity(a, "activity");
5848                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5849                    if (r == null) {
5850                        r = new StringBuilder(256);
5851                    } else {
5852                        r.append(' ');
5853                    }
5854                    r.append(a.info.name);
5855                }
5856            }
5857            if (r != null) {
5858                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5859            }
5860
5861            N = pkg.permissionGroups.size();
5862            r = null;
5863            for (i=0; i<N; i++) {
5864                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5865                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5866                if (cur == null) {
5867                    mPermissionGroups.put(pg.info.name, pg);
5868                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5869                        if (r == null) {
5870                            r = new StringBuilder(256);
5871                        } else {
5872                            r.append(' ');
5873                        }
5874                        r.append(pg.info.name);
5875                    }
5876                } else {
5877                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5878                            + pg.info.packageName + " ignored: original from "
5879                            + cur.info.packageName);
5880                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5881                        if (r == null) {
5882                            r = new StringBuilder(256);
5883                        } else {
5884                            r.append(' ');
5885                        }
5886                        r.append("DUP:");
5887                        r.append(pg.info.name);
5888                    }
5889                }
5890            }
5891            if (r != null) {
5892                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5893            }
5894
5895            N = pkg.permissions.size();
5896            r = null;
5897            for (i=0; i<N; i++) {
5898                PackageParser.Permission p = pkg.permissions.get(i);
5899                ArrayMap<String, BasePermission> permissionMap =
5900                        p.tree ? mSettings.mPermissionTrees
5901                        : mSettings.mPermissions;
5902                p.group = mPermissionGroups.get(p.info.group);
5903                if (p.info.group == null || p.group != null) {
5904                    BasePermission bp = permissionMap.get(p.info.name);
5905
5906                    // Allow system apps to redefine non-system permissions
5907                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
5908                        final boolean currentOwnerIsSystem = (bp.perm != null
5909                                && isSystemApp(bp.perm.owner));
5910                        if (isSystemApp(p.owner)) {
5911                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
5912                                // It's a built-in permission and no owner, take ownership now
5913                                bp.packageSetting = pkgSetting;
5914                                bp.perm = p;
5915                                bp.uid = pkg.applicationInfo.uid;
5916                                bp.sourcePackage = p.info.packageName;
5917                            } else if (!currentOwnerIsSystem) {
5918                                String msg = "New decl " + p.owner + " of permission  "
5919                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
5920                                reportSettingsProblem(Log.WARN, msg);
5921                                bp = null;
5922                            }
5923                        }
5924                    }
5925
5926                    if (bp == null) {
5927                        bp = new BasePermission(p.info.name, p.info.packageName,
5928                                BasePermission.TYPE_NORMAL);
5929                        permissionMap.put(p.info.name, bp);
5930                    }
5931
5932                    if (bp.perm == null) {
5933                        if (bp.sourcePackage == null
5934                                || bp.sourcePackage.equals(p.info.packageName)) {
5935                            BasePermission tree = findPermissionTreeLP(p.info.name);
5936                            if (tree == null
5937                                    || tree.sourcePackage.equals(p.info.packageName)) {
5938                                bp.packageSetting = pkgSetting;
5939                                bp.perm = p;
5940                                bp.uid = pkg.applicationInfo.uid;
5941                                bp.sourcePackage = p.info.packageName;
5942                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5943                                    if (r == null) {
5944                                        r = new StringBuilder(256);
5945                                    } else {
5946                                        r.append(' ');
5947                                    }
5948                                    r.append(p.info.name);
5949                                }
5950                            } else {
5951                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5952                                        + p.info.packageName + " ignored: base tree "
5953                                        + tree.name + " is from package "
5954                                        + tree.sourcePackage);
5955                            }
5956                        } else {
5957                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5958                                    + p.info.packageName + " ignored: original from "
5959                                    + bp.sourcePackage);
5960                        }
5961                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5962                        if (r == null) {
5963                            r = new StringBuilder(256);
5964                        } else {
5965                            r.append(' ');
5966                        }
5967                        r.append("DUP:");
5968                        r.append(p.info.name);
5969                    }
5970                    if (bp.perm == p) {
5971                        bp.protectionLevel = p.info.protectionLevel;
5972                    }
5973                } else {
5974                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5975                            + p.info.packageName + " ignored: no group "
5976                            + p.group);
5977                }
5978            }
5979            if (r != null) {
5980                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5981            }
5982
5983            N = pkg.instrumentation.size();
5984            r = null;
5985            for (i=0; i<N; i++) {
5986                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5987                a.info.packageName = pkg.applicationInfo.packageName;
5988                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5989                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5990                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
5991                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
5992                a.info.dataDir = pkg.applicationInfo.dataDir;
5993
5994                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
5995                // need other information about the application, like the ABI and what not ?
5996                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5997                mInstrumentation.put(a.getComponentName(), a);
5998                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5999                    if (r == null) {
6000                        r = new StringBuilder(256);
6001                    } else {
6002                        r.append(' ');
6003                    }
6004                    r.append(a.info.name);
6005                }
6006            }
6007            if (r != null) {
6008                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6009            }
6010
6011            if (pkg.protectedBroadcasts != null) {
6012                N = pkg.protectedBroadcasts.size();
6013                for (i=0; i<N; i++) {
6014                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6015                }
6016            }
6017
6018            pkgSetting.setTimeStamp(scanFileTime);
6019
6020            // Create idmap files for pairs of (packages, overlay packages).
6021            // Note: "android", ie framework-res.apk, is handled by native layers.
6022            if (pkg.mOverlayTarget != null) {
6023                // This is an overlay package.
6024                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6025                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6026                        mOverlays.put(pkg.mOverlayTarget,
6027                                new ArrayMap<String, PackageParser.Package>());
6028                    }
6029                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6030                    map.put(pkg.packageName, pkg);
6031                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6032                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6033                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6034                                "scanPackageLI failed to createIdmap");
6035                    }
6036                }
6037            } else if (mOverlays.containsKey(pkg.packageName) &&
6038                    !pkg.packageName.equals("android")) {
6039                // This is a regular package, with one or more known overlay packages.
6040                createIdmapsForPackageLI(pkg);
6041            }
6042        }
6043
6044        return pkg;
6045    }
6046
6047    /**
6048     * Derive the ABI of a non-system package located at {@code scanFile}. This information
6049     * is derived purely on the basis of the contents of {@code scanFile} and
6050     * {@code cpuAbiOverride}.
6051     *
6052     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
6053     */
6054    public void deriveNonSystemPackageAbi(PackageParser.Package pkg, File scanFile,
6055                                          String cpuAbiOverride, boolean extractLibs)
6056            throws PackageManagerException {
6057        // TODO: We can probably be smarter about this stuff. For installed apps,
6058        // we can calculate this information at install time once and for all. For
6059        // system apps, we can probably assume that this information doesn't change
6060        // after the first boot scan. As things stand, we do lots of unnecessary work.
6061
6062        // Give ourselves some initial paths; we'll come back for another
6063        // pass once we've determined ABI below.
6064        setNativeLibraryPaths(pkg);
6065
6066        // We would never need to extract libs for forward-locked and external packages,
6067        // since the container service will do it for us.
6068        if (pkg.isForwardLocked() || isExternal(pkg)) {
6069            extractLibs = false;
6070        }
6071
6072        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6073        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6074
6075        NativeLibraryHelper.Handle handle = null;
6076        try {
6077            handle = NativeLibraryHelper.Handle.create(scanFile);
6078            // TODO(multiArch): This can be null for apps that didn't go through the
6079            // usual installation process. We can calculate it again, like we
6080            // do during install time.
6081            //
6082            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6083            // unnecessary.
6084            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6085
6086            // Null out the abis so that they can be recalculated.
6087            pkg.applicationInfo.primaryCpuAbi = null;
6088            pkg.applicationInfo.secondaryCpuAbi = null;
6089            if (isMultiArch(pkg.applicationInfo)) {
6090                // Warn if we've set an abiOverride for multi-lib packages..
6091                // By definition, we need to copy both 32 and 64 bit libraries for
6092                // such packages.
6093                if (pkg.cpuAbiOverride != null
6094                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
6095                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
6096                }
6097
6098                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
6099                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
6100                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
6101                    if (extractLibs) {
6102                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6103                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
6104                                useIsaSpecificSubdirs);
6105                    } else {
6106                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
6107                    }
6108                }
6109
6110                maybeThrowExceptionForMultiArchCopy(
6111                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
6112
6113                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
6114                    if (extractLibs) {
6115                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6116                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
6117                                useIsaSpecificSubdirs);
6118                    } else {
6119                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
6120                    }
6121                }
6122
6123                maybeThrowExceptionForMultiArchCopy(
6124                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
6125
6126                if (abi64 >= 0) {
6127                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
6128                }
6129
6130                if (abi32 >= 0) {
6131                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
6132                    if (abi64 >= 0) {
6133                        pkg.applicationInfo.secondaryCpuAbi = abi;
6134                    } else {
6135                        pkg.applicationInfo.primaryCpuAbi = abi;
6136                    }
6137                }
6138            } else {
6139                String[] abiList = (cpuAbiOverride != null) ?
6140                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
6141
6142                // Enable gross and lame hacks for apps that are built with old
6143                // SDK tools. We must scan their APKs for renderscript bitcode and
6144                // not launch them if it's present. Don't bother checking on devices
6145                // that don't have 64 bit support.
6146                boolean needsRenderScriptOverride = false;
6147                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
6148                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6149                    abiList = Build.SUPPORTED_32_BIT_ABIS;
6150                    needsRenderScriptOverride = true;
6151                }
6152
6153                final int copyRet;
6154                if (extractLibs) {
6155                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6156                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
6157                } else {
6158                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6159                }
6160
6161                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
6162                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6163                            "Error unpackaging native libs for app, errorCode=" + copyRet);
6164                }
6165
6166                if (copyRet >= 0) {
6167                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
6168                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
6169                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
6170                } else if (needsRenderScriptOverride) {
6171                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
6172                }
6173            }
6174        } catch (IOException ioe) {
6175            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
6176        } finally {
6177            IoUtils.closeQuietly(handle);
6178        }
6179
6180        // Now that we've calculated the ABIs and determined if it's an internal app,
6181        // we will go ahead and populate the nativeLibraryPath.
6182        setNativeLibraryPaths(pkg);
6183    }
6184
6185    /**
6186     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6187     * i.e, so that all packages can be run inside a single process if required.
6188     *
6189     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6190     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6191     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6192     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6193     * updating a package that belongs to a shared user.
6194     *
6195     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6196     * adds unnecessary complexity.
6197     */
6198    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6199            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6200        String requiredInstructionSet = null;
6201        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6202            requiredInstructionSet = VMRuntime.getInstructionSet(
6203                     scannedPackage.applicationInfo.primaryCpuAbi);
6204        }
6205
6206        PackageSetting requirer = null;
6207        for (PackageSetting ps : packagesForUser) {
6208            // If packagesForUser contains scannedPackage, we skip it. This will happen
6209            // when scannedPackage is an update of an existing package. Without this check,
6210            // we will never be able to change the ABI of any package belonging to a shared
6211            // user, even if it's compatible with other packages.
6212            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6213                if (ps.primaryCpuAbiString == null) {
6214                    continue;
6215                }
6216
6217                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6218                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6219                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6220                    // this but there's not much we can do.
6221                    String errorMessage = "Instruction set mismatch, "
6222                            + ((requirer == null) ? "[caller]" : requirer)
6223                            + " requires " + requiredInstructionSet + " whereas " + ps
6224                            + " requires " + instructionSet;
6225                    Slog.w(TAG, errorMessage);
6226                }
6227
6228                if (requiredInstructionSet == null) {
6229                    requiredInstructionSet = instructionSet;
6230                    requirer = ps;
6231                }
6232            }
6233        }
6234
6235        if (requiredInstructionSet != null) {
6236            String adjustedAbi;
6237            if (requirer != null) {
6238                // requirer != null implies that either scannedPackage was null or that scannedPackage
6239                // did not require an ABI, in which case we have to adjust scannedPackage to match
6240                // the ABI of the set (which is the same as requirer's ABI)
6241                adjustedAbi = requirer.primaryCpuAbiString;
6242                if (scannedPackage != null) {
6243                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6244                }
6245            } else {
6246                // requirer == null implies that we're updating all ABIs in the set to
6247                // match scannedPackage.
6248                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6249            }
6250
6251            for (PackageSetting ps : packagesForUser) {
6252                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6253                    if (ps.primaryCpuAbiString != null) {
6254                        continue;
6255                    }
6256
6257                    ps.primaryCpuAbiString = adjustedAbi;
6258                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6259                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6260                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6261
6262                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
6263                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
6264                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6265                            ps.primaryCpuAbiString = null;
6266                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6267                            return;
6268                        } else {
6269                            mInstaller.rmdex(ps.codePathString,
6270                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
6271                        }
6272                    }
6273                }
6274            }
6275        }
6276    }
6277
6278    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6279        synchronized (mPackages) {
6280            mResolverReplaced = true;
6281            // Set up information for custom user intent resolution activity.
6282            mResolveActivity.applicationInfo = pkg.applicationInfo;
6283            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6284            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6285            mResolveActivity.processName = pkg.applicationInfo.packageName;
6286            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6287            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6288                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6289            mResolveActivity.theme = 0;
6290            mResolveActivity.exported = true;
6291            mResolveActivity.enabled = true;
6292            mResolveInfo.activityInfo = mResolveActivity;
6293            mResolveInfo.priority = 0;
6294            mResolveInfo.preferredOrder = 0;
6295            mResolveInfo.match = 0;
6296            mResolveComponentName = mCustomResolverComponentName;
6297            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6298                    mResolveComponentName);
6299        }
6300    }
6301
6302    private static String calculateBundledApkRoot(final String codePathString) {
6303        final File codePath = new File(codePathString);
6304        final File codeRoot;
6305        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6306            codeRoot = Environment.getRootDirectory();
6307        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6308            codeRoot = Environment.getOemDirectory();
6309        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6310            codeRoot = Environment.getVendorDirectory();
6311        } else {
6312            // Unrecognized code path; take its top real segment as the apk root:
6313            // e.g. /something/app/blah.apk => /something
6314            try {
6315                File f = codePath.getCanonicalFile();
6316                File parent = f.getParentFile();    // non-null because codePath is a file
6317                File tmp;
6318                while ((tmp = parent.getParentFile()) != null) {
6319                    f = parent;
6320                    parent = tmp;
6321                }
6322                codeRoot = f;
6323                Slog.w(TAG, "Unrecognized code path "
6324                        + codePath + " - using " + codeRoot);
6325            } catch (IOException e) {
6326                // Can't canonicalize the code path -- shenanigans?
6327                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6328                return Environment.getRootDirectory().getPath();
6329            }
6330        }
6331        return codeRoot.getPath();
6332    }
6333
6334    /**
6335     * Derive and set the location of native libraries for the given package,
6336     * which varies depending on where and how the package was installed.
6337     */
6338    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6339        final ApplicationInfo info = pkg.applicationInfo;
6340        final String codePath = pkg.codePath;
6341        final File codeFile = new File(codePath);
6342        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
6343        final boolean asecApp = info.isForwardLocked() || isExternal(info);
6344
6345        info.nativeLibraryRootDir = null;
6346        info.nativeLibraryRootRequiresIsa = false;
6347        info.nativeLibraryDir = null;
6348        info.secondaryNativeLibraryDir = null;
6349
6350        if (isApkFile(codeFile)) {
6351            // Monolithic install
6352            if (bundledApp) {
6353                // If "/system/lib64/apkname" exists, assume that is the per-package
6354                // native library directory to use; otherwise use "/system/lib/apkname".
6355                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6356                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6357                        getPrimaryInstructionSet(info));
6358
6359                // This is a bundled system app so choose the path based on the ABI.
6360                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6361                // is just the default path.
6362                final String apkName = deriveCodePathName(codePath);
6363                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6364                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6365                        apkName).getAbsolutePath();
6366
6367                if (info.secondaryCpuAbi != null) {
6368                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6369                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6370                            secondaryLibDir, apkName).getAbsolutePath();
6371                }
6372            } else if (asecApp) {
6373                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6374                        .getAbsolutePath();
6375            } else {
6376                final String apkName = deriveCodePathName(codePath);
6377                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6378                        .getAbsolutePath();
6379            }
6380
6381            info.nativeLibraryRootRequiresIsa = false;
6382            info.nativeLibraryDir = info.nativeLibraryRootDir;
6383        } else {
6384            // Cluster install
6385            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6386            info.nativeLibraryRootRequiresIsa = true;
6387
6388            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6389                    getPrimaryInstructionSet(info)).getAbsolutePath();
6390
6391            if (info.secondaryCpuAbi != null) {
6392                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6393                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6394            }
6395        }
6396    }
6397
6398    /**
6399     * Calculate the abis and roots for a bundled app. These can uniquely
6400     * be determined from the contents of the system partition, i.e whether
6401     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6402     * of this information, and instead assume that the system was built
6403     * sensibly.
6404     */
6405    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6406                                           PackageSetting pkgSetting) {
6407        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6408
6409        // If "/system/lib64/apkname" exists, assume that is the per-package
6410        // native library directory to use; otherwise use "/system/lib/apkname".
6411        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6412        setBundledAppAbi(pkg, apkRoot, apkName);
6413        // pkgSetting might be null during rescan following uninstall of updates
6414        // to a bundled app, so accommodate that possibility.  The settings in
6415        // that case will be established later from the parsed package.
6416        //
6417        // If the settings aren't null, sync them up with what we've just derived.
6418        // note that apkRoot isn't stored in the package settings.
6419        if (pkgSetting != null) {
6420            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6421            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6422        }
6423    }
6424
6425    /**
6426     * Deduces the ABI of a bundled app and sets the relevant fields on the
6427     * parsed pkg object.
6428     *
6429     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6430     *        under which system libraries are installed.
6431     * @param apkName the name of the installed package.
6432     */
6433    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6434        final File codeFile = new File(pkg.codePath);
6435
6436        final boolean has64BitLibs;
6437        final boolean has32BitLibs;
6438        if (isApkFile(codeFile)) {
6439            // Monolithic install
6440            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6441            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6442        } else {
6443            // Cluster install
6444            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6445            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6446                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6447                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6448                has64BitLibs = (new File(rootDir, isa)).exists();
6449            } else {
6450                has64BitLibs = false;
6451            }
6452            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6453                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6454                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6455                has32BitLibs = (new File(rootDir, isa)).exists();
6456            } else {
6457                has32BitLibs = false;
6458            }
6459        }
6460
6461        if (has64BitLibs && !has32BitLibs) {
6462            // The package has 64 bit libs, but not 32 bit libs. Its primary
6463            // ABI should be 64 bit. We can safely assume here that the bundled
6464            // native libraries correspond to the most preferred ABI in the list.
6465
6466            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6467            pkg.applicationInfo.secondaryCpuAbi = null;
6468        } else if (has32BitLibs && !has64BitLibs) {
6469            // The package has 32 bit libs but not 64 bit libs. Its primary
6470            // ABI should be 32 bit.
6471
6472            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6473            pkg.applicationInfo.secondaryCpuAbi = null;
6474        } else if (has32BitLibs && has64BitLibs) {
6475            // The application has both 64 and 32 bit bundled libraries. We check
6476            // here that the app declares multiArch support, and warn if it doesn't.
6477            //
6478            // We will be lenient here and record both ABIs. The primary will be the
6479            // ABI that's higher on the list, i.e, a device that's configured to prefer
6480            // 64 bit apps will see a 64 bit primary ABI,
6481
6482            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6483                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6484            }
6485
6486            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6487                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6488                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6489            } else {
6490                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6491                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6492            }
6493        } else {
6494            pkg.applicationInfo.primaryCpuAbi = null;
6495            pkg.applicationInfo.secondaryCpuAbi = null;
6496        }
6497    }
6498
6499    private void killApplication(String pkgName, int appId, String reason) {
6500        // Request the ActivityManager to kill the process(only for existing packages)
6501        // so that we do not end up in a confused state while the user is still using the older
6502        // version of the application while the new one gets installed.
6503        IActivityManager am = ActivityManagerNative.getDefault();
6504        if (am != null) {
6505            try {
6506                am.killApplicationWithAppId(pkgName, appId, reason);
6507            } catch (RemoteException e) {
6508            }
6509        }
6510    }
6511
6512    void removePackageLI(PackageSetting ps, boolean chatty) {
6513        if (DEBUG_INSTALL) {
6514            if (chatty)
6515                Log.d(TAG, "Removing package " + ps.name);
6516        }
6517
6518        // writer
6519        synchronized (mPackages) {
6520            mPackages.remove(ps.name);
6521            final PackageParser.Package pkg = ps.pkg;
6522            if (pkg != null) {
6523                cleanPackageDataStructuresLILPw(pkg, chatty);
6524            }
6525        }
6526    }
6527
6528    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6529        if (DEBUG_INSTALL) {
6530            if (chatty)
6531                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6532        }
6533
6534        // writer
6535        synchronized (mPackages) {
6536            mPackages.remove(pkg.applicationInfo.packageName);
6537            cleanPackageDataStructuresLILPw(pkg, chatty);
6538        }
6539    }
6540
6541    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6542        int N = pkg.providers.size();
6543        StringBuilder r = null;
6544        int i;
6545        for (i=0; i<N; i++) {
6546            PackageParser.Provider p = pkg.providers.get(i);
6547            mProviders.removeProvider(p);
6548            if (p.info.authority == null) {
6549
6550                /* There was another ContentProvider with this authority when
6551                 * this app was installed so this authority is null,
6552                 * Ignore it as we don't have to unregister the provider.
6553                 */
6554                continue;
6555            }
6556            String names[] = p.info.authority.split(";");
6557            for (int j = 0; j < names.length; j++) {
6558                if (mProvidersByAuthority.get(names[j]) == p) {
6559                    mProvidersByAuthority.remove(names[j]);
6560                    if (DEBUG_REMOVE) {
6561                        if (chatty)
6562                            Log.d(TAG, "Unregistered content provider: " + names[j]
6563                                    + ", className = " + p.info.name + ", isSyncable = "
6564                                    + p.info.isSyncable);
6565                    }
6566                }
6567            }
6568            if (DEBUG_REMOVE && chatty) {
6569                if (r == null) {
6570                    r = new StringBuilder(256);
6571                } else {
6572                    r.append(' ');
6573                }
6574                r.append(p.info.name);
6575            }
6576        }
6577        if (r != null) {
6578            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6579        }
6580
6581        N = pkg.services.size();
6582        r = null;
6583        for (i=0; i<N; i++) {
6584            PackageParser.Service s = pkg.services.get(i);
6585            mServices.removeService(s);
6586            if (chatty) {
6587                if (r == null) {
6588                    r = new StringBuilder(256);
6589                } else {
6590                    r.append(' ');
6591                }
6592                r.append(s.info.name);
6593            }
6594        }
6595        if (r != null) {
6596            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6597        }
6598
6599        N = pkg.receivers.size();
6600        r = null;
6601        for (i=0; i<N; i++) {
6602            PackageParser.Activity a = pkg.receivers.get(i);
6603            mReceivers.removeActivity(a, "receiver");
6604            if (DEBUG_REMOVE && chatty) {
6605                if (r == null) {
6606                    r = new StringBuilder(256);
6607                } else {
6608                    r.append(' ');
6609                }
6610                r.append(a.info.name);
6611            }
6612        }
6613        if (r != null) {
6614            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6615        }
6616
6617        N = pkg.activities.size();
6618        r = null;
6619        for (i=0; i<N; i++) {
6620            PackageParser.Activity a = pkg.activities.get(i);
6621            mActivities.removeActivity(a, "activity");
6622            if (DEBUG_REMOVE && chatty) {
6623                if (r == null) {
6624                    r = new StringBuilder(256);
6625                } else {
6626                    r.append(' ');
6627                }
6628                r.append(a.info.name);
6629            }
6630        }
6631        if (r != null) {
6632            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6633        }
6634
6635        N = pkg.permissions.size();
6636        r = null;
6637        for (i=0; i<N; i++) {
6638            PackageParser.Permission p = pkg.permissions.get(i);
6639            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6640            if (bp == null) {
6641                bp = mSettings.mPermissionTrees.get(p.info.name);
6642            }
6643            if (bp != null && bp.perm == p) {
6644                bp.perm = null;
6645                if (DEBUG_REMOVE && chatty) {
6646                    if (r == null) {
6647                        r = new StringBuilder(256);
6648                    } else {
6649                        r.append(' ');
6650                    }
6651                    r.append(p.info.name);
6652                }
6653            }
6654            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6655                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6656                if (appOpPerms != null) {
6657                    appOpPerms.remove(pkg.packageName);
6658                }
6659            }
6660        }
6661        if (r != null) {
6662            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6663        }
6664
6665        N = pkg.requestedPermissions.size();
6666        r = null;
6667        for (i=0; i<N; i++) {
6668            String perm = pkg.requestedPermissions.get(i);
6669            BasePermission bp = mSettings.mPermissions.get(perm);
6670            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6671                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6672                if (appOpPerms != null) {
6673                    appOpPerms.remove(pkg.packageName);
6674                    if (appOpPerms.isEmpty()) {
6675                        mAppOpPermissionPackages.remove(perm);
6676                    }
6677                }
6678            }
6679        }
6680        if (r != null) {
6681            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6682        }
6683
6684        N = pkg.instrumentation.size();
6685        r = null;
6686        for (i=0; i<N; i++) {
6687            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6688            mInstrumentation.remove(a.getComponentName());
6689            if (DEBUG_REMOVE && chatty) {
6690                if (r == null) {
6691                    r = new StringBuilder(256);
6692                } else {
6693                    r.append(' ');
6694                }
6695                r.append(a.info.name);
6696            }
6697        }
6698        if (r != null) {
6699            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6700        }
6701
6702        r = null;
6703        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6704            // Only system apps can hold shared libraries.
6705            if (pkg.libraryNames != null) {
6706                for (i=0; i<pkg.libraryNames.size(); i++) {
6707                    String name = pkg.libraryNames.get(i);
6708                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6709                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6710                        mSharedLibraries.remove(name);
6711                        if (DEBUG_REMOVE && chatty) {
6712                            if (r == null) {
6713                                r = new StringBuilder(256);
6714                            } else {
6715                                r.append(' ');
6716                            }
6717                            r.append(name);
6718                        }
6719                    }
6720                }
6721            }
6722        }
6723        if (r != null) {
6724            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6725        }
6726    }
6727
6728    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6729        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6730            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6731                return true;
6732            }
6733        }
6734        return false;
6735    }
6736
6737    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6738    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6739    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6740
6741    private void updatePermissionsLPw(String changingPkg,
6742            PackageParser.Package pkgInfo, int flags) {
6743        // Make sure there are no dangling permission trees.
6744        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6745        while (it.hasNext()) {
6746            final BasePermission bp = it.next();
6747            if (bp.packageSetting == null) {
6748                // We may not yet have parsed the package, so just see if
6749                // we still know about its settings.
6750                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6751            }
6752            if (bp.packageSetting == null) {
6753                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6754                        + " from package " + bp.sourcePackage);
6755                it.remove();
6756            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6757                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6758                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6759                            + " from package " + bp.sourcePackage);
6760                    flags |= UPDATE_PERMISSIONS_ALL;
6761                    it.remove();
6762                }
6763            }
6764        }
6765
6766        // Make sure all dynamic permissions have been assigned to a package,
6767        // and make sure there are no dangling permissions.
6768        it = mSettings.mPermissions.values().iterator();
6769        while (it.hasNext()) {
6770            final BasePermission bp = it.next();
6771            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6772                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6773                        + bp.name + " pkg=" + bp.sourcePackage
6774                        + " info=" + bp.pendingInfo);
6775                if (bp.packageSetting == null && bp.pendingInfo != null) {
6776                    final BasePermission tree = findPermissionTreeLP(bp.name);
6777                    if (tree != null && tree.perm != null) {
6778                        bp.packageSetting = tree.packageSetting;
6779                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6780                                new PermissionInfo(bp.pendingInfo));
6781                        bp.perm.info.packageName = tree.perm.info.packageName;
6782                        bp.perm.info.name = bp.name;
6783                        bp.uid = tree.uid;
6784                    }
6785                }
6786            }
6787            if (bp.packageSetting == null) {
6788                // We may not yet have parsed the package, so just see if
6789                // we still know about its settings.
6790                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6791            }
6792            if (bp.packageSetting == null) {
6793                Slog.w(TAG, "Removing dangling permission: " + bp.name
6794                        + " from package " + bp.sourcePackage);
6795                it.remove();
6796            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6797                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6798                    Slog.i(TAG, "Removing old permission: " + bp.name
6799                            + " from package " + bp.sourcePackage);
6800                    flags |= UPDATE_PERMISSIONS_ALL;
6801                    it.remove();
6802                }
6803            }
6804        }
6805
6806        // Now update the permissions for all packages, in particular
6807        // replace the granted permissions of the system packages.
6808        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6809            for (PackageParser.Package pkg : mPackages.values()) {
6810                if (pkg != pkgInfo) {
6811                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6812                            changingPkg);
6813                }
6814            }
6815        }
6816
6817        if (pkgInfo != null) {
6818            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6819        }
6820    }
6821
6822    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6823            String packageOfInterest) {
6824        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6825        if (ps == null) {
6826            return;
6827        }
6828        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6829        ArraySet<String> origPermissions = gp.grantedPermissions;
6830        boolean changedPermission = false;
6831
6832        if (replace) {
6833            ps.permissionsFixed = false;
6834            if (gp == ps) {
6835                origPermissions = new ArraySet<String>(gp.grantedPermissions);
6836                gp.grantedPermissions.clear();
6837                gp.gids = mGlobalGids;
6838            }
6839        }
6840
6841        if (gp.gids == null) {
6842            gp.gids = mGlobalGids;
6843        }
6844
6845        final int N = pkg.requestedPermissions.size();
6846        for (int i=0; i<N; i++) {
6847            final String name = pkg.requestedPermissions.get(i);
6848            final boolean required = pkg.requestedPermissionsRequired.get(i);
6849            final BasePermission bp = mSettings.mPermissions.get(name);
6850            if (DEBUG_INSTALL) {
6851                if (gp != ps) {
6852                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6853                }
6854            }
6855
6856            if (bp == null || bp.packageSetting == null) {
6857                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6858                    Slog.w(TAG, "Unknown permission " + name
6859                            + " in package " + pkg.packageName);
6860                }
6861                continue;
6862            }
6863
6864            final String perm = bp.name;
6865            boolean allowed;
6866            boolean allowedSig = false;
6867            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6868                // Keep track of app op permissions.
6869                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6870                if (pkgs == null) {
6871                    pkgs = new ArraySet<>();
6872                    mAppOpPermissionPackages.put(bp.name, pkgs);
6873                }
6874                pkgs.add(pkg.packageName);
6875            }
6876            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6877            if (level == PermissionInfo.PROTECTION_NORMAL
6878                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6879                // We grant a normal or dangerous permission if any of the following
6880                // are true:
6881                // 1) The permission is required
6882                // 2) The permission is optional, but was granted in the past
6883                // 3) The permission is optional, but was requested by an
6884                //    app in /system (not /data)
6885                //
6886                // Otherwise, reject the permission.
6887                allowed = (required || origPermissions.contains(perm)
6888                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6889            } else if (bp.packageSetting == null) {
6890                // This permission is invalid; skip it.
6891                allowed = false;
6892            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6893                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6894                if (allowed) {
6895                    allowedSig = true;
6896                }
6897            } else {
6898                allowed = false;
6899            }
6900            if (DEBUG_INSTALL) {
6901                if (gp != ps) {
6902                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6903                }
6904            }
6905            if (allowed) {
6906                if (!isSystemApp(ps) && ps.permissionsFixed) {
6907                    // If this is an existing, non-system package, then
6908                    // we can't add any new permissions to it.
6909                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6910                        // Except...  if this is a permission that was added
6911                        // to the platform (note: need to only do this when
6912                        // updating the platform).
6913                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6914                    }
6915                }
6916                if (allowed) {
6917                    if (!gp.grantedPermissions.contains(perm)) {
6918                        changedPermission = true;
6919                        gp.grantedPermissions.add(perm);
6920                        gp.gids = appendInts(gp.gids, bp.gids);
6921                    } else if (!ps.haveGids) {
6922                        gp.gids = appendInts(gp.gids, bp.gids);
6923                    }
6924                } else {
6925                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6926                        Slog.w(TAG, "Not granting permission " + perm
6927                                + " to package " + pkg.packageName
6928                                + " because it was previously installed without");
6929                    }
6930                }
6931            } else {
6932                if (gp.grantedPermissions.remove(perm)) {
6933                    changedPermission = true;
6934                    gp.gids = removeInts(gp.gids, bp.gids);
6935                    Slog.i(TAG, "Un-granting permission " + perm
6936                            + " from package " + pkg.packageName
6937                            + " (protectionLevel=" + bp.protectionLevel
6938                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6939                            + ")");
6940                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6941                    // Don't print warning for app op permissions, since it is fine for them
6942                    // not to be granted, there is a UI for the user to decide.
6943                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6944                        Slog.w(TAG, "Not granting permission " + perm
6945                                + " to package " + pkg.packageName
6946                                + " (protectionLevel=" + bp.protectionLevel
6947                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6948                                + ")");
6949                    }
6950                }
6951            }
6952        }
6953
6954        if ((changedPermission || replace) && !ps.permissionsFixed &&
6955                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6956            // This is the first that we have heard about this package, so the
6957            // permissions we have now selected are fixed until explicitly
6958            // changed.
6959            ps.permissionsFixed = true;
6960        }
6961        ps.haveGids = true;
6962    }
6963
6964    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6965        boolean allowed = false;
6966        final int NP = PackageParser.NEW_PERMISSIONS.length;
6967        for (int ip=0; ip<NP; ip++) {
6968            final PackageParser.NewPermissionInfo npi
6969                    = PackageParser.NEW_PERMISSIONS[ip];
6970            if (npi.name.equals(perm)
6971                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6972                allowed = true;
6973                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6974                        + pkg.packageName);
6975                break;
6976            }
6977        }
6978        return allowed;
6979    }
6980
6981    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6982                                          BasePermission bp, ArraySet<String> origPermissions) {
6983        boolean allowed;
6984        allowed = (compareSignatures(
6985                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6986                        == PackageManager.SIGNATURE_MATCH)
6987                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6988                        == PackageManager.SIGNATURE_MATCH);
6989        if (!allowed && (bp.protectionLevel
6990                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6991            if (isSystemApp(pkg)) {
6992                // For updated system applications, a system permission
6993                // is granted only if it had been defined by the original application.
6994                if (pkg.isUpdatedSystemApp()) {
6995                    final PackageSetting sysPs = mSettings
6996                            .getDisabledSystemPkgLPr(pkg.packageName);
6997                    final GrantedPermissions origGp = sysPs.sharedUser != null
6998                            ? sysPs.sharedUser : sysPs;
6999
7000                    if (origGp.grantedPermissions.contains(perm)) {
7001                        // If the original was granted this permission, we take
7002                        // that grant decision as read and propagate it to the
7003                        // update.
7004                        if (sysPs.isPrivileged()) {
7005                            allowed = true;
7006                        }
7007                    } else {
7008                        // The system apk may have been updated with an older
7009                        // version of the one on the data partition, but which
7010                        // granted a new system permission that it didn't have
7011                        // before.  In this case we do want to allow the app to
7012                        // now get the new permission if the ancestral apk is
7013                        // privileged to get it.
7014                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7015                            for (int j=0;
7016                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7017                                if (perm.equals(
7018                                        sysPs.pkg.requestedPermissions.get(j))) {
7019                                    allowed = true;
7020                                    break;
7021                                }
7022                            }
7023                        }
7024                    }
7025                } else {
7026                    allowed = isPrivilegedApp(pkg);
7027                }
7028            }
7029        }
7030        if (!allowed && (bp.protectionLevel
7031                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7032            // For development permissions, a development permission
7033            // is granted only if it was already granted.
7034            allowed = origPermissions.contains(perm);
7035        }
7036        return allowed;
7037    }
7038
7039    final class ActivityIntentResolver
7040            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7041        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7042                boolean defaultOnly, int userId) {
7043            if (!sUserManager.exists(userId)) return null;
7044            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7045            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7046        }
7047
7048        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7049                int userId) {
7050            if (!sUserManager.exists(userId)) return null;
7051            mFlags = flags;
7052            return super.queryIntent(intent, resolvedType,
7053                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7054        }
7055
7056        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7057                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7058            if (!sUserManager.exists(userId)) return null;
7059            if (packageActivities == null) {
7060                return null;
7061            }
7062            mFlags = flags;
7063            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7064            final int N = packageActivities.size();
7065            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7066                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7067
7068            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7069            for (int i = 0; i < N; ++i) {
7070                intentFilters = packageActivities.get(i).intents;
7071                if (intentFilters != null && intentFilters.size() > 0) {
7072                    PackageParser.ActivityIntentInfo[] array =
7073                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7074                    intentFilters.toArray(array);
7075                    listCut.add(array);
7076                }
7077            }
7078            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7079        }
7080
7081        public final void addActivity(PackageParser.Activity a, String type) {
7082            final boolean systemApp = a.info.applicationInfo.isSystemApp();
7083            mActivities.put(a.getComponentName(), a);
7084            if (DEBUG_SHOW_INFO)
7085                Log.v(
7086                TAG, "  " + type + " " +
7087                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7088            if (DEBUG_SHOW_INFO)
7089                Log.v(TAG, "    Class=" + a.info.name);
7090            final int NI = a.intents.size();
7091            for (int j=0; j<NI; j++) {
7092                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7093                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7094                    intent.setPriority(0);
7095                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7096                            + a.className + " with priority > 0, forcing to 0");
7097                }
7098                if (DEBUG_SHOW_INFO) {
7099                    Log.v(TAG, "    IntentFilter:");
7100                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7101                }
7102                if (!intent.debugCheck()) {
7103                    Log.w(TAG, "==> For Activity " + a.info.name);
7104                }
7105                addFilter(intent);
7106            }
7107        }
7108
7109        public final void removeActivity(PackageParser.Activity a, String type) {
7110            mActivities.remove(a.getComponentName());
7111            if (DEBUG_SHOW_INFO) {
7112                Log.v(TAG, "  " + type + " "
7113                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7114                                : a.info.name) + ":");
7115                Log.v(TAG, "    Class=" + a.info.name);
7116            }
7117            final int NI = a.intents.size();
7118            for (int j=0; j<NI; j++) {
7119                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7120                if (DEBUG_SHOW_INFO) {
7121                    Log.v(TAG, "    IntentFilter:");
7122                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7123                }
7124                removeFilter(intent);
7125            }
7126        }
7127
7128        @Override
7129        protected boolean allowFilterResult(
7130                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7131            ActivityInfo filterAi = filter.activity.info;
7132            for (int i=dest.size()-1; i>=0; i--) {
7133                ActivityInfo destAi = dest.get(i).activityInfo;
7134                if (destAi.name == filterAi.name
7135                        && destAi.packageName == filterAi.packageName) {
7136                    return false;
7137                }
7138            }
7139            return true;
7140        }
7141
7142        @Override
7143        protected ActivityIntentInfo[] newArray(int size) {
7144            return new ActivityIntentInfo[size];
7145        }
7146
7147        @Override
7148        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7149            if (!sUserManager.exists(userId)) return true;
7150            PackageParser.Package p = filter.activity.owner;
7151            if (p != null) {
7152                PackageSetting ps = (PackageSetting)p.mExtras;
7153                if (ps != null) {
7154                    // System apps are never considered stopped for purposes of
7155                    // filtering, because there may be no way for the user to
7156                    // actually re-launch them.
7157                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7158                            && ps.getStopped(userId);
7159                }
7160            }
7161            return false;
7162        }
7163
7164        @Override
7165        protected boolean isPackageForFilter(String packageName,
7166                PackageParser.ActivityIntentInfo info) {
7167            return packageName.equals(info.activity.owner.packageName);
7168        }
7169
7170        @Override
7171        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7172                int match, int userId) {
7173            if (!sUserManager.exists(userId)) return null;
7174            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7175                return null;
7176            }
7177            final PackageParser.Activity activity = info.activity;
7178            if (mSafeMode && (activity.info.applicationInfo.flags
7179                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7180                return null;
7181            }
7182            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7183            if (ps == null) {
7184                return null;
7185            }
7186            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7187                    ps.readUserState(userId), userId);
7188            if (ai == null) {
7189                return null;
7190            }
7191            final ResolveInfo res = new ResolveInfo();
7192            res.activityInfo = ai;
7193            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7194                res.filter = info;
7195            }
7196            res.priority = info.getPriority();
7197            res.preferredOrder = activity.owner.mPreferredOrder;
7198            //System.out.println("Result: " + res.activityInfo.className +
7199            //                   " = " + res.priority);
7200            res.match = match;
7201            res.isDefault = info.hasDefault;
7202            res.labelRes = info.labelRes;
7203            res.nonLocalizedLabel = info.nonLocalizedLabel;
7204            if (userNeedsBadging(userId)) {
7205                res.noResourceId = true;
7206            } else {
7207                res.icon = info.icon;
7208            }
7209            res.system = res.activityInfo.applicationInfo.isSystemApp();
7210            return res;
7211        }
7212
7213        @Override
7214        protected void sortResults(List<ResolveInfo> results) {
7215            Collections.sort(results, mResolvePrioritySorter);
7216        }
7217
7218        @Override
7219        protected void dumpFilter(PrintWriter out, String prefix,
7220                PackageParser.ActivityIntentInfo filter) {
7221            out.print(prefix); out.print(
7222                    Integer.toHexString(System.identityHashCode(filter.activity)));
7223                    out.print(' ');
7224                    filter.activity.printComponentShortName(out);
7225                    out.print(" filter ");
7226                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7227        }
7228
7229        @Override
7230        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7231            return filter.activity;
7232        }
7233
7234        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7235            PackageParser.Activity activity = (PackageParser.Activity)label;
7236            out.print(prefix); out.print(
7237                    Integer.toHexString(System.identityHashCode(activity)));
7238                    out.print(' ');
7239                    activity.printComponentShortName(out);
7240            if (count > 1) {
7241                out.print(" ("); out.print(count); out.print(" filters)");
7242            }
7243            out.println();
7244        }
7245
7246//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7247//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7248//            final List<ResolveInfo> retList = Lists.newArrayList();
7249//            while (i.hasNext()) {
7250//                final ResolveInfo resolveInfo = i.next();
7251//                if (isEnabledLP(resolveInfo.activityInfo)) {
7252//                    retList.add(resolveInfo);
7253//                }
7254//            }
7255//            return retList;
7256//        }
7257
7258        // Keys are String (activity class name), values are Activity.
7259        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
7260                = new ArrayMap<ComponentName, PackageParser.Activity>();
7261        private int mFlags;
7262    }
7263
7264    private final class ServiceIntentResolver
7265            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7266        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7267                boolean defaultOnly, int userId) {
7268            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7269            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7270        }
7271
7272        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7273                int userId) {
7274            if (!sUserManager.exists(userId)) return null;
7275            mFlags = flags;
7276            return super.queryIntent(intent, resolvedType,
7277                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7278        }
7279
7280        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7281                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7282            if (!sUserManager.exists(userId)) return null;
7283            if (packageServices == null) {
7284                return null;
7285            }
7286            mFlags = flags;
7287            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7288            final int N = packageServices.size();
7289            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7290                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7291
7292            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7293            for (int i = 0; i < N; ++i) {
7294                intentFilters = packageServices.get(i).intents;
7295                if (intentFilters != null && intentFilters.size() > 0) {
7296                    PackageParser.ServiceIntentInfo[] array =
7297                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7298                    intentFilters.toArray(array);
7299                    listCut.add(array);
7300                }
7301            }
7302            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7303        }
7304
7305        public final void addService(PackageParser.Service s) {
7306            mServices.put(s.getComponentName(), s);
7307            if (DEBUG_SHOW_INFO) {
7308                Log.v(TAG, "  "
7309                        + (s.info.nonLocalizedLabel != null
7310                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7311                Log.v(TAG, "    Class=" + s.info.name);
7312            }
7313            final int NI = s.intents.size();
7314            int j;
7315            for (j=0; j<NI; j++) {
7316                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7317                if (DEBUG_SHOW_INFO) {
7318                    Log.v(TAG, "    IntentFilter:");
7319                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7320                }
7321                if (!intent.debugCheck()) {
7322                    Log.w(TAG, "==> For Service " + s.info.name);
7323                }
7324                addFilter(intent);
7325            }
7326        }
7327
7328        public final void removeService(PackageParser.Service s) {
7329            mServices.remove(s.getComponentName());
7330            if (DEBUG_SHOW_INFO) {
7331                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7332                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7333                Log.v(TAG, "    Class=" + s.info.name);
7334            }
7335            final int NI = s.intents.size();
7336            int j;
7337            for (j=0; j<NI; j++) {
7338                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7339                if (DEBUG_SHOW_INFO) {
7340                    Log.v(TAG, "    IntentFilter:");
7341                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7342                }
7343                removeFilter(intent);
7344            }
7345        }
7346
7347        @Override
7348        protected boolean allowFilterResult(
7349                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7350            ServiceInfo filterSi = filter.service.info;
7351            for (int i=dest.size()-1; i>=0; i--) {
7352                ServiceInfo destAi = dest.get(i).serviceInfo;
7353                if (destAi.name == filterSi.name
7354                        && destAi.packageName == filterSi.packageName) {
7355                    return false;
7356                }
7357            }
7358            return true;
7359        }
7360
7361        @Override
7362        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7363            return new PackageParser.ServiceIntentInfo[size];
7364        }
7365
7366        @Override
7367        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7368            if (!sUserManager.exists(userId)) return true;
7369            PackageParser.Package p = filter.service.owner;
7370            if (p != null) {
7371                PackageSetting ps = (PackageSetting)p.mExtras;
7372                if (ps != null) {
7373                    // System apps are never considered stopped for purposes of
7374                    // filtering, because there may be no way for the user to
7375                    // actually re-launch them.
7376                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7377                            && ps.getStopped(userId);
7378                }
7379            }
7380            return false;
7381        }
7382
7383        @Override
7384        protected boolean isPackageForFilter(String packageName,
7385                PackageParser.ServiceIntentInfo info) {
7386            return packageName.equals(info.service.owner.packageName);
7387        }
7388
7389        @Override
7390        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7391                int match, int userId) {
7392            if (!sUserManager.exists(userId)) return null;
7393            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7394            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7395                return null;
7396            }
7397            final PackageParser.Service service = info.service;
7398            if (mSafeMode && (service.info.applicationInfo.flags
7399                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7400                return null;
7401            }
7402            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7403            if (ps == null) {
7404                return null;
7405            }
7406            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7407                    ps.readUserState(userId), userId);
7408            if (si == null) {
7409                return null;
7410            }
7411            final ResolveInfo res = new ResolveInfo();
7412            res.serviceInfo = si;
7413            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7414                res.filter = filter;
7415            }
7416            res.priority = info.getPriority();
7417            res.preferredOrder = service.owner.mPreferredOrder;
7418            //System.out.println("Result: " + res.activityInfo.className +
7419            //                   " = " + res.priority);
7420            res.match = match;
7421            res.isDefault = info.hasDefault;
7422            res.labelRes = info.labelRes;
7423            res.nonLocalizedLabel = info.nonLocalizedLabel;
7424            res.icon = info.icon;
7425            res.system = res.serviceInfo.applicationInfo.isSystemApp();
7426            return res;
7427        }
7428
7429        @Override
7430        protected void sortResults(List<ResolveInfo> results) {
7431            Collections.sort(results, mResolvePrioritySorter);
7432        }
7433
7434        @Override
7435        protected void dumpFilter(PrintWriter out, String prefix,
7436                PackageParser.ServiceIntentInfo filter) {
7437            out.print(prefix); out.print(
7438                    Integer.toHexString(System.identityHashCode(filter.service)));
7439                    out.print(' ');
7440                    filter.service.printComponentShortName(out);
7441                    out.print(" filter ");
7442                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7443        }
7444
7445        @Override
7446        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
7447            return filter.service;
7448        }
7449
7450        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7451            PackageParser.Service service = (PackageParser.Service)label;
7452            out.print(prefix); out.print(
7453                    Integer.toHexString(System.identityHashCode(service)));
7454                    out.print(' ');
7455                    service.printComponentShortName(out);
7456            if (count > 1) {
7457                out.print(" ("); out.print(count); out.print(" filters)");
7458            }
7459            out.println();
7460        }
7461
7462//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7463//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7464//            final List<ResolveInfo> retList = Lists.newArrayList();
7465//            while (i.hasNext()) {
7466//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7467//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7468//                    retList.add(resolveInfo);
7469//                }
7470//            }
7471//            return retList;
7472//        }
7473
7474        // Keys are String (activity class name), values are Activity.
7475        private final ArrayMap<ComponentName, PackageParser.Service> mServices
7476                = new ArrayMap<ComponentName, PackageParser.Service>();
7477        private int mFlags;
7478    };
7479
7480    private final class ProviderIntentResolver
7481            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7482        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7483                boolean defaultOnly, int userId) {
7484            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7485            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7486        }
7487
7488        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7489                int userId) {
7490            if (!sUserManager.exists(userId))
7491                return null;
7492            mFlags = flags;
7493            return super.queryIntent(intent, resolvedType,
7494                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7495        }
7496
7497        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7498                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7499            if (!sUserManager.exists(userId))
7500                return null;
7501            if (packageProviders == null) {
7502                return null;
7503            }
7504            mFlags = flags;
7505            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7506            final int N = packageProviders.size();
7507            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7508                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7509
7510            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7511            for (int i = 0; i < N; ++i) {
7512                intentFilters = packageProviders.get(i).intents;
7513                if (intentFilters != null && intentFilters.size() > 0) {
7514                    PackageParser.ProviderIntentInfo[] array =
7515                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7516                    intentFilters.toArray(array);
7517                    listCut.add(array);
7518                }
7519            }
7520            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7521        }
7522
7523        public final void addProvider(PackageParser.Provider p) {
7524            if (mProviders.containsKey(p.getComponentName())) {
7525                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7526                return;
7527            }
7528
7529            mProviders.put(p.getComponentName(), p);
7530            if (DEBUG_SHOW_INFO) {
7531                Log.v(TAG, "  "
7532                        + (p.info.nonLocalizedLabel != null
7533                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7534                Log.v(TAG, "    Class=" + p.info.name);
7535            }
7536            final int NI = p.intents.size();
7537            int j;
7538            for (j = 0; j < NI; j++) {
7539                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7540                if (DEBUG_SHOW_INFO) {
7541                    Log.v(TAG, "    IntentFilter:");
7542                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7543                }
7544                if (!intent.debugCheck()) {
7545                    Log.w(TAG, "==> For Provider " + p.info.name);
7546                }
7547                addFilter(intent);
7548            }
7549        }
7550
7551        public final void removeProvider(PackageParser.Provider p) {
7552            mProviders.remove(p.getComponentName());
7553            if (DEBUG_SHOW_INFO) {
7554                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7555                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7556                Log.v(TAG, "    Class=" + p.info.name);
7557            }
7558            final int NI = p.intents.size();
7559            int j;
7560            for (j = 0; j < NI; j++) {
7561                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7562                if (DEBUG_SHOW_INFO) {
7563                    Log.v(TAG, "    IntentFilter:");
7564                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7565                }
7566                removeFilter(intent);
7567            }
7568        }
7569
7570        @Override
7571        protected boolean allowFilterResult(
7572                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7573            ProviderInfo filterPi = filter.provider.info;
7574            for (int i = dest.size() - 1; i >= 0; i--) {
7575                ProviderInfo destPi = dest.get(i).providerInfo;
7576                if (destPi.name == filterPi.name
7577                        && destPi.packageName == filterPi.packageName) {
7578                    return false;
7579                }
7580            }
7581            return true;
7582        }
7583
7584        @Override
7585        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7586            return new PackageParser.ProviderIntentInfo[size];
7587        }
7588
7589        @Override
7590        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7591            if (!sUserManager.exists(userId))
7592                return true;
7593            PackageParser.Package p = filter.provider.owner;
7594            if (p != null) {
7595                PackageSetting ps = (PackageSetting) p.mExtras;
7596                if (ps != null) {
7597                    // System apps are never considered stopped for purposes of
7598                    // filtering, because there may be no way for the user to
7599                    // actually re-launch them.
7600                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7601                            && ps.getStopped(userId);
7602                }
7603            }
7604            return false;
7605        }
7606
7607        @Override
7608        protected boolean isPackageForFilter(String packageName,
7609                PackageParser.ProviderIntentInfo info) {
7610            return packageName.equals(info.provider.owner.packageName);
7611        }
7612
7613        @Override
7614        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7615                int match, int userId) {
7616            if (!sUserManager.exists(userId))
7617                return null;
7618            final PackageParser.ProviderIntentInfo info = filter;
7619            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7620                return null;
7621            }
7622            final PackageParser.Provider provider = info.provider;
7623            if (mSafeMode && (provider.info.applicationInfo.flags
7624                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7625                return null;
7626            }
7627            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7628            if (ps == null) {
7629                return null;
7630            }
7631            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7632                    ps.readUserState(userId), userId);
7633            if (pi == null) {
7634                return null;
7635            }
7636            final ResolveInfo res = new ResolveInfo();
7637            res.providerInfo = pi;
7638            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7639                res.filter = filter;
7640            }
7641            res.priority = info.getPriority();
7642            res.preferredOrder = provider.owner.mPreferredOrder;
7643            res.match = match;
7644            res.isDefault = info.hasDefault;
7645            res.labelRes = info.labelRes;
7646            res.nonLocalizedLabel = info.nonLocalizedLabel;
7647            res.icon = info.icon;
7648            res.system = res.providerInfo.applicationInfo.isSystemApp();
7649            return res;
7650        }
7651
7652        @Override
7653        protected void sortResults(List<ResolveInfo> results) {
7654            Collections.sort(results, mResolvePrioritySorter);
7655        }
7656
7657        @Override
7658        protected void dumpFilter(PrintWriter out, String prefix,
7659                PackageParser.ProviderIntentInfo filter) {
7660            out.print(prefix);
7661            out.print(
7662                    Integer.toHexString(System.identityHashCode(filter.provider)));
7663            out.print(' ');
7664            filter.provider.printComponentShortName(out);
7665            out.print(" filter ");
7666            out.println(Integer.toHexString(System.identityHashCode(filter)));
7667        }
7668
7669        @Override
7670        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
7671            return filter.provider;
7672        }
7673
7674        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7675            PackageParser.Provider provider = (PackageParser.Provider)label;
7676            out.print(prefix); out.print(
7677                    Integer.toHexString(System.identityHashCode(provider)));
7678                    out.print(' ');
7679                    provider.printComponentShortName(out);
7680            if (count > 1) {
7681                out.print(" ("); out.print(count); out.print(" filters)");
7682            }
7683            out.println();
7684        }
7685
7686        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
7687                = new ArrayMap<ComponentName, PackageParser.Provider>();
7688        private int mFlags;
7689    };
7690
7691    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7692            new Comparator<ResolveInfo>() {
7693        public int compare(ResolveInfo r1, ResolveInfo r2) {
7694            int v1 = r1.priority;
7695            int v2 = r2.priority;
7696            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7697            if (v1 != v2) {
7698                return (v1 > v2) ? -1 : 1;
7699            }
7700            v1 = r1.preferredOrder;
7701            v2 = r2.preferredOrder;
7702            if (v1 != v2) {
7703                return (v1 > v2) ? -1 : 1;
7704            }
7705            if (r1.isDefault != r2.isDefault) {
7706                return r1.isDefault ? -1 : 1;
7707            }
7708            v1 = r1.match;
7709            v2 = r2.match;
7710            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7711            if (v1 != v2) {
7712                return (v1 > v2) ? -1 : 1;
7713            }
7714            if (r1.system != r2.system) {
7715                return r1.system ? -1 : 1;
7716            }
7717            return 0;
7718        }
7719    };
7720
7721    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7722            new Comparator<ProviderInfo>() {
7723        public int compare(ProviderInfo p1, ProviderInfo p2) {
7724            final int v1 = p1.initOrder;
7725            final int v2 = p2.initOrder;
7726            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7727        }
7728    };
7729
7730    static final void sendPackageBroadcast(String action, String pkg,
7731            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7732            int[] userIds) {
7733        IActivityManager am = ActivityManagerNative.getDefault();
7734        if (am != null) {
7735            try {
7736                if (userIds == null) {
7737                    userIds = am.getRunningUserIds();
7738                }
7739                for (int id : userIds) {
7740                    final Intent intent = new Intent(action,
7741                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7742                    if (extras != null) {
7743                        intent.putExtras(extras);
7744                    }
7745                    if (targetPkg != null) {
7746                        intent.setPackage(targetPkg);
7747                    }
7748                    // Modify the UID when posting to other users
7749                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7750                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7751                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7752                        intent.putExtra(Intent.EXTRA_UID, uid);
7753                    }
7754                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7755                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7756                    if (DEBUG_BROADCASTS) {
7757                        RuntimeException here = new RuntimeException("here");
7758                        here.fillInStackTrace();
7759                        Slog.d(TAG, "Sending to user " + id + ": "
7760                                + intent.toShortString(false, true, false, false)
7761                                + " " + intent.getExtras(), here);
7762                    }
7763                    am.broadcastIntent(null, intent, null, finishedReceiver,
7764                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7765                            finishedReceiver != null, false, id);
7766                }
7767            } catch (RemoteException ex) {
7768            }
7769        }
7770    }
7771
7772    /**
7773     * Check if the external storage media is available. This is true if there
7774     * is a mounted external storage medium or if the external storage is
7775     * emulated.
7776     */
7777    private boolean isExternalMediaAvailable() {
7778        return mMediaMounted || Environment.isExternalStorageEmulated();
7779    }
7780
7781    @Override
7782    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7783        // writer
7784        synchronized (mPackages) {
7785            if (!isExternalMediaAvailable()) {
7786                // If the external storage is no longer mounted at this point,
7787                // the caller may not have been able to delete all of this
7788                // packages files and can not delete any more.  Bail.
7789                return null;
7790            }
7791            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7792            if (lastPackage != null) {
7793                pkgs.remove(lastPackage);
7794            }
7795            if (pkgs.size() > 0) {
7796                return pkgs.get(0);
7797            }
7798        }
7799        return null;
7800    }
7801
7802    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7803        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7804                userId, andCode ? 1 : 0, packageName);
7805        if (mSystemReady) {
7806            msg.sendToTarget();
7807        } else {
7808            if (mPostSystemReadyMessages == null) {
7809                mPostSystemReadyMessages = new ArrayList<>();
7810            }
7811            mPostSystemReadyMessages.add(msg);
7812        }
7813    }
7814
7815    void startCleaningPackages() {
7816        // reader
7817        synchronized (mPackages) {
7818            if (!isExternalMediaAvailable()) {
7819                return;
7820            }
7821            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7822                return;
7823            }
7824        }
7825        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7826        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7827        IActivityManager am = ActivityManagerNative.getDefault();
7828        if (am != null) {
7829            try {
7830                am.startService(null, intent, null, UserHandle.USER_OWNER);
7831            } catch (RemoteException e) {
7832            }
7833        }
7834    }
7835
7836    @Override
7837    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7838            int installFlags, String installerPackageName, VerificationParams verificationParams,
7839            String packageAbiOverride) {
7840        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7841                packageAbiOverride, UserHandle.getCallingUserId());
7842    }
7843
7844    @Override
7845    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7846            int installFlags, String installerPackageName, VerificationParams verificationParams,
7847            String packageAbiOverride, int userId) {
7848        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
7849
7850        final int callingUid = Binder.getCallingUid();
7851        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
7852
7853        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7854            try {
7855                if (observer != null) {
7856                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7857                }
7858            } catch (RemoteException re) {
7859            }
7860            return;
7861        }
7862
7863        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
7864            installFlags |= PackageManager.INSTALL_FROM_ADB;
7865
7866        } else {
7867            // Caller holds INSTALL_PACKAGES permission, so we're less strict
7868            // about installerPackageName.
7869
7870            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
7871            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
7872        }
7873
7874        UserHandle user;
7875        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7876            user = UserHandle.ALL;
7877        } else {
7878            user = new UserHandle(userId);
7879        }
7880
7881        verificationParams.setInstallerUid(callingUid);
7882
7883        final File originFile = new File(originPath);
7884        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7885
7886        final Message msg = mHandler.obtainMessage(INIT_COPY);
7887        msg.obj = new InstallParams(origin, observer, installFlags,
7888                installerPackageName, verificationParams, user, packageAbiOverride);
7889        mHandler.sendMessage(msg);
7890    }
7891
7892    void installStage(String packageName, File stagedDir, String stagedCid,
7893            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7894            String installerPackageName, int installerUid, UserHandle user) {
7895        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7896                params.referrerUri, installerUid, null);
7897
7898        final OriginInfo origin;
7899        if (stagedDir != null) {
7900            origin = OriginInfo.fromStagedFile(stagedDir);
7901        } else {
7902            origin = OriginInfo.fromStagedContainer(stagedCid);
7903        }
7904
7905        final Message msg = mHandler.obtainMessage(INIT_COPY);
7906        msg.obj = new InstallParams(origin, observer, params.installFlags,
7907                installerPackageName, verifParams, user, params.abiOverride);
7908        mHandler.sendMessage(msg);
7909    }
7910
7911    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7912        Bundle extras = new Bundle(1);
7913        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7914
7915        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7916                packageName, extras, null, null, new int[] {userId});
7917        try {
7918            IActivityManager am = ActivityManagerNative.getDefault();
7919            final boolean isSystem =
7920                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7921            if (isSystem && am.isUserRunning(userId, false)) {
7922                // The just-installed/enabled app is bundled on the system, so presumed
7923                // to be able to run automatically without needing an explicit launch.
7924                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7925                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7926                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7927                        .setPackage(packageName);
7928                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7929                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7930            }
7931        } catch (RemoteException e) {
7932            // shouldn't happen
7933            Slog.w(TAG, "Unable to bootstrap installed package", e);
7934        }
7935    }
7936
7937    @Override
7938    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7939            int userId) {
7940        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7941        PackageSetting pkgSetting;
7942        final int uid = Binder.getCallingUid();
7943        enforceCrossUserPermission(uid, userId, true, true,
7944                "setApplicationHiddenSetting for user " + userId);
7945
7946        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7947            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7948            return false;
7949        }
7950
7951        long callingId = Binder.clearCallingIdentity();
7952        try {
7953            boolean sendAdded = false;
7954            boolean sendRemoved = false;
7955            // writer
7956            synchronized (mPackages) {
7957                pkgSetting = mSettings.mPackages.get(packageName);
7958                if (pkgSetting == null) {
7959                    return false;
7960                }
7961                if (pkgSetting.getHidden(userId) != hidden) {
7962                    pkgSetting.setHidden(hidden, userId);
7963                    mSettings.writePackageRestrictionsLPr(userId);
7964                    if (hidden) {
7965                        sendRemoved = true;
7966                    } else {
7967                        sendAdded = true;
7968                    }
7969                }
7970            }
7971            if (sendAdded) {
7972                sendPackageAddedForUser(packageName, pkgSetting, userId);
7973                return true;
7974            }
7975            if (sendRemoved) {
7976                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7977                        "hiding pkg");
7978                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7979            }
7980        } finally {
7981            Binder.restoreCallingIdentity(callingId);
7982        }
7983        return false;
7984    }
7985
7986    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7987            int userId) {
7988        final PackageRemovedInfo info = new PackageRemovedInfo();
7989        info.removedPackage = packageName;
7990        info.removedUsers = new int[] {userId};
7991        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7992        info.sendBroadcast(false, false, false);
7993    }
7994
7995    /**
7996     * Returns true if application is not found or there was an error. Otherwise it returns
7997     * the hidden state of the package for the given user.
7998     */
7999    @Override
8000    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8001        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8002        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8003                false, "getApplicationHidden for user " + userId);
8004        PackageSetting pkgSetting;
8005        long callingId = Binder.clearCallingIdentity();
8006        try {
8007            // writer
8008            synchronized (mPackages) {
8009                pkgSetting = mSettings.mPackages.get(packageName);
8010                if (pkgSetting == null) {
8011                    return true;
8012                }
8013                return pkgSetting.getHidden(userId);
8014            }
8015        } finally {
8016            Binder.restoreCallingIdentity(callingId);
8017        }
8018    }
8019
8020    /**
8021     * @hide
8022     */
8023    @Override
8024    public int installExistingPackageAsUser(String packageName, int userId) {
8025        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8026                null);
8027        PackageSetting pkgSetting;
8028        final int uid = Binder.getCallingUid();
8029        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8030                + userId);
8031        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8032            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8033        }
8034
8035        long callingId = Binder.clearCallingIdentity();
8036        try {
8037            boolean sendAdded = false;
8038            Bundle extras = new Bundle(1);
8039
8040            // writer
8041            synchronized (mPackages) {
8042                pkgSetting = mSettings.mPackages.get(packageName);
8043                if (pkgSetting == null) {
8044                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8045                }
8046                if (!pkgSetting.getInstalled(userId)) {
8047                    pkgSetting.setInstalled(true, userId);
8048                    pkgSetting.setHidden(false, userId);
8049                    mSettings.writePackageRestrictionsLPr(userId);
8050                    sendAdded = true;
8051                }
8052            }
8053
8054            if (sendAdded) {
8055                sendPackageAddedForUser(packageName, pkgSetting, userId);
8056            }
8057        } finally {
8058            Binder.restoreCallingIdentity(callingId);
8059        }
8060
8061        return PackageManager.INSTALL_SUCCEEDED;
8062    }
8063
8064    boolean isUserRestricted(int userId, String restrictionKey) {
8065        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8066        if (restrictions.getBoolean(restrictionKey, false)) {
8067            Log.w(TAG, "User is restricted: " + restrictionKey);
8068            return true;
8069        }
8070        return false;
8071    }
8072
8073    @Override
8074    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8075        mContext.enforceCallingOrSelfPermission(
8076                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8077                "Only package verification agents can verify applications");
8078
8079        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8080        final PackageVerificationResponse response = new PackageVerificationResponse(
8081                verificationCode, Binder.getCallingUid());
8082        msg.arg1 = id;
8083        msg.obj = response;
8084        mHandler.sendMessage(msg);
8085    }
8086
8087    @Override
8088    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8089            long millisecondsToDelay) {
8090        mContext.enforceCallingOrSelfPermission(
8091                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8092                "Only package verification agents can extend verification timeouts");
8093
8094        final PackageVerificationState state = mPendingVerification.get(id);
8095        final PackageVerificationResponse response = new PackageVerificationResponse(
8096                verificationCodeAtTimeout, Binder.getCallingUid());
8097
8098        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8099            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8100        }
8101        if (millisecondsToDelay < 0) {
8102            millisecondsToDelay = 0;
8103        }
8104        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8105                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8106            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8107        }
8108
8109        if ((state != null) && !state.timeoutExtended()) {
8110            state.extendTimeout();
8111
8112            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8113            msg.arg1 = id;
8114            msg.obj = response;
8115            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8116        }
8117    }
8118
8119    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8120            int verificationCode, UserHandle user) {
8121        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8122        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8123        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8124        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8125        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8126
8127        mContext.sendBroadcastAsUser(intent, user,
8128                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8129    }
8130
8131    private ComponentName matchComponentForVerifier(String packageName,
8132            List<ResolveInfo> receivers) {
8133        ActivityInfo targetReceiver = null;
8134
8135        final int NR = receivers.size();
8136        for (int i = 0; i < NR; i++) {
8137            final ResolveInfo info = receivers.get(i);
8138            if (info.activityInfo == null) {
8139                continue;
8140            }
8141
8142            if (packageName.equals(info.activityInfo.packageName)) {
8143                targetReceiver = info.activityInfo;
8144                break;
8145            }
8146        }
8147
8148        if (targetReceiver == null) {
8149            return null;
8150        }
8151
8152        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8153    }
8154
8155    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8156            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8157        if (pkgInfo.verifiers.length == 0) {
8158            return null;
8159        }
8160
8161        final int N = pkgInfo.verifiers.length;
8162        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8163        for (int i = 0; i < N; i++) {
8164            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8165
8166            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8167                    receivers);
8168            if (comp == null) {
8169                continue;
8170            }
8171
8172            final int verifierUid = getUidForVerifier(verifierInfo);
8173            if (verifierUid == -1) {
8174                continue;
8175            }
8176
8177            if (DEBUG_VERIFY) {
8178                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8179                        + " with the correct signature");
8180            }
8181            sufficientVerifiers.add(comp);
8182            verificationState.addSufficientVerifier(verifierUid);
8183        }
8184
8185        return sufficientVerifiers;
8186    }
8187
8188    private int getUidForVerifier(VerifierInfo verifierInfo) {
8189        synchronized (mPackages) {
8190            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8191            if (pkg == null) {
8192                return -1;
8193            } else if (pkg.mSignatures.length != 1) {
8194                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8195                        + " has more than one signature; ignoring");
8196                return -1;
8197            }
8198
8199            /*
8200             * If the public key of the package's signature does not match
8201             * our expected public key, then this is a different package and
8202             * we should skip.
8203             */
8204
8205            final byte[] expectedPublicKey;
8206            try {
8207                final Signature verifierSig = pkg.mSignatures[0];
8208                final PublicKey publicKey = verifierSig.getPublicKey();
8209                expectedPublicKey = publicKey.getEncoded();
8210            } catch (CertificateException e) {
8211                return -1;
8212            }
8213
8214            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8215
8216            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8217                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8218                        + " does not have the expected public key; ignoring");
8219                return -1;
8220            }
8221
8222            return pkg.applicationInfo.uid;
8223        }
8224    }
8225
8226    @Override
8227    public void finishPackageInstall(int token) {
8228        enforceSystemOrRoot("Only the system is allowed to finish installs");
8229
8230        if (DEBUG_INSTALL) {
8231            Slog.v(TAG, "BM finishing package install for " + token);
8232        }
8233
8234        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8235        mHandler.sendMessage(msg);
8236    }
8237
8238    /**
8239     * Get the verification agent timeout.
8240     *
8241     * @return verification timeout in milliseconds
8242     */
8243    private long getVerificationTimeout() {
8244        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8245                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8246                DEFAULT_VERIFICATION_TIMEOUT);
8247    }
8248
8249    /**
8250     * Get the default verification agent response code.
8251     *
8252     * @return default verification response code
8253     */
8254    private int getDefaultVerificationResponse() {
8255        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8256                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8257                DEFAULT_VERIFICATION_RESPONSE);
8258    }
8259
8260    /**
8261     * Check whether or not package verification has been enabled.
8262     *
8263     * @return true if verification should be performed
8264     */
8265    private boolean isVerificationEnabled(int userId, int installFlags) {
8266        if (!DEFAULT_VERIFY_ENABLE) {
8267            return false;
8268        }
8269
8270        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8271
8272        // Check if installing from ADB
8273        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8274            // Do not run verification in a test harness environment
8275            if (ActivityManager.isRunningInTestHarness()) {
8276                return false;
8277            }
8278            if (ensureVerifyAppsEnabled) {
8279                return true;
8280            }
8281            // Check if the developer does not want package verification for ADB installs
8282            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8283                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8284                return false;
8285            }
8286        }
8287
8288        if (ensureVerifyAppsEnabled) {
8289            return true;
8290        }
8291
8292        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8293                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8294    }
8295
8296    /**
8297     * Get the "allow unknown sources" setting.
8298     *
8299     * @return the current "allow unknown sources" setting
8300     */
8301    private int getUnknownSourcesSettings() {
8302        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8303                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8304                -1);
8305    }
8306
8307    @Override
8308    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8309        final int uid = Binder.getCallingUid();
8310        // writer
8311        synchronized (mPackages) {
8312            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8313            if (targetPackageSetting == null) {
8314                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8315            }
8316
8317            PackageSetting installerPackageSetting;
8318            if (installerPackageName != null) {
8319                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8320                if (installerPackageSetting == null) {
8321                    throw new IllegalArgumentException("Unknown installer package: "
8322                            + installerPackageName);
8323                }
8324            } else {
8325                installerPackageSetting = null;
8326            }
8327
8328            Signature[] callerSignature;
8329            Object obj = mSettings.getUserIdLPr(uid);
8330            if (obj != null) {
8331                if (obj instanceof SharedUserSetting) {
8332                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8333                } else if (obj instanceof PackageSetting) {
8334                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8335                } else {
8336                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8337                }
8338            } else {
8339                throw new SecurityException("Unknown calling uid " + uid);
8340            }
8341
8342            // Verify: can't set installerPackageName to a package that is
8343            // not signed with the same cert as the caller.
8344            if (installerPackageSetting != null) {
8345                if (compareSignatures(callerSignature,
8346                        installerPackageSetting.signatures.mSignatures)
8347                        != PackageManager.SIGNATURE_MATCH) {
8348                    throw new SecurityException(
8349                            "Caller does not have same cert as new installer package "
8350                            + installerPackageName);
8351                }
8352            }
8353
8354            // Verify: if target already has an installer package, it must
8355            // be signed with the same cert as the caller.
8356            if (targetPackageSetting.installerPackageName != null) {
8357                PackageSetting setting = mSettings.mPackages.get(
8358                        targetPackageSetting.installerPackageName);
8359                // If the currently set package isn't valid, then it's always
8360                // okay to change it.
8361                if (setting != null) {
8362                    if (compareSignatures(callerSignature,
8363                            setting.signatures.mSignatures)
8364                            != PackageManager.SIGNATURE_MATCH) {
8365                        throw new SecurityException(
8366                                "Caller does not have same cert as old installer package "
8367                                + targetPackageSetting.installerPackageName);
8368                    }
8369                }
8370            }
8371
8372            // Okay!
8373            targetPackageSetting.installerPackageName = installerPackageName;
8374            scheduleWriteSettingsLocked();
8375        }
8376    }
8377
8378    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8379        // Queue up an async operation since the package installation may take a little while.
8380        mHandler.post(new Runnable() {
8381            public void run() {
8382                mHandler.removeCallbacks(this);
8383                 // Result object to be returned
8384                PackageInstalledInfo res = new PackageInstalledInfo();
8385                res.returnCode = currentStatus;
8386                res.uid = -1;
8387                res.pkg = null;
8388                res.removedInfo = new PackageRemovedInfo();
8389                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8390                    args.doPreInstall(res.returnCode);
8391                    synchronized (mInstallLock) {
8392                        installPackageLI(args, res);
8393                    }
8394                    args.doPostInstall(res.returnCode, res.uid);
8395                }
8396
8397                // A restore should be performed at this point if (a) the install
8398                // succeeded, (b) the operation is not an update, and (c) the new
8399                // package has not opted out of backup participation.
8400                final boolean update = res.removedInfo.removedPackage != null;
8401                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8402                boolean doRestore = !update
8403                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8404
8405                // Set up the post-install work request bookkeeping.  This will be used
8406                // and cleaned up by the post-install event handling regardless of whether
8407                // there's a restore pass performed.  Token values are >= 1.
8408                int token;
8409                if (mNextInstallToken < 0) mNextInstallToken = 1;
8410                token = mNextInstallToken++;
8411
8412                PostInstallData data = new PostInstallData(args, res);
8413                mRunningInstalls.put(token, data);
8414                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8415
8416                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8417                    // Pass responsibility to the Backup Manager.  It will perform a
8418                    // restore if appropriate, then pass responsibility back to the
8419                    // Package Manager to run the post-install observer callbacks
8420                    // and broadcasts.
8421                    IBackupManager bm = IBackupManager.Stub.asInterface(
8422                            ServiceManager.getService(Context.BACKUP_SERVICE));
8423                    if (bm != null) {
8424                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8425                                + " to BM for possible restore");
8426                        try {
8427                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
8428                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8429                            } else {
8430                                doRestore = false;
8431                            }
8432                        } catch (RemoteException e) {
8433                            // can't happen; the backup manager is local
8434                        } catch (Exception e) {
8435                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8436                            doRestore = false;
8437                        }
8438                    } else {
8439                        Slog.e(TAG, "Backup Manager not found!");
8440                        doRestore = false;
8441                    }
8442                }
8443
8444                if (!doRestore) {
8445                    // No restore possible, or the Backup Manager was mysteriously not
8446                    // available -- just fire the post-install work request directly.
8447                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8448                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8449                    mHandler.sendMessage(msg);
8450                }
8451            }
8452        });
8453    }
8454
8455    private abstract class HandlerParams {
8456        private static final int MAX_RETRIES = 4;
8457
8458        /**
8459         * Number of times startCopy() has been attempted and had a non-fatal
8460         * error.
8461         */
8462        private int mRetries = 0;
8463
8464        /** User handle for the user requesting the information or installation. */
8465        private final UserHandle mUser;
8466
8467        HandlerParams(UserHandle user) {
8468            mUser = user;
8469        }
8470
8471        UserHandle getUser() {
8472            return mUser;
8473        }
8474
8475        final boolean startCopy() {
8476            boolean res;
8477            try {
8478                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8479
8480                if (++mRetries > MAX_RETRIES) {
8481                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8482                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8483                    handleServiceError();
8484                    return false;
8485                } else {
8486                    handleStartCopy();
8487                    res = true;
8488                }
8489            } catch (RemoteException e) {
8490                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8491                mHandler.sendEmptyMessage(MCS_RECONNECT);
8492                res = false;
8493            }
8494            handleReturnCode();
8495            return res;
8496        }
8497
8498        final void serviceError() {
8499            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8500            handleServiceError();
8501            handleReturnCode();
8502        }
8503
8504        abstract void handleStartCopy() throws RemoteException;
8505        abstract void handleServiceError();
8506        abstract void handleReturnCode();
8507    }
8508
8509    class MeasureParams extends HandlerParams {
8510        private final PackageStats mStats;
8511        private boolean mSuccess;
8512
8513        private final IPackageStatsObserver mObserver;
8514
8515        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8516            super(new UserHandle(stats.userHandle));
8517            mObserver = observer;
8518            mStats = stats;
8519        }
8520
8521        @Override
8522        public String toString() {
8523            return "MeasureParams{"
8524                + Integer.toHexString(System.identityHashCode(this))
8525                + " " + mStats.packageName + "}";
8526        }
8527
8528        @Override
8529        void handleStartCopy() throws RemoteException {
8530            synchronized (mInstallLock) {
8531                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8532            }
8533
8534            if (mSuccess) {
8535                final boolean mounted;
8536                if (Environment.isExternalStorageEmulated()) {
8537                    mounted = true;
8538                } else {
8539                    final String status = Environment.getExternalStorageState();
8540                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8541                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8542                }
8543
8544                if (mounted) {
8545                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8546
8547                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8548                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8549
8550                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8551                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8552
8553                    // Always subtract cache size, since it's a subdirectory
8554                    mStats.externalDataSize -= mStats.externalCacheSize;
8555
8556                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8557                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8558
8559                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8560                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8561                }
8562            }
8563        }
8564
8565        @Override
8566        void handleReturnCode() {
8567            if (mObserver != null) {
8568                try {
8569                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8570                } catch (RemoteException e) {
8571                    Slog.i(TAG, "Observer no longer exists.");
8572                }
8573            }
8574        }
8575
8576        @Override
8577        void handleServiceError() {
8578            Slog.e(TAG, "Could not measure application " + mStats.packageName
8579                            + " external storage");
8580        }
8581    }
8582
8583    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8584            throws RemoteException {
8585        long result = 0;
8586        for (File path : paths) {
8587            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8588        }
8589        return result;
8590    }
8591
8592    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8593        for (File path : paths) {
8594            try {
8595                mcs.clearDirectory(path.getAbsolutePath());
8596            } catch (RemoteException e) {
8597            }
8598        }
8599    }
8600
8601    static class OriginInfo {
8602        /**
8603         * Location where install is coming from, before it has been
8604         * copied/renamed into place. This could be a single monolithic APK
8605         * file, or a cluster directory. This location may be untrusted.
8606         */
8607        final File file;
8608        final String cid;
8609
8610        /**
8611         * Flag indicating that {@link #file} or {@link #cid} has already been
8612         * staged, meaning downstream users don't need to defensively copy the
8613         * contents.
8614         */
8615        final boolean staged;
8616
8617        /**
8618         * Flag indicating that {@link #file} or {@link #cid} is an already
8619         * installed app that is being moved.
8620         */
8621        final boolean existing;
8622
8623        final String resolvedPath;
8624        final File resolvedFile;
8625
8626        static OriginInfo fromNothing() {
8627            return new OriginInfo(null, null, false, false);
8628        }
8629
8630        static OriginInfo fromUntrustedFile(File file) {
8631            return new OriginInfo(file, null, false, false);
8632        }
8633
8634        static OriginInfo fromExistingFile(File file) {
8635            return new OriginInfo(file, null, false, true);
8636        }
8637
8638        static OriginInfo fromStagedFile(File file) {
8639            return new OriginInfo(file, null, true, false);
8640        }
8641
8642        static OriginInfo fromStagedContainer(String cid) {
8643            return new OriginInfo(null, cid, true, false);
8644        }
8645
8646        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8647            this.file = file;
8648            this.cid = cid;
8649            this.staged = staged;
8650            this.existing = existing;
8651
8652            if (cid != null) {
8653                resolvedPath = PackageHelper.getSdDir(cid);
8654                resolvedFile = new File(resolvedPath);
8655            } else if (file != null) {
8656                resolvedPath = file.getAbsolutePath();
8657                resolvedFile = file;
8658            } else {
8659                resolvedPath = null;
8660                resolvedFile = null;
8661            }
8662        }
8663    }
8664
8665    class InstallParams extends HandlerParams {
8666        final OriginInfo origin;
8667        final IPackageInstallObserver2 observer;
8668        int installFlags;
8669        final String installerPackageName;
8670        final VerificationParams verificationParams;
8671        private InstallArgs mArgs;
8672        private int mRet;
8673        final String packageAbiOverride;
8674
8675        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8676                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8677                String packageAbiOverride) {
8678            super(user);
8679            this.origin = origin;
8680            this.observer = observer;
8681            this.installFlags = installFlags;
8682            this.installerPackageName = installerPackageName;
8683            this.verificationParams = verificationParams;
8684            this.packageAbiOverride = packageAbiOverride;
8685        }
8686
8687        @Override
8688        public String toString() {
8689            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8690                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8691        }
8692
8693        public ManifestDigest getManifestDigest() {
8694            if (verificationParams == null) {
8695                return null;
8696            }
8697            return verificationParams.getManifestDigest();
8698        }
8699
8700        private int installLocationPolicy(PackageInfoLite pkgLite) {
8701            String packageName = pkgLite.packageName;
8702            int installLocation = pkgLite.installLocation;
8703            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8704            // reader
8705            synchronized (mPackages) {
8706                PackageParser.Package pkg = mPackages.get(packageName);
8707                if (pkg != null) {
8708                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8709                        // Check for downgrading.
8710                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8711                            try {
8712                                checkDowngrade(pkg, pkgLite);
8713                            } catch (PackageManagerException e) {
8714                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
8715                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8716                            }
8717                        }
8718                        // Check for updated system application.
8719                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8720                            if (onSd) {
8721                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8722                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8723                            }
8724                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8725                        } else {
8726                            if (onSd) {
8727                                // Install flag overrides everything.
8728                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8729                            }
8730                            // If current upgrade specifies particular preference
8731                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8732                                // Application explicitly specified internal.
8733                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8734                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8735                                // App explictly prefers external. Let policy decide
8736                            } else {
8737                                // Prefer previous location
8738                                if (isExternal(pkg)) {
8739                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8740                                }
8741                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8742                            }
8743                        }
8744                    } else {
8745                        // Invalid install. Return error code
8746                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8747                    }
8748                }
8749            }
8750            // All the special cases have been taken care of.
8751            // Return result based on recommended install location.
8752            if (onSd) {
8753                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8754            }
8755            return pkgLite.recommendedInstallLocation;
8756        }
8757
8758        /*
8759         * Invoke remote method to get package information and install
8760         * location values. Override install location based on default
8761         * policy if needed and then create install arguments based
8762         * on the install location.
8763         */
8764        public void handleStartCopy() throws RemoteException {
8765            int ret = PackageManager.INSTALL_SUCCEEDED;
8766
8767            // If we're already staged, we've firmly committed to an install location
8768            if (origin.staged) {
8769                if (origin.file != null) {
8770                    installFlags |= PackageManager.INSTALL_INTERNAL;
8771                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8772                } else if (origin.cid != null) {
8773                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8774                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8775                } else {
8776                    throw new IllegalStateException("Invalid stage location");
8777                }
8778            }
8779
8780            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8781            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8782
8783            PackageInfoLite pkgLite = null;
8784
8785            if (onInt && onSd) {
8786                // Check if both bits are set.
8787                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8788                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8789            } else {
8790                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8791                        packageAbiOverride);
8792
8793                /*
8794                 * If we have too little free space, try to free cache
8795                 * before giving up.
8796                 */
8797                if (!origin.staged && pkgLite.recommendedInstallLocation
8798                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8799                    // TODO: focus freeing disk space on the target device
8800                    final StorageManager storage = StorageManager.from(mContext);
8801                    final long lowThreshold = storage.getStorageLowBytes(
8802                            Environment.getDataDirectory());
8803
8804                    final long sizeBytes = mContainerService.calculateInstalledSize(
8805                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8806
8807                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8808                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8809                                installFlags, packageAbiOverride);
8810                    }
8811
8812                    /*
8813                     * The cache free must have deleted the file we
8814                     * downloaded to install.
8815                     *
8816                     * TODO: fix the "freeCache" call to not delete
8817                     *       the file we care about.
8818                     */
8819                    if (pkgLite.recommendedInstallLocation
8820                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8821                        pkgLite.recommendedInstallLocation
8822                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8823                    }
8824                }
8825            }
8826
8827            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8828                int loc = pkgLite.recommendedInstallLocation;
8829                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8830                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8831                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8832                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8833                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8834                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8835                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8836                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8837                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8838                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8839                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8840                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8841                } else {
8842                    // Override with defaults if needed.
8843                    loc = installLocationPolicy(pkgLite);
8844                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8845                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8846                    } else if (!onSd && !onInt) {
8847                        // Override install location with flags
8848                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8849                            // Set the flag to install on external media.
8850                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8851                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8852                        } else {
8853                            // Make sure the flag for installing on external
8854                            // media is unset
8855                            installFlags |= PackageManager.INSTALL_INTERNAL;
8856                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8857                        }
8858                    }
8859                }
8860            }
8861
8862            final InstallArgs args = createInstallArgs(this);
8863            mArgs = args;
8864
8865            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8866                 /*
8867                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8868                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8869                 */
8870                int userIdentifier = getUser().getIdentifier();
8871                if (userIdentifier == UserHandle.USER_ALL
8872                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8873                    userIdentifier = UserHandle.USER_OWNER;
8874                }
8875
8876                /*
8877                 * Determine if we have any installed package verifiers. If we
8878                 * do, then we'll defer to them to verify the packages.
8879                 */
8880                final int requiredUid = mRequiredVerifierPackage == null ? -1
8881                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8882                if (!origin.existing && requiredUid != -1
8883                        && isVerificationEnabled(userIdentifier, installFlags)) {
8884                    final Intent verification = new Intent(
8885                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8886                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
8887                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8888                            PACKAGE_MIME_TYPE);
8889                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8890
8891                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8892                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8893                            0 /* TODO: Which userId? */);
8894
8895                    if (DEBUG_VERIFY) {
8896                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8897                                + verification.toString() + " with " + pkgLite.verifiers.length
8898                                + " optional verifiers");
8899                    }
8900
8901                    final int verificationId = mPendingVerificationToken++;
8902
8903                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8904
8905                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8906                            installerPackageName);
8907
8908                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8909                            installFlags);
8910
8911                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8912                            pkgLite.packageName);
8913
8914                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8915                            pkgLite.versionCode);
8916
8917                    if (verificationParams != null) {
8918                        if (verificationParams.getVerificationURI() != null) {
8919                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8920                                 verificationParams.getVerificationURI());
8921                        }
8922                        if (verificationParams.getOriginatingURI() != null) {
8923                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8924                                  verificationParams.getOriginatingURI());
8925                        }
8926                        if (verificationParams.getReferrer() != null) {
8927                            verification.putExtra(Intent.EXTRA_REFERRER,
8928                                  verificationParams.getReferrer());
8929                        }
8930                        if (verificationParams.getOriginatingUid() >= 0) {
8931                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8932                                  verificationParams.getOriginatingUid());
8933                        }
8934                        if (verificationParams.getInstallerUid() >= 0) {
8935                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8936                                  verificationParams.getInstallerUid());
8937                        }
8938                    }
8939
8940                    final PackageVerificationState verificationState = new PackageVerificationState(
8941                            requiredUid, args);
8942
8943                    mPendingVerification.append(verificationId, verificationState);
8944
8945                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8946                            receivers, verificationState);
8947
8948                    /*
8949                     * If any sufficient verifiers were listed in the package
8950                     * manifest, attempt to ask them.
8951                     */
8952                    if (sufficientVerifiers != null) {
8953                        final int N = sufficientVerifiers.size();
8954                        if (N == 0) {
8955                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8956                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8957                        } else {
8958                            for (int i = 0; i < N; i++) {
8959                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8960
8961                                final Intent sufficientIntent = new Intent(verification);
8962                                sufficientIntent.setComponent(verifierComponent);
8963
8964                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8965                            }
8966                        }
8967                    }
8968
8969                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8970                            mRequiredVerifierPackage, receivers);
8971                    if (ret == PackageManager.INSTALL_SUCCEEDED
8972                            && mRequiredVerifierPackage != null) {
8973                        /*
8974                         * Send the intent to the required verification agent,
8975                         * but only start the verification timeout after the
8976                         * target BroadcastReceivers have run.
8977                         */
8978                        verification.setComponent(requiredVerifierComponent);
8979                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8980                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8981                                new BroadcastReceiver() {
8982                                    @Override
8983                                    public void onReceive(Context context, Intent intent) {
8984                                        final Message msg = mHandler
8985                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8986                                        msg.arg1 = verificationId;
8987                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8988                                    }
8989                                }, null, 0, null, null);
8990
8991                        /*
8992                         * We don't want the copy to proceed until verification
8993                         * succeeds, so null out this field.
8994                         */
8995                        mArgs = null;
8996                    }
8997                } else {
8998                    /*
8999                     * No package verification is enabled, so immediately start
9000                     * the remote call to initiate copy using temporary file.
9001                     */
9002                    ret = args.copyApk(mContainerService, true);
9003                }
9004            }
9005
9006            mRet = ret;
9007        }
9008
9009        @Override
9010        void handleReturnCode() {
9011            // If mArgs is null, then MCS couldn't be reached. When it
9012            // reconnects, it will try again to install. At that point, this
9013            // will succeed.
9014            if (mArgs != null) {
9015                processPendingInstall(mArgs, mRet);
9016            }
9017        }
9018
9019        @Override
9020        void handleServiceError() {
9021            mArgs = createInstallArgs(this);
9022            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9023        }
9024
9025        public boolean isForwardLocked() {
9026            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9027        }
9028    }
9029
9030    /**
9031     * Used during creation of InstallArgs
9032     *
9033     * @param installFlags package installation flags
9034     * @return true if should be installed on external storage
9035     */
9036    private static boolean installOnSd(int installFlags) {
9037        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9038            return false;
9039        }
9040        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9041            return true;
9042        }
9043        return false;
9044    }
9045
9046    /**
9047     * Used during creation of InstallArgs
9048     *
9049     * @param installFlags package installation flags
9050     * @return true if should be installed as forward locked
9051     */
9052    private static boolean installForwardLocked(int installFlags) {
9053        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9054    }
9055
9056    private InstallArgs createInstallArgs(InstallParams params) {
9057        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
9058            return new AsecInstallArgs(params);
9059        } else {
9060            return new FileInstallArgs(params);
9061        }
9062    }
9063
9064    /**
9065     * Create args that describe an existing installed package. Typically used
9066     * when cleaning up old installs, or used as a move source.
9067     */
9068    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9069            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9070        final boolean isInAsec;
9071        if (installOnSd(installFlags)) {
9072            /* Apps on SD card are always in ASEC containers. */
9073            isInAsec = true;
9074        } else if (installForwardLocked(installFlags)
9075                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9076            /*
9077             * Forward-locked apps are only in ASEC containers if they're the
9078             * new style
9079             */
9080            isInAsec = true;
9081        } else {
9082            isInAsec = false;
9083        }
9084
9085        if (isInAsec) {
9086            return new AsecInstallArgs(codePath, instructionSets,
9087                    installOnSd(installFlags), installForwardLocked(installFlags));
9088        } else {
9089            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9090                    instructionSets);
9091        }
9092    }
9093
9094    static abstract class InstallArgs {
9095        /** @see InstallParams#origin */
9096        final OriginInfo origin;
9097
9098        final IPackageInstallObserver2 observer;
9099        // Always refers to PackageManager flags only
9100        final int installFlags;
9101        final String installerPackageName;
9102        final ManifestDigest manifestDigest;
9103        final UserHandle user;
9104        final String abiOverride;
9105
9106        // The list of instruction sets supported by this app. This is currently
9107        // only used during the rmdex() phase to clean up resources. We can get rid of this
9108        // if we move dex files under the common app path.
9109        /* nullable */ String[] instructionSets;
9110
9111        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9112                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9113                String[] instructionSets, String abiOverride) {
9114            this.origin = origin;
9115            this.installFlags = installFlags;
9116            this.observer = observer;
9117            this.installerPackageName = installerPackageName;
9118            this.manifestDigest = manifestDigest;
9119            this.user = user;
9120            this.instructionSets = instructionSets;
9121            this.abiOverride = abiOverride;
9122        }
9123
9124        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9125        abstract int doPreInstall(int status);
9126
9127        /**
9128         * Rename package into final resting place. All paths on the given
9129         * scanned package should be updated to reflect the rename.
9130         */
9131        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9132        abstract int doPostInstall(int status, int uid);
9133
9134        /** @see PackageSettingBase#codePathString */
9135        abstract String getCodePath();
9136        /** @see PackageSettingBase#resourcePathString */
9137        abstract String getResourcePath();
9138        abstract String getLegacyNativeLibraryPath();
9139
9140        // Need installer lock especially for dex file removal.
9141        abstract void cleanUpResourcesLI();
9142        abstract boolean doPostDeleteLI(boolean delete);
9143        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9144
9145        /**
9146         * Called before the source arguments are copied. This is used mostly
9147         * for MoveParams when it needs to read the source file to put it in the
9148         * destination.
9149         */
9150        int doPreCopy() {
9151            return PackageManager.INSTALL_SUCCEEDED;
9152        }
9153
9154        /**
9155         * Called after the source arguments are copied. This is used mostly for
9156         * MoveParams when it needs to read the source file to put it in the
9157         * destination.
9158         *
9159         * @return
9160         */
9161        int doPostCopy(int uid) {
9162            return PackageManager.INSTALL_SUCCEEDED;
9163        }
9164
9165        protected boolean isFwdLocked() {
9166            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9167        }
9168
9169        protected boolean isExternal() {
9170            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9171        }
9172
9173        UserHandle getUser() {
9174            return user;
9175        }
9176    }
9177
9178    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
9179        if (!allCodePaths.isEmpty()) {
9180            if (instructionSets == null) {
9181                throw new IllegalStateException("instructionSet == null");
9182            }
9183            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9184            for (String codePath : allCodePaths) {
9185                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9186                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9187                    if (retCode < 0) {
9188                        Slog.w(TAG, "Couldn't remove dex file for package: "
9189                                + " at location " + codePath + ", retcode=" + retCode);
9190                        // we don't consider this to be a failure of the core package deletion
9191                    }
9192                }
9193            }
9194        }
9195    }
9196
9197    /**
9198     * Logic to handle installation of non-ASEC applications, including copying
9199     * and renaming logic.
9200     */
9201    class FileInstallArgs extends InstallArgs {
9202        private File codeFile;
9203        private File resourceFile;
9204        private File legacyNativeLibraryPath;
9205
9206        // Example topology:
9207        // /data/app/com.example/base.apk
9208        // /data/app/com.example/split_foo.apk
9209        // /data/app/com.example/lib/arm/libfoo.so
9210        // /data/app/com.example/lib/arm64/libfoo.so
9211        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9212
9213        /** New install */
9214        FileInstallArgs(InstallParams params) {
9215            super(params.origin, params.observer, params.installFlags,
9216                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9217                    null /* instruction sets */, params.packageAbiOverride);
9218            if (isFwdLocked()) {
9219                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9220            }
9221        }
9222
9223        /** Existing install */
9224        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9225                String[] instructionSets) {
9226            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9227            this.codeFile = (codePath != null) ? new File(codePath) : null;
9228            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9229            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9230                    new File(legacyNativeLibraryPath) : null;
9231        }
9232
9233        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9234            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9235                    isFwdLocked(), abiOverride);
9236
9237            final StorageManager storage = StorageManager.from(mContext);
9238            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9239        }
9240
9241        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9242            if (origin.staged) {
9243                Slog.d(TAG, origin.file + " already staged; skipping copy");
9244                codeFile = origin.file;
9245                resourceFile = origin.file;
9246                return PackageManager.INSTALL_SUCCEEDED;
9247            }
9248
9249            try {
9250                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9251                codeFile = tempDir;
9252                resourceFile = tempDir;
9253            } catch (IOException e) {
9254                Slog.w(TAG, "Failed to create copy file: " + e);
9255                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9256            }
9257
9258            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9259                @Override
9260                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9261                    if (!FileUtils.isValidExtFilename(name)) {
9262                        throw new IllegalArgumentException("Invalid filename: " + name);
9263                    }
9264                    try {
9265                        final File file = new File(codeFile, name);
9266                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9267                                O_RDWR | O_CREAT, 0644);
9268                        Os.chmod(file.getAbsolutePath(), 0644);
9269                        return new ParcelFileDescriptor(fd);
9270                    } catch (ErrnoException e) {
9271                        throw new RemoteException("Failed to open: " + e.getMessage());
9272                    }
9273                }
9274            };
9275
9276            int ret = PackageManager.INSTALL_SUCCEEDED;
9277            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9278            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9279                Slog.e(TAG, "Failed to copy package");
9280                return ret;
9281            }
9282
9283            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9284            NativeLibraryHelper.Handle handle = null;
9285            try {
9286                handle = NativeLibraryHelper.Handle.create(codeFile);
9287                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9288                        abiOverride);
9289            } catch (IOException e) {
9290                Slog.e(TAG, "Copying native libraries failed", e);
9291                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9292            } finally {
9293                IoUtils.closeQuietly(handle);
9294            }
9295
9296            return ret;
9297        }
9298
9299        int doPreInstall(int status) {
9300            if (status != PackageManager.INSTALL_SUCCEEDED) {
9301                cleanUp();
9302            }
9303            return status;
9304        }
9305
9306        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9307            if (status != PackageManager.INSTALL_SUCCEEDED) {
9308                cleanUp();
9309                return false;
9310            } else {
9311                final File beforeCodeFile = codeFile;
9312                final File afterCodeFile = getNextCodePath(pkg.packageName);
9313
9314                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9315                try {
9316                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9317                } catch (ErrnoException e) {
9318                    Slog.d(TAG, "Failed to rename", e);
9319                    return false;
9320                }
9321
9322                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9323                    Slog.d(TAG, "Failed to restorecon");
9324                    return false;
9325                }
9326
9327                // Reflect the rename internally
9328                codeFile = afterCodeFile;
9329                resourceFile = afterCodeFile;
9330
9331                // Reflect the rename in scanned details
9332                pkg.codePath = afterCodeFile.getAbsolutePath();
9333                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9334                        pkg.baseCodePath);
9335                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9336                        pkg.splitCodePaths);
9337
9338                // Reflect the rename in app info
9339                pkg.applicationInfo.setCodePath(pkg.codePath);
9340                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9341                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9342                pkg.applicationInfo.setResourcePath(pkg.codePath);
9343                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9344                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9345
9346                return true;
9347            }
9348        }
9349
9350        int doPostInstall(int status, int uid) {
9351            if (status != PackageManager.INSTALL_SUCCEEDED) {
9352                cleanUp();
9353            }
9354            return status;
9355        }
9356
9357        @Override
9358        String getCodePath() {
9359            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9360        }
9361
9362        @Override
9363        String getResourcePath() {
9364            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9365        }
9366
9367        @Override
9368        String getLegacyNativeLibraryPath() {
9369            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9370        }
9371
9372        private boolean cleanUp() {
9373            if (codeFile == null || !codeFile.exists()) {
9374                return false;
9375            }
9376
9377            if (codeFile.isDirectory()) {
9378                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
9379            } else {
9380                codeFile.delete();
9381            }
9382
9383            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9384                resourceFile.delete();
9385            }
9386
9387            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9388                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9389                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9390                }
9391                legacyNativeLibraryPath.delete();
9392            }
9393
9394            return true;
9395        }
9396
9397        void cleanUpResourcesLI() {
9398            // Try enumerating all code paths before deleting
9399            List<String> allCodePaths = Collections.EMPTY_LIST;
9400            if (codeFile != null && codeFile.exists()) {
9401                try {
9402                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9403                    allCodePaths = pkg.getAllCodePaths();
9404                } catch (PackageParserException e) {
9405                    // Ignored; we tried our best
9406                }
9407            }
9408
9409            cleanUp();
9410            removeDexFiles(allCodePaths, instructionSets);
9411        }
9412
9413        boolean doPostDeleteLI(boolean delete) {
9414            // XXX err, shouldn't we respect the delete flag?
9415            cleanUpResourcesLI();
9416            return true;
9417        }
9418    }
9419
9420    private boolean isAsecExternal(String cid) {
9421        final String asecPath = PackageHelper.getSdFilesystem(cid);
9422        return !asecPath.startsWith(mAsecInternalPath);
9423    }
9424
9425    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9426            PackageManagerException {
9427        if (copyRet < 0) {
9428            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9429                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9430                throw new PackageManagerException(copyRet, message);
9431            }
9432        }
9433    }
9434
9435    /**
9436     * Extract the MountService "container ID" from the full code path of an
9437     * .apk.
9438     */
9439    static String cidFromCodePath(String fullCodePath) {
9440        int eidx = fullCodePath.lastIndexOf("/");
9441        String subStr1 = fullCodePath.substring(0, eidx);
9442        int sidx = subStr1.lastIndexOf("/");
9443        return subStr1.substring(sidx+1, eidx);
9444    }
9445
9446    /**
9447     * Logic to handle installation of ASEC applications, including copying and
9448     * renaming logic.
9449     */
9450    class AsecInstallArgs extends InstallArgs {
9451        static final String RES_FILE_NAME = "pkg.apk";
9452        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9453
9454        String cid;
9455        String packagePath;
9456        String resourcePath;
9457        String legacyNativeLibraryDir;
9458
9459        /** New install */
9460        AsecInstallArgs(InstallParams params) {
9461            super(params.origin, params.observer, params.installFlags,
9462                    params.installerPackageName, params.getManifestDigest(),
9463                    params.getUser(), null /* instruction sets */,
9464                    params.packageAbiOverride);
9465        }
9466
9467        /** Existing install */
9468        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9469                        boolean isExternal, boolean isForwardLocked) {
9470            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9471                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9472                    instructionSets, null);
9473            // Hackily pretend we're still looking at a full code path
9474            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9475                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9476            }
9477
9478            // Extract cid from fullCodePath
9479            int eidx = fullCodePath.lastIndexOf("/");
9480            String subStr1 = fullCodePath.substring(0, eidx);
9481            int sidx = subStr1.lastIndexOf("/");
9482            cid = subStr1.substring(sidx+1, eidx);
9483            setMountPath(subStr1);
9484        }
9485
9486        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9487            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9488                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9489                    instructionSets, null);
9490            this.cid = cid;
9491            setMountPath(PackageHelper.getSdDir(cid));
9492        }
9493
9494        void createCopyFile() {
9495            cid = mInstallerService.allocateExternalStageCidLegacy();
9496        }
9497
9498        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9499            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9500                    abiOverride);
9501
9502            final File target;
9503            if (isExternal()) {
9504                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9505            } else {
9506                target = Environment.getDataDirectory();
9507            }
9508
9509            final StorageManager storage = StorageManager.from(mContext);
9510            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9511        }
9512
9513        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9514            if (origin.staged) {
9515                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9516                cid = origin.cid;
9517                setMountPath(PackageHelper.getSdDir(cid));
9518                return PackageManager.INSTALL_SUCCEEDED;
9519            }
9520
9521            if (temp) {
9522                createCopyFile();
9523            } else {
9524                /*
9525                 * Pre-emptively destroy the container since it's destroyed if
9526                 * copying fails due to it existing anyway.
9527                 */
9528                PackageHelper.destroySdDir(cid);
9529            }
9530
9531            final String newMountPath = imcs.copyPackageToContainer(
9532                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9533                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9534
9535            if (newMountPath != null) {
9536                setMountPath(newMountPath);
9537                return PackageManager.INSTALL_SUCCEEDED;
9538            } else {
9539                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9540            }
9541        }
9542
9543        @Override
9544        String getCodePath() {
9545            return packagePath;
9546        }
9547
9548        @Override
9549        String getResourcePath() {
9550            return resourcePath;
9551        }
9552
9553        @Override
9554        String getLegacyNativeLibraryPath() {
9555            return legacyNativeLibraryDir;
9556        }
9557
9558        int doPreInstall(int status) {
9559            if (status != PackageManager.INSTALL_SUCCEEDED) {
9560                // Destroy container
9561                PackageHelper.destroySdDir(cid);
9562            } else {
9563                boolean mounted = PackageHelper.isContainerMounted(cid);
9564                if (!mounted) {
9565                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9566                            Process.SYSTEM_UID);
9567                    if (newMountPath != null) {
9568                        setMountPath(newMountPath);
9569                    } else {
9570                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9571                    }
9572                }
9573            }
9574            return status;
9575        }
9576
9577        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9578            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9579            String newMountPath = null;
9580            if (PackageHelper.isContainerMounted(cid)) {
9581                // Unmount the container
9582                if (!PackageHelper.unMountSdDir(cid)) {
9583                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9584                    return false;
9585                }
9586            }
9587            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9588                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9589                        " which might be stale. Will try to clean up.");
9590                // Clean up the stale container and proceed to recreate.
9591                if (!PackageHelper.destroySdDir(newCacheId)) {
9592                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9593                    return false;
9594                }
9595                // Successfully cleaned up stale container. Try to rename again.
9596                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9597                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9598                            + " inspite of cleaning it up.");
9599                    return false;
9600                }
9601            }
9602            if (!PackageHelper.isContainerMounted(newCacheId)) {
9603                Slog.w(TAG, "Mounting container " + newCacheId);
9604                newMountPath = PackageHelper.mountSdDir(newCacheId,
9605                        getEncryptKey(), Process.SYSTEM_UID);
9606            } else {
9607                newMountPath = PackageHelper.getSdDir(newCacheId);
9608            }
9609            if (newMountPath == null) {
9610                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9611                return false;
9612            }
9613            Log.i(TAG, "Succesfully renamed " + cid +
9614                    " to " + newCacheId +
9615                    " at new path: " + newMountPath);
9616            cid = newCacheId;
9617
9618            final File beforeCodeFile = new File(packagePath);
9619            setMountPath(newMountPath);
9620            final File afterCodeFile = new File(packagePath);
9621
9622            // Reflect the rename in scanned details
9623            pkg.codePath = afterCodeFile.getAbsolutePath();
9624            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9625                    pkg.baseCodePath);
9626            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9627                    pkg.splitCodePaths);
9628
9629            // Reflect the rename in app info
9630            pkg.applicationInfo.setCodePath(pkg.codePath);
9631            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9632            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9633            pkg.applicationInfo.setResourcePath(pkg.codePath);
9634            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9635            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9636
9637            return true;
9638        }
9639
9640        private void setMountPath(String mountPath) {
9641            final File mountFile = new File(mountPath);
9642
9643            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9644            if (monolithicFile.exists()) {
9645                packagePath = monolithicFile.getAbsolutePath();
9646                if (isFwdLocked()) {
9647                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9648                } else {
9649                    resourcePath = packagePath;
9650                }
9651            } else {
9652                packagePath = mountFile.getAbsolutePath();
9653                resourcePath = packagePath;
9654            }
9655
9656            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9657        }
9658
9659        int doPostInstall(int status, int uid) {
9660            if (status != PackageManager.INSTALL_SUCCEEDED) {
9661                cleanUp();
9662            } else {
9663                final int groupOwner;
9664                final String protectedFile;
9665                if (isFwdLocked()) {
9666                    groupOwner = UserHandle.getSharedAppGid(uid);
9667                    protectedFile = RES_FILE_NAME;
9668                } else {
9669                    groupOwner = -1;
9670                    protectedFile = null;
9671                }
9672
9673                if (uid < Process.FIRST_APPLICATION_UID
9674                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9675                    Slog.e(TAG, "Failed to finalize " + cid);
9676                    PackageHelper.destroySdDir(cid);
9677                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9678                }
9679
9680                boolean mounted = PackageHelper.isContainerMounted(cid);
9681                if (!mounted) {
9682                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9683                }
9684            }
9685            return status;
9686        }
9687
9688        private void cleanUp() {
9689            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9690
9691            // Destroy secure container
9692            PackageHelper.destroySdDir(cid);
9693        }
9694
9695        private List<String> getAllCodePaths() {
9696            final File codeFile = new File(getCodePath());
9697            if (codeFile != null && codeFile.exists()) {
9698                try {
9699                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9700                    return pkg.getAllCodePaths();
9701                } catch (PackageParserException e) {
9702                    // Ignored; we tried our best
9703                }
9704            }
9705            return Collections.EMPTY_LIST;
9706        }
9707
9708        void cleanUpResourcesLI() {
9709            // Enumerate all code paths before deleting
9710            cleanUpResourcesLI(getAllCodePaths());
9711        }
9712
9713        private void cleanUpResourcesLI(List<String> allCodePaths) {
9714            cleanUp();
9715            removeDexFiles(allCodePaths, instructionSets);
9716        }
9717
9718
9719
9720        String getPackageName() {
9721            return getAsecPackageName(cid);
9722        }
9723
9724        boolean doPostDeleteLI(boolean delete) {
9725            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9726            final List<String> allCodePaths = getAllCodePaths();
9727            boolean mounted = PackageHelper.isContainerMounted(cid);
9728            if (mounted) {
9729                // Unmount first
9730                if (PackageHelper.unMountSdDir(cid)) {
9731                    mounted = false;
9732                }
9733            }
9734            if (!mounted && delete) {
9735                cleanUpResourcesLI(allCodePaths);
9736            }
9737            return !mounted;
9738        }
9739
9740        @Override
9741        int doPreCopy() {
9742            if (isFwdLocked()) {
9743                if (!PackageHelper.fixSdPermissions(cid,
9744                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9745                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9746                }
9747            }
9748
9749            return PackageManager.INSTALL_SUCCEEDED;
9750        }
9751
9752        @Override
9753        int doPostCopy(int uid) {
9754            if (isFwdLocked()) {
9755                if (uid < Process.FIRST_APPLICATION_UID
9756                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9757                                RES_FILE_NAME)) {
9758                    Slog.e(TAG, "Failed to finalize " + cid);
9759                    PackageHelper.destroySdDir(cid);
9760                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9761                }
9762            }
9763
9764            return PackageManager.INSTALL_SUCCEEDED;
9765        }
9766    }
9767
9768    static String getAsecPackageName(String packageCid) {
9769        int idx = packageCid.lastIndexOf("-");
9770        if (idx == -1) {
9771            return packageCid;
9772        }
9773        return packageCid.substring(0, idx);
9774    }
9775
9776    // Utility method used to create code paths based on package name and available index.
9777    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9778        String idxStr = "";
9779        int idx = 1;
9780        // Fall back to default value of idx=1 if prefix is not
9781        // part of oldCodePath
9782        if (oldCodePath != null) {
9783            String subStr = oldCodePath;
9784            // Drop the suffix right away
9785            if (suffix != null && subStr.endsWith(suffix)) {
9786                subStr = subStr.substring(0, subStr.length() - suffix.length());
9787            }
9788            // If oldCodePath already contains prefix find out the
9789            // ending index to either increment or decrement.
9790            int sidx = subStr.lastIndexOf(prefix);
9791            if (sidx != -1) {
9792                subStr = subStr.substring(sidx + prefix.length());
9793                if (subStr != null) {
9794                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9795                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9796                    }
9797                    try {
9798                        idx = Integer.parseInt(subStr);
9799                        if (idx <= 1) {
9800                            idx++;
9801                        } else {
9802                            idx--;
9803                        }
9804                    } catch(NumberFormatException e) {
9805                    }
9806                }
9807            }
9808        }
9809        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9810        return prefix + idxStr;
9811    }
9812
9813    private File getNextCodePath(String packageName) {
9814        int suffix = 1;
9815        File result;
9816        do {
9817            result = new File(mAppInstallDir, packageName + "-" + suffix);
9818            suffix++;
9819        } while (result.exists());
9820        return result;
9821    }
9822
9823    // Utility method that returns the relative package path with respect
9824    // to the installation directory. Like say for /data/data/com.test-1.apk
9825    // string com.test-1 is returned.
9826    static String deriveCodePathName(String codePath) {
9827        if (codePath == null) {
9828            return null;
9829        }
9830        final File codeFile = new File(codePath);
9831        final String name = codeFile.getName();
9832        if (codeFile.isDirectory()) {
9833            return name;
9834        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9835            final int lastDot = name.lastIndexOf('.');
9836            return name.substring(0, lastDot);
9837        } else {
9838            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9839            return null;
9840        }
9841    }
9842
9843    class PackageInstalledInfo {
9844        String name;
9845        int uid;
9846        // The set of users that originally had this package installed.
9847        int[] origUsers;
9848        // The set of users that now have this package installed.
9849        int[] newUsers;
9850        PackageParser.Package pkg;
9851        int returnCode;
9852        String returnMsg;
9853        PackageRemovedInfo removedInfo;
9854
9855        public void setError(int code, String msg) {
9856            returnCode = code;
9857            returnMsg = msg;
9858            Slog.w(TAG, msg);
9859        }
9860
9861        public void setError(String msg, PackageParserException e) {
9862            returnCode = e.error;
9863            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9864            Slog.w(TAG, msg, e);
9865        }
9866
9867        public void setError(String msg, PackageManagerException e) {
9868            returnCode = e.error;
9869            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9870            Slog.w(TAG, msg, e);
9871        }
9872
9873        // In some error cases we want to convey more info back to the observer
9874        String origPackage;
9875        String origPermission;
9876    }
9877
9878    /*
9879     * Install a non-existing package.
9880     */
9881    private void installNewPackageLI(PackageParser.Package pkg,
9882            int parseFlags, int scanFlags, UserHandle user,
9883            String installerPackageName, PackageInstalledInfo res) {
9884        // Remember this for later, in case we need to rollback this install
9885        String pkgName = pkg.packageName;
9886
9887        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9888        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9889        synchronized(mPackages) {
9890            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9891                // A package with the same name is already installed, though
9892                // it has been renamed to an older name.  The package we
9893                // are trying to install should be installed as an update to
9894                // the existing one, but that has not been requested, so bail.
9895                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9896                        + " without first uninstalling package running as "
9897                        + mSettings.mRenamedPackages.get(pkgName));
9898                return;
9899            }
9900            if (mPackages.containsKey(pkgName)) {
9901                // Don't allow installation over an existing package with the same name.
9902                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9903                        + " without first uninstalling.");
9904                return;
9905            }
9906        }
9907
9908        try {
9909            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9910                    System.currentTimeMillis(), user);
9911
9912            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9913            // delete the partially installed application. the data directory will have to be
9914            // restored if it was already existing
9915            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9916                // remove package from internal structures.  Note that we want deletePackageX to
9917                // delete the package data and cache directories that it created in
9918                // scanPackageLocked, unless those directories existed before we even tried to
9919                // install.
9920                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9921                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9922                                res.removedInfo, true);
9923            }
9924
9925        } catch (PackageManagerException e) {
9926            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9927        }
9928    }
9929
9930    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9931        // Upgrade keysets are being used.  Determine if new package has a superset of the
9932        // required keys.
9933        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9934        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9935        for (int i = 0; i < upgradeKeySets.length; i++) {
9936            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9937            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9938                return true;
9939            }
9940        }
9941        return false;
9942    }
9943
9944    private void replacePackageLI(PackageParser.Package pkg,
9945            int parseFlags, int scanFlags, UserHandle user,
9946            String installerPackageName, PackageInstalledInfo res) {
9947        PackageParser.Package oldPackage;
9948        String pkgName = pkg.packageName;
9949        int[] allUsers;
9950        boolean[] perUserInstalled;
9951
9952        // First find the old package info and check signatures
9953        synchronized(mPackages) {
9954            oldPackage = mPackages.get(pkgName);
9955            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9956            PackageSetting ps = mSettings.mPackages.get(pkgName);
9957            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9958                // default to original signature matching
9959                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9960                    != PackageManager.SIGNATURE_MATCH) {
9961                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9962                            "New package has a different signature: " + pkgName);
9963                    return;
9964                }
9965            } else {
9966                if(!checkUpgradeKeySetLP(ps, pkg)) {
9967                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9968                            "New package not signed by keys specified by upgrade-keysets: "
9969                            + pkgName);
9970                    return;
9971                }
9972            }
9973
9974            // In case of rollback, remember per-user/profile install state
9975            allUsers = sUserManager.getUserIds();
9976            perUserInstalled = new boolean[allUsers.length];
9977            for (int i = 0; i < allUsers.length; i++) {
9978                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9979            }
9980        }
9981
9982        boolean sysPkg = (isSystemApp(oldPackage));
9983        if (sysPkg) {
9984            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9985                    user, allUsers, perUserInstalled, installerPackageName, res);
9986        } else {
9987            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9988                    user, allUsers, perUserInstalled, installerPackageName, res);
9989        }
9990    }
9991
9992    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9993            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9994            int[] allUsers, boolean[] perUserInstalled,
9995            String installerPackageName, PackageInstalledInfo res) {
9996        String pkgName = deletedPackage.packageName;
9997        boolean deletedPkg = true;
9998        boolean updatedSettings = false;
9999
10000        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10001                + deletedPackage);
10002        long origUpdateTime;
10003        if (pkg.mExtras != null) {
10004            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10005        } else {
10006            origUpdateTime = 0;
10007        }
10008
10009        // First delete the existing package while retaining the data directory
10010        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10011                res.removedInfo, true)) {
10012            // If the existing package wasn't successfully deleted
10013            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10014            deletedPkg = false;
10015        } else {
10016            // Successfully deleted the old package; proceed with replace.
10017
10018            // If deleted package lived in a container, give users a chance to
10019            // relinquish resources before killing.
10020            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
10021                if (DEBUG_INSTALL) {
10022                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10023                }
10024                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10025                final ArrayList<String> pkgList = new ArrayList<String>(1);
10026                pkgList.add(deletedPackage.applicationInfo.packageName);
10027                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10028            }
10029
10030            deleteCodeCacheDirsLI(pkgName);
10031            try {
10032                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10033                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10034                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10035                updatedSettings = true;
10036            } catch (PackageManagerException e) {
10037                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10038            }
10039        }
10040
10041        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10042            // remove package from internal structures.  Note that we want deletePackageX to
10043            // delete the package data and cache directories that it created in
10044            // scanPackageLocked, unless those directories existed before we even tried to
10045            // install.
10046            if(updatedSettings) {
10047                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10048                deletePackageLI(
10049                        pkgName, null, true, allUsers, perUserInstalled,
10050                        PackageManager.DELETE_KEEP_DATA,
10051                                res.removedInfo, true);
10052            }
10053            // Since we failed to install the new package we need to restore the old
10054            // package that we deleted.
10055            if (deletedPkg) {
10056                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10057                File restoreFile = new File(deletedPackage.codePath);
10058                // Parse old package
10059                boolean oldOnSd = isExternal(deletedPackage);
10060                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10061                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10062                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10063                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10064                try {
10065                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10066                } catch (PackageManagerException e) {
10067                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10068                            + e.getMessage());
10069                    return;
10070                }
10071                // Restore of old package succeeded. Update permissions.
10072                // writer
10073                synchronized (mPackages) {
10074                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10075                            UPDATE_PERMISSIONS_ALL);
10076                    // can downgrade to reader
10077                    mSettings.writeLPr();
10078                }
10079                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10080            }
10081        }
10082    }
10083
10084    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10085            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10086            int[] allUsers, boolean[] perUserInstalled,
10087            String installerPackageName, PackageInstalledInfo res) {
10088        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10089                + ", old=" + deletedPackage);
10090        boolean disabledSystem = false;
10091        boolean updatedSettings = false;
10092        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10093        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
10094                != 0) {
10095            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10096        }
10097        String packageName = deletedPackage.packageName;
10098        if (packageName == null) {
10099            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10100                    "Attempt to delete null packageName.");
10101            return;
10102        }
10103        PackageParser.Package oldPkg;
10104        PackageSetting oldPkgSetting;
10105        // reader
10106        synchronized (mPackages) {
10107            oldPkg = mPackages.get(packageName);
10108            oldPkgSetting = mSettings.mPackages.get(packageName);
10109            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10110                    (oldPkgSetting == null)) {
10111                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10112                        "Couldn't find package:" + packageName + " information");
10113                return;
10114            }
10115        }
10116
10117        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10118
10119        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10120        res.removedInfo.removedPackage = packageName;
10121        // Remove existing system package
10122        removePackageLI(oldPkgSetting, true);
10123        // writer
10124        synchronized (mPackages) {
10125            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10126            if (!disabledSystem && deletedPackage != null) {
10127                // We didn't need to disable the .apk as a current system package,
10128                // which means we are replacing another update that is already
10129                // installed.  We need to make sure to delete the older one's .apk.
10130                res.removedInfo.args = createInstallArgsForExisting(0,
10131                        deletedPackage.applicationInfo.getCodePath(),
10132                        deletedPackage.applicationInfo.getResourcePath(),
10133                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10134                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10135            } else {
10136                res.removedInfo.args = null;
10137            }
10138        }
10139
10140        // Successfully disabled the old package. Now proceed with re-installation
10141        deleteCodeCacheDirsLI(packageName);
10142
10143        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10144        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10145
10146        PackageParser.Package newPackage = null;
10147        try {
10148            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10149            if (newPackage.mExtras != null) {
10150                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10151                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10152                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10153
10154                // is the update attempting to change shared user? that isn't going to work...
10155                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10156                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10157                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10158                            + " to " + newPkgSetting.sharedUser);
10159                    updatedSettings = true;
10160                }
10161            }
10162
10163            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10164                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10165                updatedSettings = true;
10166            }
10167
10168        } catch (PackageManagerException e) {
10169            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10170        }
10171
10172        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10173            // Re installation failed. Restore old information
10174            // Remove new pkg information
10175            if (newPackage != null) {
10176                removeInstalledPackageLI(newPackage, true);
10177            }
10178            // Add back the old system package
10179            try {
10180                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10181            } catch (PackageManagerException e) {
10182                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10183            }
10184            // Restore the old system information in Settings
10185            synchronized (mPackages) {
10186                if (disabledSystem) {
10187                    mSettings.enableSystemPackageLPw(packageName);
10188                }
10189                if (updatedSettings) {
10190                    mSettings.setInstallerPackageName(packageName,
10191                            oldPkgSetting.installerPackageName);
10192                }
10193                mSettings.writeLPr();
10194            }
10195        }
10196    }
10197
10198    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10199            int[] allUsers, boolean[] perUserInstalled,
10200            PackageInstalledInfo res) {
10201        String pkgName = newPackage.packageName;
10202        synchronized (mPackages) {
10203            //write settings. the installStatus will be incomplete at this stage.
10204            //note that the new package setting would have already been
10205            //added to mPackages. It hasn't been persisted yet.
10206            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10207            mSettings.writeLPr();
10208        }
10209
10210        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10211
10212        synchronized (mPackages) {
10213            updatePermissionsLPw(newPackage.packageName, newPackage,
10214                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10215                            ? UPDATE_PERMISSIONS_ALL : 0));
10216            // For system-bundled packages, we assume that installing an upgraded version
10217            // of the package implies that the user actually wants to run that new code,
10218            // so we enable the package.
10219            if (isSystemApp(newPackage)) {
10220                // NB: implicit assumption that system package upgrades apply to all users
10221                if (DEBUG_INSTALL) {
10222                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10223                }
10224                PackageSetting ps = mSettings.mPackages.get(pkgName);
10225                if (ps != null) {
10226                    if (res.origUsers != null) {
10227                        for (int userHandle : res.origUsers) {
10228                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10229                                    userHandle, installerPackageName);
10230                        }
10231                    }
10232                    // Also convey the prior install/uninstall state
10233                    if (allUsers != null && perUserInstalled != null) {
10234                        for (int i = 0; i < allUsers.length; i++) {
10235                            if (DEBUG_INSTALL) {
10236                                Slog.d(TAG, "    user " + allUsers[i]
10237                                        + " => " + perUserInstalled[i]);
10238                            }
10239                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10240                        }
10241                        // these install state changes will be persisted in the
10242                        // upcoming call to mSettings.writeLPr().
10243                    }
10244                }
10245            }
10246            res.name = pkgName;
10247            res.uid = newPackage.applicationInfo.uid;
10248            res.pkg = newPackage;
10249            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10250            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10251            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10252            //to update install status
10253            mSettings.writeLPr();
10254        }
10255    }
10256
10257    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10258        final int installFlags = args.installFlags;
10259        String installerPackageName = args.installerPackageName;
10260        File tmpPackageFile = new File(args.getCodePath());
10261        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10262        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10263        boolean replace = false;
10264        int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10265        // Result object to be returned
10266        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10267
10268        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10269        // Retrieve PackageSettings and parse package
10270        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10271                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10272                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10273        PackageParser pp = new PackageParser();
10274        pp.setSeparateProcesses(mSeparateProcesses);
10275        pp.setDisplayMetrics(mMetrics);
10276
10277        final PackageParser.Package pkg;
10278        try {
10279            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10280        } catch (PackageParserException e) {
10281            res.setError("Failed parse during installPackageLI", e);
10282            return;
10283        }
10284
10285        // Mark that we have an install time CPU ABI override.
10286        pkg.cpuAbiOverride = args.abiOverride;
10287
10288        String pkgName = res.name = pkg.packageName;
10289        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10290            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10291                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10292                return;
10293            }
10294        }
10295
10296        try {
10297            pp.collectCertificates(pkg, parseFlags);
10298            pp.collectManifestDigest(pkg);
10299        } catch (PackageParserException e) {
10300            res.setError("Failed collect during installPackageLI", e);
10301            return;
10302        }
10303
10304        /* If the installer passed in a manifest digest, compare it now. */
10305        if (args.manifestDigest != null) {
10306            if (DEBUG_INSTALL) {
10307                final String parsedManifest = pkg.manifestDigest == null ? "null"
10308                        : pkg.manifestDigest.toString();
10309                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10310                        + parsedManifest);
10311            }
10312
10313            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10314                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10315                return;
10316            }
10317        } else if (DEBUG_INSTALL) {
10318            final String parsedManifest = pkg.manifestDigest == null
10319                    ? "null" : pkg.manifestDigest.toString();
10320            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10321        }
10322
10323        // Get rid of all references to package scan path via parser.
10324        pp = null;
10325        String oldCodePath = null;
10326        boolean systemApp = false;
10327        synchronized (mPackages) {
10328            // Check if installing already existing package
10329            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10330                String oldName = mSettings.mRenamedPackages.get(pkgName);
10331                if (pkg.mOriginalPackages != null
10332                        && pkg.mOriginalPackages.contains(oldName)
10333                        && mPackages.containsKey(oldName)) {
10334                    // This package is derived from an original package,
10335                    // and this device has been updating from that original
10336                    // name.  We must continue using the original name, so
10337                    // rename the new package here.
10338                    pkg.setPackageName(oldName);
10339                    pkgName = pkg.packageName;
10340                    replace = true;
10341                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10342                            + oldName + " pkgName=" + pkgName);
10343                } else if (mPackages.containsKey(pkgName)) {
10344                    // This package, under its official name, already exists
10345                    // on the device; we should replace it.
10346                    replace = true;
10347                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10348                }
10349            }
10350
10351            PackageSetting ps = mSettings.mPackages.get(pkgName);
10352            if (ps != null) {
10353                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10354
10355                // Quick sanity check that we're signed correctly if updating;
10356                // we'll check this again later when scanning, but we want to
10357                // bail early here before tripping over redefined permissions.
10358                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10359                    try {
10360                        verifySignaturesLP(ps, pkg);
10361                    } catch (PackageManagerException e) {
10362                        res.setError(e.error, e.getMessage());
10363                        return;
10364                    }
10365                } else {
10366                    if (!checkUpgradeKeySetLP(ps, pkg)) {
10367                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
10368                                + pkg.packageName + " upgrade keys do not match the "
10369                                + "previously installed version");
10370                        return;
10371                    }
10372                }
10373
10374                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10375                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10376                    systemApp = (ps.pkg.applicationInfo.flags &
10377                            ApplicationInfo.FLAG_SYSTEM) != 0;
10378                }
10379                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10380            }
10381
10382            // Check whether the newly-scanned package wants to define an already-defined perm
10383            int N = pkg.permissions.size();
10384            for (int i = N-1; i >= 0; i--) {
10385                PackageParser.Permission perm = pkg.permissions.get(i);
10386                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10387                if (bp != null) {
10388                    // If the defining package is signed with our cert, it's okay.  This
10389                    // also includes the "updating the same package" case, of course.
10390                    // "updating same package" could also involve key-rotation.
10391                    final boolean sigsOk;
10392                    if (!bp.sourcePackage.equals(pkg.packageName)
10393                            || !(bp.packageSetting instanceof PackageSetting)
10394                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10395                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10396                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10397                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10398                    } else {
10399                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10400                    }
10401                    if (!sigsOk) {
10402                        // If the owning package is the system itself, we log but allow
10403                        // install to proceed; we fail the install on all other permission
10404                        // redefinitions.
10405                        if (!bp.sourcePackage.equals("android")) {
10406                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10407                                    + pkg.packageName + " attempting to redeclare permission "
10408                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10409                            res.origPermission = perm.info.name;
10410                            res.origPackage = bp.sourcePackage;
10411                            return;
10412                        } else {
10413                            Slog.w(TAG, "Package " + pkg.packageName
10414                                    + " attempting to redeclare system permission "
10415                                    + perm.info.name + "; ignoring new declaration");
10416                            pkg.permissions.remove(i);
10417                        }
10418                    }
10419                }
10420            }
10421
10422        }
10423
10424        if (systemApp && onSd) {
10425            // Disable updates to system apps on sdcard
10426            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10427                    "Cannot install updates to system apps on sdcard");
10428            return;
10429        }
10430
10431        // If app directory is not writable, dexopt will be called after the rename
10432        if (!forwardLocked && pkg.applicationInfo.isInternal()) {
10433            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
10434            scanFlags |= SCAN_NO_DEX;
10435            try {
10436                deriveNonSystemPackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
10437                        true /* extract libs */);
10438            } catch (PackageManagerException pme) {
10439                Slog.e(TAG, "Error deriving application ABI", pme);
10440                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
10441                return;
10442            }
10443
10444            // Run dexopt before old package gets removed, to minimize time when app is unavailable
10445            int result = mPackageDexOptimizer
10446                    .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */,
10447                            false /* defer */, false /* inclDependencies */);
10448            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
10449                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
10450                return;
10451            }
10452        }
10453
10454        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10455            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10456            return;
10457        }
10458
10459        if (replace) {
10460            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10461                    installerPackageName, res);
10462        } else {
10463            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10464                    args.user, installerPackageName, res);
10465        }
10466        synchronized (mPackages) {
10467            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10468            if (ps != null) {
10469                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10470            }
10471        }
10472    }
10473
10474    private static boolean isMultiArch(PackageSetting ps) {
10475        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10476    }
10477
10478    private static boolean isMultiArch(ApplicationInfo info) {
10479        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10480    }
10481
10482    private static boolean isExternal(PackageParser.Package pkg) {
10483        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10484    }
10485
10486    private static boolean isExternal(PackageSetting ps) {
10487        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10488    }
10489
10490    private static boolean isExternal(ApplicationInfo info) {
10491        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10492    }
10493
10494    private static boolean isSystemApp(PackageParser.Package pkg) {
10495        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10496    }
10497
10498    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10499        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
10500    }
10501
10502    private static boolean isSystemApp(PackageSetting ps) {
10503        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10504    }
10505
10506    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10507        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10508    }
10509
10510    private int packageFlagsToInstallFlags(PackageSetting ps) {
10511        int installFlags = 0;
10512        if (isExternal(ps)) {
10513            installFlags |= PackageManager.INSTALL_EXTERNAL;
10514        }
10515        if (ps.isForwardLocked()) {
10516            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10517        }
10518        return installFlags;
10519    }
10520
10521    private void deleteTempPackageFiles() {
10522        final FilenameFilter filter = new FilenameFilter() {
10523            public boolean accept(File dir, String name) {
10524                return name.startsWith("vmdl") && name.endsWith(".tmp");
10525            }
10526        };
10527        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10528            file.delete();
10529        }
10530    }
10531
10532    @Override
10533    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10534            int flags) {
10535        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10536                flags);
10537    }
10538
10539    @Override
10540    public void deletePackage(final String packageName,
10541            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10542        mContext.enforceCallingOrSelfPermission(
10543                android.Manifest.permission.DELETE_PACKAGES, null);
10544        final int uid = Binder.getCallingUid();
10545        if (UserHandle.getUserId(uid) != userId) {
10546            mContext.enforceCallingPermission(
10547                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10548                    "deletePackage for user " + userId);
10549        }
10550        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10551            try {
10552                observer.onPackageDeleted(packageName,
10553                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10554            } catch (RemoteException re) {
10555            }
10556            return;
10557        }
10558
10559        boolean uninstallBlocked = false;
10560        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10561            int[] users = sUserManager.getUserIds();
10562            for (int i = 0; i < users.length; ++i) {
10563                if (getBlockUninstallForUser(packageName, users[i])) {
10564                    uninstallBlocked = true;
10565                    break;
10566                }
10567            }
10568        } else {
10569            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10570        }
10571        if (uninstallBlocked) {
10572            try {
10573                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10574                        null);
10575            } catch (RemoteException re) {
10576            }
10577            return;
10578        }
10579
10580        if (DEBUG_REMOVE) {
10581            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10582        }
10583        // Queue up an async operation since the package deletion may take a little while.
10584        mHandler.post(new Runnable() {
10585            public void run() {
10586                mHandler.removeCallbacks(this);
10587                final int returnCode = deletePackageX(packageName, userId, flags);
10588                if (observer != null) {
10589                    try {
10590                        observer.onPackageDeleted(packageName, returnCode, null);
10591                    } catch (RemoteException e) {
10592                        Log.i(TAG, "Observer no longer exists.");
10593                    } //end catch
10594                } //end if
10595            } //end run
10596        });
10597    }
10598
10599    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10600        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10601                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10602        try {
10603            if (dpm != null) {
10604                if (dpm.isDeviceOwner(packageName)) {
10605                    return true;
10606                }
10607                int[] users;
10608                if (userId == UserHandle.USER_ALL) {
10609                    users = sUserManager.getUserIds();
10610                } else {
10611                    users = new int[]{userId};
10612                }
10613                for (int i = 0; i < users.length; ++i) {
10614                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10615                        return true;
10616                    }
10617                }
10618            }
10619        } catch (RemoteException e) {
10620        }
10621        return false;
10622    }
10623
10624    /**
10625     *  This method is an internal method that could be get invoked either
10626     *  to delete an installed package or to clean up a failed installation.
10627     *  After deleting an installed package, a broadcast is sent to notify any
10628     *  listeners that the package has been installed. For cleaning up a failed
10629     *  installation, the broadcast is not necessary since the package's
10630     *  installation wouldn't have sent the initial broadcast either
10631     *  The key steps in deleting a package are
10632     *  deleting the package information in internal structures like mPackages,
10633     *  deleting the packages base directories through installd
10634     *  updating mSettings to reflect current status
10635     *  persisting settings for later use
10636     *  sending a broadcast if necessary
10637     */
10638    private int deletePackageX(String packageName, int userId, int flags) {
10639        final PackageRemovedInfo info = new PackageRemovedInfo();
10640        final boolean res;
10641
10642        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10643                ? UserHandle.ALL : new UserHandle(userId);
10644
10645        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10646            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10647            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10648        }
10649
10650        boolean removedForAllUsers = false;
10651        boolean systemUpdate = false;
10652
10653        // for the uninstall-updates case and restricted profiles, remember the per-
10654        // userhandle installed state
10655        int[] allUsers;
10656        boolean[] perUserInstalled;
10657        synchronized (mPackages) {
10658            PackageSetting ps = mSettings.mPackages.get(packageName);
10659            allUsers = sUserManager.getUserIds();
10660            perUserInstalled = new boolean[allUsers.length];
10661            for (int i = 0; i < allUsers.length; i++) {
10662                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10663            }
10664        }
10665
10666        synchronized (mInstallLock) {
10667            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10668            res = deletePackageLI(packageName, removeForUser,
10669                    true, allUsers, perUserInstalled,
10670                    flags | REMOVE_CHATTY, info, true);
10671            systemUpdate = info.isRemovedPackageSystemUpdate;
10672            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10673                removedForAllUsers = true;
10674            }
10675            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10676                    + " removedForAllUsers=" + removedForAllUsers);
10677        }
10678
10679        if (res) {
10680            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10681
10682            // If the removed package was a system update, the old system package
10683            // was re-enabled; we need to broadcast this information
10684            if (systemUpdate) {
10685                Bundle extras = new Bundle(1);
10686                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10687                        ? info.removedAppId : info.uid);
10688                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10689
10690                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10691                        extras, null, null, null);
10692                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10693                        extras, null, null, null);
10694                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10695                        null, packageName, null, null);
10696            }
10697        }
10698        // Force a gc here.
10699        Runtime.getRuntime().gc();
10700        // Delete the resources here after sending the broadcast to let
10701        // other processes clean up before deleting resources.
10702        if (info.args != null) {
10703            synchronized (mInstallLock) {
10704                info.args.doPostDeleteLI(true);
10705            }
10706        }
10707
10708        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10709    }
10710
10711    static class PackageRemovedInfo {
10712        String removedPackage;
10713        int uid = -1;
10714        int removedAppId = -1;
10715        int[] removedUsers = null;
10716        boolean isRemovedPackageSystemUpdate = false;
10717        // Clean up resources deleted packages.
10718        InstallArgs args = null;
10719
10720        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10721            Bundle extras = new Bundle(1);
10722            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10723            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10724            if (replacing) {
10725                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10726            }
10727            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10728            if (removedPackage != null) {
10729                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10730                        extras, null, null, removedUsers);
10731                if (fullRemove && !replacing) {
10732                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10733                            extras, null, null, removedUsers);
10734                }
10735            }
10736            if (removedAppId >= 0) {
10737                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10738                        removedUsers);
10739            }
10740        }
10741    }
10742
10743    /*
10744     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10745     * flag is not set, the data directory is removed as well.
10746     * make sure this flag is set for partially installed apps. If not its meaningless to
10747     * delete a partially installed application.
10748     */
10749    private void removePackageDataLI(PackageSetting ps,
10750            int[] allUserHandles, boolean[] perUserInstalled,
10751            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10752        String packageName = ps.name;
10753        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10754        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10755        // Retrieve object to delete permissions for shared user later on
10756        final PackageSetting deletedPs;
10757        // reader
10758        synchronized (mPackages) {
10759            deletedPs = mSettings.mPackages.get(packageName);
10760            if (outInfo != null) {
10761                outInfo.removedPackage = packageName;
10762                outInfo.removedUsers = deletedPs != null
10763                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10764                        : null;
10765            }
10766        }
10767        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10768            removeDataDirsLI(packageName);
10769            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10770        }
10771        // writer
10772        synchronized (mPackages) {
10773            if (deletedPs != null) {
10774                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10775                    if (outInfo != null) {
10776                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10777                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10778                    }
10779                    if (deletedPs != null) {
10780                        updatePermissionsLPw(deletedPs.name, null, 0);
10781                        if (deletedPs.sharedUser != null) {
10782                            // remove permissions associated with package
10783                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10784                        }
10785                    }
10786                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10787                }
10788                // make sure to preserve per-user disabled state if this removal was just
10789                // a downgrade of a system app to the factory package
10790                if (allUserHandles != null && perUserInstalled != null) {
10791                    if (DEBUG_REMOVE) {
10792                        Slog.d(TAG, "Propagating install state across downgrade");
10793                    }
10794                    for (int i = 0; i < allUserHandles.length; i++) {
10795                        if (DEBUG_REMOVE) {
10796                            Slog.d(TAG, "    user " + allUserHandles[i]
10797                                    + " => " + perUserInstalled[i]);
10798                        }
10799                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10800                    }
10801                }
10802            }
10803            // can downgrade to reader
10804            if (writeSettings) {
10805                // Save settings now
10806                mSettings.writeLPr();
10807            }
10808        }
10809        if (outInfo != null) {
10810            // A user ID was deleted here. Go through all users and remove it
10811            // from KeyStore.
10812            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10813        }
10814    }
10815
10816    static boolean locationIsPrivileged(File path) {
10817        try {
10818            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10819                    .getCanonicalPath();
10820            return path.getCanonicalPath().startsWith(privilegedAppDir);
10821        } catch (IOException e) {
10822            Slog.e(TAG, "Unable to access code path " + path);
10823        }
10824        return false;
10825    }
10826
10827    /*
10828     * Tries to delete system package.
10829     */
10830    private boolean deleteSystemPackageLI(PackageSetting newPs,
10831            int[] allUserHandles, boolean[] perUserInstalled,
10832            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10833        final boolean applyUserRestrictions
10834                = (allUserHandles != null) && (perUserInstalled != null);
10835        PackageSetting disabledPs = null;
10836        // Confirm if the system package has been updated
10837        // An updated system app can be deleted. This will also have to restore
10838        // the system pkg from system partition
10839        // reader
10840        synchronized (mPackages) {
10841            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10842        }
10843        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10844                + " disabledPs=" + disabledPs);
10845        if (disabledPs == null) {
10846            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10847            return false;
10848        } else if (DEBUG_REMOVE) {
10849            Slog.d(TAG, "Deleting system pkg from data partition");
10850        }
10851        if (DEBUG_REMOVE) {
10852            if (applyUserRestrictions) {
10853                Slog.d(TAG, "Remembering install states:");
10854                for (int i = 0; i < allUserHandles.length; i++) {
10855                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10856                }
10857            }
10858        }
10859        // Delete the updated package
10860        outInfo.isRemovedPackageSystemUpdate = true;
10861        if (disabledPs.versionCode < newPs.versionCode) {
10862            // Delete data for downgrades
10863            flags &= ~PackageManager.DELETE_KEEP_DATA;
10864        } else {
10865            // Preserve data by setting flag
10866            flags |= PackageManager.DELETE_KEEP_DATA;
10867        }
10868        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10869                allUserHandles, perUserInstalled, outInfo, writeSettings);
10870        if (!ret) {
10871            return false;
10872        }
10873        // writer
10874        synchronized (mPackages) {
10875            // Reinstate the old system package
10876            mSettings.enableSystemPackageLPw(newPs.name);
10877            // Remove any native libraries from the upgraded package.
10878            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10879        }
10880        // Install the system package
10881        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10882        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10883        if (locationIsPrivileged(disabledPs.codePath)) {
10884            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10885        }
10886
10887        final PackageParser.Package newPkg;
10888        try {
10889            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10890        } catch (PackageManagerException e) {
10891            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10892            return false;
10893        }
10894
10895        // writer
10896        synchronized (mPackages) {
10897            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10898            updatePermissionsLPw(newPkg.packageName, newPkg,
10899                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10900            if (applyUserRestrictions) {
10901                if (DEBUG_REMOVE) {
10902                    Slog.d(TAG, "Propagating install state across reinstall");
10903                }
10904                for (int i = 0; i < allUserHandles.length; i++) {
10905                    if (DEBUG_REMOVE) {
10906                        Slog.d(TAG, "    user " + allUserHandles[i]
10907                                + " => " + perUserInstalled[i]);
10908                    }
10909                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10910                }
10911                // Regardless of writeSettings we need to ensure that this restriction
10912                // state propagation is persisted
10913                mSettings.writeAllUsersPackageRestrictionsLPr();
10914            }
10915            // can downgrade to reader here
10916            if (writeSettings) {
10917                mSettings.writeLPr();
10918            }
10919        }
10920        return true;
10921    }
10922
10923    private boolean deleteInstalledPackageLI(PackageSetting ps,
10924            boolean deleteCodeAndResources, int flags,
10925            int[] allUserHandles, boolean[] perUserInstalled,
10926            PackageRemovedInfo outInfo, boolean writeSettings) {
10927        if (outInfo != null) {
10928            outInfo.uid = ps.appId;
10929        }
10930
10931        // Delete package data from internal structures and also remove data if flag is set
10932        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10933
10934        // Delete application code and resources
10935        if (deleteCodeAndResources && (outInfo != null)) {
10936            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10937                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10938                    getAppDexInstructionSets(ps));
10939            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10940        }
10941        return true;
10942    }
10943
10944    @Override
10945    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10946            int userId) {
10947        mContext.enforceCallingOrSelfPermission(
10948                android.Manifest.permission.DELETE_PACKAGES, null);
10949        synchronized (mPackages) {
10950            PackageSetting ps = mSettings.mPackages.get(packageName);
10951            if (ps == null) {
10952                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10953                return false;
10954            }
10955            if (!ps.getInstalled(userId)) {
10956                // Can't block uninstall for an app that is not installed or enabled.
10957                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10958                return false;
10959            }
10960            ps.setBlockUninstall(blockUninstall, userId);
10961            mSettings.writePackageRestrictionsLPr(userId);
10962        }
10963        return true;
10964    }
10965
10966    @Override
10967    public boolean getBlockUninstallForUser(String packageName, int userId) {
10968        synchronized (mPackages) {
10969            PackageSetting ps = mSettings.mPackages.get(packageName);
10970            if (ps == null) {
10971                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10972                return false;
10973            }
10974            return ps.getBlockUninstall(userId);
10975        }
10976    }
10977
10978    /*
10979     * This method handles package deletion in general
10980     */
10981    private boolean deletePackageLI(String packageName, UserHandle user,
10982            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10983            int flags, PackageRemovedInfo outInfo,
10984            boolean writeSettings) {
10985        if (packageName == null) {
10986            Slog.w(TAG, "Attempt to delete null packageName.");
10987            return false;
10988        }
10989        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10990        PackageSetting ps;
10991        boolean dataOnly = false;
10992        int removeUser = -1;
10993        int appId = -1;
10994        synchronized (mPackages) {
10995            ps = mSettings.mPackages.get(packageName);
10996            if (ps == null) {
10997                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10998                return false;
10999            }
11000            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11001                    && user.getIdentifier() != UserHandle.USER_ALL) {
11002                // The caller is asking that the package only be deleted for a single
11003                // user.  To do this, we just mark its uninstalled state and delete
11004                // its data.  If this is a system app, we only allow this to happen if
11005                // they have set the special DELETE_SYSTEM_APP which requests different
11006                // semantics than normal for uninstalling system apps.
11007                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11008                ps.setUserState(user.getIdentifier(),
11009                        COMPONENT_ENABLED_STATE_DEFAULT,
11010                        false, //installed
11011                        true,  //stopped
11012                        true,  //notLaunched
11013                        false, //hidden
11014                        null, null, null,
11015                        false // blockUninstall
11016                        );
11017                if (!isSystemApp(ps)) {
11018                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11019                        // Other user still have this package installed, so all
11020                        // we need to do is clear this user's data and save that
11021                        // it is uninstalled.
11022                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11023                        removeUser = user.getIdentifier();
11024                        appId = ps.appId;
11025                        mSettings.writePackageRestrictionsLPr(removeUser);
11026                    } else {
11027                        // We need to set it back to 'installed' so the uninstall
11028                        // broadcasts will be sent correctly.
11029                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11030                        ps.setInstalled(true, user.getIdentifier());
11031                    }
11032                } else {
11033                    // This is a system app, so we assume that the
11034                    // other users 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, "Deleting system app");
11038                    removeUser = user.getIdentifier();
11039                    appId = ps.appId;
11040                    mSettings.writePackageRestrictionsLPr(removeUser);
11041                }
11042            }
11043        }
11044
11045        if (removeUser >= 0) {
11046            // From above, we determined that we are deleting this only
11047            // for a single user.  Continue the work here.
11048            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11049            if (outInfo != null) {
11050                outInfo.removedPackage = packageName;
11051                outInfo.removedAppId = appId;
11052                outInfo.removedUsers = new int[] {removeUser};
11053            }
11054            mInstaller.clearUserData(packageName, removeUser);
11055            removeKeystoreDataIfNeeded(removeUser, appId);
11056            schedulePackageCleaning(packageName, removeUser, false);
11057            return true;
11058        }
11059
11060        if (dataOnly) {
11061            // Delete application data first
11062            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11063            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11064            return true;
11065        }
11066
11067        boolean ret = false;
11068        if (isSystemApp(ps)) {
11069            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11070            // When an updated system application is deleted we delete the existing resources as well and
11071            // fall back to existing code in system partition
11072            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11073                    flags, outInfo, writeSettings);
11074        } else {
11075            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11076            // Kill application pre-emptively especially for apps on sd.
11077            killApplication(packageName, ps.appId, "uninstall pkg");
11078            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11079                    allUserHandles, perUserInstalled,
11080                    outInfo, writeSettings);
11081        }
11082
11083        return ret;
11084    }
11085
11086    private final class ClearStorageConnection implements ServiceConnection {
11087        IMediaContainerService mContainerService;
11088
11089        @Override
11090        public void onServiceConnected(ComponentName name, IBinder service) {
11091            synchronized (this) {
11092                mContainerService = IMediaContainerService.Stub.asInterface(service);
11093                notifyAll();
11094            }
11095        }
11096
11097        @Override
11098        public void onServiceDisconnected(ComponentName name) {
11099        }
11100    }
11101
11102    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11103        final boolean mounted;
11104        if (Environment.isExternalStorageEmulated()) {
11105            mounted = true;
11106        } else {
11107            final String status = Environment.getExternalStorageState();
11108
11109            mounted = status.equals(Environment.MEDIA_MOUNTED)
11110                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11111        }
11112
11113        if (!mounted) {
11114            return;
11115        }
11116
11117        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11118        int[] users;
11119        if (userId == UserHandle.USER_ALL) {
11120            users = sUserManager.getUserIds();
11121        } else {
11122            users = new int[] { userId };
11123        }
11124        final ClearStorageConnection conn = new ClearStorageConnection();
11125        if (mContext.bindServiceAsUser(
11126                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11127            try {
11128                for (int curUser : users) {
11129                    long timeout = SystemClock.uptimeMillis() + 5000;
11130                    synchronized (conn) {
11131                        long now = SystemClock.uptimeMillis();
11132                        while (conn.mContainerService == null && now < timeout) {
11133                            try {
11134                                conn.wait(timeout - now);
11135                            } catch (InterruptedException e) {
11136                            }
11137                        }
11138                    }
11139                    if (conn.mContainerService == null) {
11140                        return;
11141                    }
11142
11143                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11144                    clearDirectory(conn.mContainerService,
11145                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11146                    if (allData) {
11147                        clearDirectory(conn.mContainerService,
11148                                userEnv.buildExternalStorageAppDataDirs(packageName));
11149                        clearDirectory(conn.mContainerService,
11150                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11151                    }
11152                }
11153            } finally {
11154                mContext.unbindService(conn);
11155            }
11156        }
11157    }
11158
11159    @Override
11160    public void clearApplicationUserData(final String packageName,
11161            final IPackageDataObserver observer, final int userId) {
11162        mContext.enforceCallingOrSelfPermission(
11163                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11164        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11165        // Queue up an async operation since the package deletion may take a little while.
11166        mHandler.post(new Runnable() {
11167            public void run() {
11168                mHandler.removeCallbacks(this);
11169                final boolean succeeded;
11170                synchronized (mInstallLock) {
11171                    succeeded = clearApplicationUserDataLI(packageName, userId);
11172                }
11173                clearExternalStorageDataSync(packageName, userId, true);
11174                if (succeeded) {
11175                    // invoke DeviceStorageMonitor's update method to clear any notifications
11176                    DeviceStorageMonitorInternal
11177                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11178                    if (dsm != null) {
11179                        dsm.checkMemory();
11180                    }
11181                }
11182                if(observer != null) {
11183                    try {
11184                        observer.onRemoveCompleted(packageName, succeeded);
11185                    } catch (RemoteException e) {
11186                        Log.i(TAG, "Observer no longer exists.");
11187                    }
11188                } //end if observer
11189            } //end run
11190        });
11191    }
11192
11193    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11194        if (packageName == null) {
11195            Slog.w(TAG, "Attempt to delete null packageName.");
11196            return false;
11197        }
11198
11199        // Try finding details about the requested package
11200        PackageParser.Package pkg;
11201        synchronized (mPackages) {
11202            pkg = mPackages.get(packageName);
11203            if (pkg == null) {
11204                final PackageSetting ps = mSettings.mPackages.get(packageName);
11205                if (ps != null) {
11206                    pkg = ps.pkg;
11207                }
11208            }
11209        }
11210
11211        if (pkg == null) {
11212            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11213        }
11214
11215        // Always delete data directories for package, even if we found no other
11216        // record of app. This helps users recover from UID mismatches without
11217        // resorting to a full data wipe.
11218        int retCode = mInstaller.clearUserData(packageName, userId);
11219        if (retCode < 0) {
11220            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11221            return false;
11222        }
11223
11224        if (pkg == null) {
11225            return false;
11226        }
11227
11228        if (pkg != null && pkg.applicationInfo != null) {
11229            final int appId = pkg.applicationInfo.uid;
11230            removeKeystoreDataIfNeeded(userId, appId);
11231        }
11232
11233        // Create a native library symlink only if we have native libraries
11234        // and if the native libraries are 32 bit libraries. We do not provide
11235        // this symlink for 64 bit libraries.
11236        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11237                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11238            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11239            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11240                Slog.w(TAG, "Failed linking native library dir");
11241                return false;
11242            }
11243        }
11244
11245        return true;
11246    }
11247
11248    /**
11249     * Remove entries from the keystore daemon. Will only remove it if the
11250     * {@code appId} is valid.
11251     */
11252    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11253        if (appId < 0) {
11254            return;
11255        }
11256
11257        final KeyStore keyStore = KeyStore.getInstance();
11258        if (keyStore != null) {
11259            if (userId == UserHandle.USER_ALL) {
11260                for (final int individual : sUserManager.getUserIds()) {
11261                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11262                }
11263            } else {
11264                keyStore.clearUid(UserHandle.getUid(userId, appId));
11265            }
11266        } else {
11267            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11268        }
11269    }
11270
11271    @Override
11272    public void deleteApplicationCacheFiles(final String packageName,
11273            final IPackageDataObserver observer) {
11274        mContext.enforceCallingOrSelfPermission(
11275                android.Manifest.permission.DELETE_CACHE_FILES, null);
11276        // Queue up an async operation since the package deletion may take a little while.
11277        final int userId = UserHandle.getCallingUserId();
11278        mHandler.post(new Runnable() {
11279            public void run() {
11280                mHandler.removeCallbacks(this);
11281                final boolean succeded;
11282                synchronized (mInstallLock) {
11283                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11284                }
11285                clearExternalStorageDataSync(packageName, userId, false);
11286                if(observer != null) {
11287                    try {
11288                        observer.onRemoveCompleted(packageName, succeded);
11289                    } catch (RemoteException e) {
11290                        Log.i(TAG, "Observer no longer exists.");
11291                    }
11292                } //end if observer
11293            } //end run
11294        });
11295    }
11296
11297    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11298        if (packageName == null) {
11299            Slog.w(TAG, "Attempt to delete null packageName.");
11300            return false;
11301        }
11302        PackageParser.Package p;
11303        synchronized (mPackages) {
11304            p = mPackages.get(packageName);
11305        }
11306        if (p == null) {
11307            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11308            return false;
11309        }
11310        final ApplicationInfo applicationInfo = p.applicationInfo;
11311        if (applicationInfo == null) {
11312            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11313            return false;
11314        }
11315        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11316        if (retCode < 0) {
11317            Slog.w(TAG, "Couldn't remove cache files for package: "
11318                       + packageName + " u" + userId);
11319            return false;
11320        }
11321        return true;
11322    }
11323
11324    @Override
11325    public void getPackageSizeInfo(final String packageName, int userHandle,
11326            final IPackageStatsObserver observer) {
11327        mContext.enforceCallingOrSelfPermission(
11328                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11329        if (packageName == null) {
11330            throw new IllegalArgumentException("Attempt to get size of null packageName");
11331        }
11332
11333        PackageStats stats = new PackageStats(packageName, userHandle);
11334
11335        /*
11336         * Queue up an async operation since the package measurement may take a
11337         * little while.
11338         */
11339        Message msg = mHandler.obtainMessage(INIT_COPY);
11340        msg.obj = new MeasureParams(stats, observer);
11341        mHandler.sendMessage(msg);
11342    }
11343
11344    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11345            PackageStats pStats) {
11346        if (packageName == null) {
11347            Slog.w(TAG, "Attempt to get size of null packageName.");
11348            return false;
11349        }
11350        PackageParser.Package p;
11351        boolean dataOnly = false;
11352        String libDirRoot = null;
11353        String asecPath = null;
11354        PackageSetting ps = null;
11355        synchronized (mPackages) {
11356            p = mPackages.get(packageName);
11357            ps = mSettings.mPackages.get(packageName);
11358            if(p == null) {
11359                dataOnly = true;
11360                if((ps == null) || (ps.pkg == null)) {
11361                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11362                    return false;
11363                }
11364                p = ps.pkg;
11365            }
11366            if (ps != null) {
11367                libDirRoot = ps.legacyNativeLibraryPathString;
11368            }
11369            if (p != null && (isExternal(p) || p.isForwardLocked())) {
11370                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11371                if (secureContainerId != null) {
11372                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11373                }
11374            }
11375        }
11376        String publicSrcDir = null;
11377        if(!dataOnly) {
11378            final ApplicationInfo applicationInfo = p.applicationInfo;
11379            if (applicationInfo == null) {
11380                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11381                return false;
11382            }
11383            if (p.isForwardLocked()) {
11384                publicSrcDir = applicationInfo.getBaseResourcePath();
11385            }
11386        }
11387        // TODO: extend to measure size of split APKs
11388        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11389        // not just the first level.
11390        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11391        // just the primary.
11392        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11393        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11394                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11395        if (res < 0) {
11396            return false;
11397        }
11398
11399        // Fix-up for forward-locked applications in ASEC containers.
11400        if (!isExternal(p)) {
11401            pStats.codeSize += pStats.externalCodeSize;
11402            pStats.externalCodeSize = 0L;
11403        }
11404
11405        return true;
11406    }
11407
11408
11409    @Override
11410    public void addPackageToPreferred(String packageName) {
11411        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11412    }
11413
11414    @Override
11415    public void removePackageFromPreferred(String packageName) {
11416        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11417    }
11418
11419    @Override
11420    public List<PackageInfo> getPreferredPackages(int flags) {
11421        return new ArrayList<PackageInfo>();
11422    }
11423
11424    private int getUidTargetSdkVersionLockedLPr(int uid) {
11425        Object obj = mSettings.getUserIdLPr(uid);
11426        if (obj instanceof SharedUserSetting) {
11427            final SharedUserSetting sus = (SharedUserSetting) obj;
11428            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11429            final Iterator<PackageSetting> it = sus.packages.iterator();
11430            while (it.hasNext()) {
11431                final PackageSetting ps = it.next();
11432                if (ps.pkg != null) {
11433                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11434                    if (v < vers) vers = v;
11435                }
11436            }
11437            return vers;
11438        } else if (obj instanceof PackageSetting) {
11439            final PackageSetting ps = (PackageSetting) obj;
11440            if (ps.pkg != null) {
11441                return ps.pkg.applicationInfo.targetSdkVersion;
11442            }
11443        }
11444        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11445    }
11446
11447    @Override
11448    public void addPreferredActivity(IntentFilter filter, int match,
11449            ComponentName[] set, ComponentName activity, int userId) {
11450        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11451                "Adding preferred");
11452    }
11453
11454    private void addPreferredActivityInternal(IntentFilter filter, int match,
11455            ComponentName[] set, ComponentName activity, boolean always, int userId,
11456            String opname) {
11457        // writer
11458        int callingUid = Binder.getCallingUid();
11459        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11460        if (filter.countActions() == 0) {
11461            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11462            return;
11463        }
11464        synchronized (mPackages) {
11465            if (mContext.checkCallingOrSelfPermission(
11466                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11467                    != PackageManager.PERMISSION_GRANTED) {
11468                if (getUidTargetSdkVersionLockedLPr(callingUid)
11469                        < Build.VERSION_CODES.FROYO) {
11470                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11471                            + callingUid);
11472                    return;
11473                }
11474                mContext.enforceCallingOrSelfPermission(
11475                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11476            }
11477
11478            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11479            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11480                    + userId + ":");
11481            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11482            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11483            scheduleWritePackageRestrictionsLocked(userId);
11484        }
11485    }
11486
11487    @Override
11488    public void replacePreferredActivity(IntentFilter filter, int match,
11489            ComponentName[] set, ComponentName activity, int userId) {
11490        if (filter.countActions() != 1) {
11491            throw new IllegalArgumentException(
11492                    "replacePreferredActivity expects filter to have only 1 action.");
11493        }
11494        if (filter.countDataAuthorities() != 0
11495                || filter.countDataPaths() != 0
11496                || filter.countDataSchemes() > 1
11497                || filter.countDataTypes() != 0) {
11498            throw new IllegalArgumentException(
11499                    "replacePreferredActivity expects filter to have no data authorities, " +
11500                    "paths, or types; and at most one scheme.");
11501        }
11502
11503        final int callingUid = Binder.getCallingUid();
11504        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11505        synchronized (mPackages) {
11506            if (mContext.checkCallingOrSelfPermission(
11507                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11508                    != PackageManager.PERMISSION_GRANTED) {
11509                if (getUidTargetSdkVersionLockedLPr(callingUid)
11510                        < Build.VERSION_CODES.FROYO) {
11511                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11512                            + Binder.getCallingUid());
11513                    return;
11514                }
11515                mContext.enforceCallingOrSelfPermission(
11516                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11517            }
11518
11519            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11520            if (pir != null) {
11521                // Get all of the existing entries that exactly match this filter.
11522                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11523                if (existing != null && existing.size() == 1) {
11524                    PreferredActivity cur = existing.get(0);
11525                    if (DEBUG_PREFERRED) {
11526                        Slog.i(TAG, "Checking replace of preferred:");
11527                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11528                        if (!cur.mPref.mAlways) {
11529                            Slog.i(TAG, "  -- CUR; not mAlways!");
11530                        } else {
11531                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11532                            Slog.i(TAG, "  -- CUR: mSet="
11533                                    + Arrays.toString(cur.mPref.mSetComponents));
11534                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11535                            Slog.i(TAG, "  -- NEW: mMatch="
11536                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11537                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11538                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11539                        }
11540                    }
11541                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11542                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11543                            && cur.mPref.sameSet(set)) {
11544                        // Setting the preferred activity to what it happens to be already
11545                        if (DEBUG_PREFERRED) {
11546                            Slog.i(TAG, "Replacing with same preferred activity "
11547                                    + cur.mPref.mShortComponent + " for user "
11548                                    + userId + ":");
11549                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11550                        }
11551                        return;
11552                    }
11553                }
11554
11555                if (existing != null) {
11556                    if (DEBUG_PREFERRED) {
11557                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11558                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11559                    }
11560                    for (int i = 0; i < existing.size(); i++) {
11561                        PreferredActivity pa = existing.get(i);
11562                        if (DEBUG_PREFERRED) {
11563                            Slog.i(TAG, "Removing existing preferred activity "
11564                                    + pa.mPref.mComponent + ":");
11565                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11566                        }
11567                        pir.removeFilter(pa);
11568                    }
11569                }
11570            }
11571            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11572                    "Replacing preferred");
11573        }
11574    }
11575
11576    @Override
11577    public void clearPackagePreferredActivities(String packageName) {
11578        final int uid = Binder.getCallingUid();
11579        // writer
11580        synchronized (mPackages) {
11581            PackageParser.Package pkg = mPackages.get(packageName);
11582            if (pkg == null || pkg.applicationInfo.uid != uid) {
11583                if (mContext.checkCallingOrSelfPermission(
11584                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11585                        != PackageManager.PERMISSION_GRANTED) {
11586                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11587                            < Build.VERSION_CODES.FROYO) {
11588                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11589                                + Binder.getCallingUid());
11590                        return;
11591                    }
11592                    mContext.enforceCallingOrSelfPermission(
11593                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11594                }
11595            }
11596
11597            int user = UserHandle.getCallingUserId();
11598            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11599                scheduleWritePackageRestrictionsLocked(user);
11600            }
11601        }
11602    }
11603
11604    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11605    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11606        ArrayList<PreferredActivity> removed = null;
11607        boolean changed = false;
11608        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11609            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11610            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11611            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11612                continue;
11613            }
11614            Iterator<PreferredActivity> it = pir.filterIterator();
11615            while (it.hasNext()) {
11616                PreferredActivity pa = it.next();
11617                // Mark entry for removal only if it matches the package name
11618                // and the entry is of type "always".
11619                if (packageName == null ||
11620                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11621                                && pa.mPref.mAlways)) {
11622                    if (removed == null) {
11623                        removed = new ArrayList<PreferredActivity>();
11624                    }
11625                    removed.add(pa);
11626                }
11627            }
11628            if (removed != null) {
11629                for (int j=0; j<removed.size(); j++) {
11630                    PreferredActivity pa = removed.get(j);
11631                    pir.removeFilter(pa);
11632                }
11633                changed = true;
11634            }
11635        }
11636        return changed;
11637    }
11638
11639    @Override
11640    public void resetPreferredActivities(int userId) {
11641        /* TODO: Actually use userId. Why is it being passed in? */
11642        mContext.enforceCallingOrSelfPermission(
11643                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11644        // writer
11645        synchronized (mPackages) {
11646            int user = UserHandle.getCallingUserId();
11647            clearPackagePreferredActivitiesLPw(null, user);
11648            mSettings.readDefaultPreferredAppsLPw(this, user);
11649            scheduleWritePackageRestrictionsLocked(user);
11650        }
11651    }
11652
11653    @Override
11654    public int getPreferredActivities(List<IntentFilter> outFilters,
11655            List<ComponentName> outActivities, String packageName) {
11656
11657        int num = 0;
11658        final int userId = UserHandle.getCallingUserId();
11659        // reader
11660        synchronized (mPackages) {
11661            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11662            if (pir != null) {
11663                final Iterator<PreferredActivity> it = pir.filterIterator();
11664                while (it.hasNext()) {
11665                    final PreferredActivity pa = it.next();
11666                    if (packageName == null
11667                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11668                                    && pa.mPref.mAlways)) {
11669                        if (outFilters != null) {
11670                            outFilters.add(new IntentFilter(pa));
11671                        }
11672                        if (outActivities != null) {
11673                            outActivities.add(pa.mPref.mComponent);
11674                        }
11675                    }
11676                }
11677            }
11678        }
11679
11680        return num;
11681    }
11682
11683    @Override
11684    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11685            int userId) {
11686        int callingUid = Binder.getCallingUid();
11687        if (callingUid != Process.SYSTEM_UID) {
11688            throw new SecurityException(
11689                    "addPersistentPreferredActivity can only be run by the system");
11690        }
11691        if (filter.countActions() == 0) {
11692            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11693            return;
11694        }
11695        synchronized (mPackages) {
11696            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11697                    " :");
11698            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11699            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11700                    new PersistentPreferredActivity(filter, activity));
11701            scheduleWritePackageRestrictionsLocked(userId);
11702        }
11703    }
11704
11705    @Override
11706    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11707        int callingUid = Binder.getCallingUid();
11708        if (callingUid != Process.SYSTEM_UID) {
11709            throw new SecurityException(
11710                    "clearPackagePersistentPreferredActivities can only be run by the system");
11711        }
11712        ArrayList<PersistentPreferredActivity> removed = null;
11713        boolean changed = false;
11714        synchronized (mPackages) {
11715            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11716                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11717                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11718                        .valueAt(i);
11719                if (userId != thisUserId) {
11720                    continue;
11721                }
11722                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11723                while (it.hasNext()) {
11724                    PersistentPreferredActivity ppa = it.next();
11725                    // Mark entry for removal only if it matches the package name.
11726                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11727                        if (removed == null) {
11728                            removed = new ArrayList<PersistentPreferredActivity>();
11729                        }
11730                        removed.add(ppa);
11731                    }
11732                }
11733                if (removed != null) {
11734                    for (int j=0; j<removed.size(); j++) {
11735                        PersistentPreferredActivity ppa = removed.get(j);
11736                        ppir.removeFilter(ppa);
11737                    }
11738                    changed = true;
11739                }
11740            }
11741
11742            if (changed) {
11743                scheduleWritePackageRestrictionsLocked(userId);
11744            }
11745        }
11746    }
11747
11748    @Override
11749    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11750            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11751        mContext.enforceCallingOrSelfPermission(
11752                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11753        int callingUid = Binder.getCallingUid();
11754        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11755        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11756        if (intentFilter.countActions() == 0) {
11757            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11758            return;
11759        }
11760        synchronized (mPackages) {
11761            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
11762                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11763            CrossProfileIntentResolver resolver =
11764                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11765            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
11766            // We have all those whose filter is equal. Now checking if the rest is equal as well.
11767            if (existing != null) {
11768                int size = existing.size();
11769                for (int i = 0; i < size; i++) {
11770                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
11771                        return;
11772                    }
11773                }
11774            }
11775            resolver.addFilter(newFilter);
11776            scheduleWritePackageRestrictionsLocked(sourceUserId);
11777        }
11778    }
11779
11780    @Override
11781    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11782            int ownerUserId) {
11783        mContext.enforceCallingOrSelfPermission(
11784                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11785        int callingUid = Binder.getCallingUid();
11786        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11787        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11788        int callingUserId = UserHandle.getUserId(callingUid);
11789        synchronized (mPackages) {
11790            CrossProfileIntentResolver resolver =
11791                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11792            ArraySet<CrossProfileIntentFilter> set =
11793                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
11794            for (CrossProfileIntentFilter filter : set) {
11795                if (filter.getOwnerPackage().equals(ownerPackage)
11796                        && filter.getOwnerUserId() == callingUserId) {
11797                    resolver.removeFilter(filter);
11798                }
11799            }
11800            scheduleWritePackageRestrictionsLocked(sourceUserId);
11801        }
11802    }
11803
11804    // Enforcing that callingUid is owning pkg on userId
11805    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11806        // The system owns everything.
11807        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11808            return;
11809        }
11810        int callingUserId = UserHandle.getUserId(callingUid);
11811        if (callingUserId != userId) {
11812            throw new SecurityException("calling uid " + callingUid
11813                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11814                    + callingUserId);
11815        }
11816        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11817        if (pi == null) {
11818            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11819                    + callingUserId);
11820        }
11821        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11822            throw new SecurityException("Calling uid " + callingUid
11823                    + " does not own package " + pkg);
11824        }
11825    }
11826
11827    @Override
11828    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11829        Intent intent = new Intent(Intent.ACTION_MAIN);
11830        intent.addCategory(Intent.CATEGORY_HOME);
11831
11832        final int callingUserId = UserHandle.getCallingUserId();
11833        List<ResolveInfo> list = queryIntentActivities(intent, null,
11834                PackageManager.GET_META_DATA, callingUserId);
11835        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11836                true, false, false, callingUserId);
11837
11838        allHomeCandidates.clear();
11839        if (list != null) {
11840            for (ResolveInfo ri : list) {
11841                allHomeCandidates.add(ri);
11842            }
11843        }
11844        return (preferred == null || preferred.activityInfo == null)
11845                ? null
11846                : new ComponentName(preferred.activityInfo.packageName,
11847                        preferred.activityInfo.name);
11848    }
11849
11850    @Override
11851    public void setApplicationEnabledSetting(String appPackageName,
11852            int newState, int flags, int userId, String callingPackage) {
11853        if (!sUserManager.exists(userId)) return;
11854        if (callingPackage == null) {
11855            callingPackage = Integer.toString(Binder.getCallingUid());
11856        }
11857        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11858    }
11859
11860    @Override
11861    public void setComponentEnabledSetting(ComponentName componentName,
11862            int newState, int flags, int userId) {
11863        if (!sUserManager.exists(userId)) return;
11864        setEnabledSetting(componentName.getPackageName(),
11865                componentName.getClassName(), newState, flags, userId, null);
11866    }
11867
11868    private void setEnabledSetting(final String packageName, String className, int newState,
11869            final int flags, int userId, String callingPackage) {
11870        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11871              || newState == COMPONENT_ENABLED_STATE_ENABLED
11872              || newState == COMPONENT_ENABLED_STATE_DISABLED
11873              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11874              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11875            throw new IllegalArgumentException("Invalid new component state: "
11876                    + newState);
11877        }
11878        PackageSetting pkgSetting;
11879        final int uid = Binder.getCallingUid();
11880        final int permission = mContext.checkCallingOrSelfPermission(
11881                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11882        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
11883        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11884        boolean sendNow = false;
11885        boolean isApp = (className == null);
11886        String componentName = isApp ? packageName : className;
11887        int packageUid = -1;
11888        ArrayList<String> components;
11889
11890        // writer
11891        synchronized (mPackages) {
11892            pkgSetting = mSettings.mPackages.get(packageName);
11893            if (pkgSetting == null) {
11894                if (className == null) {
11895                    throw new IllegalArgumentException(
11896                            "Unknown package: " + packageName);
11897                }
11898                throw new IllegalArgumentException(
11899                        "Unknown component: " + packageName
11900                        + "/" + className);
11901            }
11902            // Allow root and verify that userId is not being specified by a different user
11903            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11904                throw new SecurityException(
11905                        "Permission Denial: attempt to change component state from pid="
11906                        + Binder.getCallingPid()
11907                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11908            }
11909            if (className == null) {
11910                // We're dealing with an application/package level state change
11911                if (pkgSetting.getEnabled(userId) == newState) {
11912                    // Nothing to do
11913                    return;
11914                }
11915                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11916                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11917                    // Don't care about who enables an app.
11918                    callingPackage = null;
11919                }
11920                pkgSetting.setEnabled(newState, userId, callingPackage);
11921                // pkgSetting.pkg.mSetEnabled = newState;
11922            } else {
11923                // We're dealing with a component level state change
11924                // First, verify that this is a valid class name.
11925                PackageParser.Package pkg = pkgSetting.pkg;
11926                if (pkg == null || !pkg.hasComponentClassName(className)) {
11927                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11928                        throw new IllegalArgumentException("Component class " + className
11929                                + " does not exist in " + packageName);
11930                    } else {
11931                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11932                                + className + " does not exist in " + packageName);
11933                    }
11934                }
11935                switch (newState) {
11936                case COMPONENT_ENABLED_STATE_ENABLED:
11937                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11938                        return;
11939                    }
11940                    break;
11941                case COMPONENT_ENABLED_STATE_DISABLED:
11942                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11943                        return;
11944                    }
11945                    break;
11946                case COMPONENT_ENABLED_STATE_DEFAULT:
11947                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11948                        return;
11949                    }
11950                    break;
11951                default:
11952                    Slog.e(TAG, "Invalid new component state: " + newState);
11953                    return;
11954                }
11955            }
11956            mSettings.writePackageRestrictionsLPr(userId);
11957            components = mPendingBroadcasts.get(userId, packageName);
11958            final boolean newPackage = components == null;
11959            if (newPackage) {
11960                components = new ArrayList<String>();
11961            }
11962            if (!components.contains(componentName)) {
11963                components.add(componentName);
11964            }
11965            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11966                sendNow = true;
11967                // Purge entry from pending broadcast list if another one exists already
11968                // since we are sending one right away.
11969                mPendingBroadcasts.remove(userId, packageName);
11970            } else {
11971                if (newPackage) {
11972                    mPendingBroadcasts.put(userId, packageName, components);
11973                }
11974                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11975                    // Schedule a message
11976                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11977                }
11978            }
11979        }
11980
11981        long callingId = Binder.clearCallingIdentity();
11982        try {
11983            if (sendNow) {
11984                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11985                sendPackageChangedBroadcast(packageName,
11986                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11987            }
11988        } finally {
11989            Binder.restoreCallingIdentity(callingId);
11990        }
11991    }
11992
11993    private void sendPackageChangedBroadcast(String packageName,
11994            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11995        if (DEBUG_INSTALL)
11996            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11997                    + componentNames);
11998        Bundle extras = new Bundle(4);
11999        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12000        String nameList[] = new String[componentNames.size()];
12001        componentNames.toArray(nameList);
12002        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12003        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12004        extras.putInt(Intent.EXTRA_UID, packageUid);
12005        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12006                new int[] {UserHandle.getUserId(packageUid)});
12007    }
12008
12009    @Override
12010    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12011        if (!sUserManager.exists(userId)) return;
12012        final int uid = Binder.getCallingUid();
12013        final int permission = mContext.checkCallingOrSelfPermission(
12014                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12015        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12016        enforceCrossUserPermission(uid, userId, true, true, "stop package");
12017        // writer
12018        synchronized (mPackages) {
12019            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12020                    uid, userId)) {
12021                scheduleWritePackageRestrictionsLocked(userId);
12022            }
12023        }
12024    }
12025
12026    @Override
12027    public String getInstallerPackageName(String packageName) {
12028        // reader
12029        synchronized (mPackages) {
12030            return mSettings.getInstallerPackageNameLPr(packageName);
12031        }
12032    }
12033
12034    @Override
12035    public int getApplicationEnabledSetting(String packageName, int userId) {
12036        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12037        int uid = Binder.getCallingUid();
12038        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
12039        // reader
12040        synchronized (mPackages) {
12041            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12042        }
12043    }
12044
12045    @Override
12046    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12047        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12048        int uid = Binder.getCallingUid();
12049        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
12050        // reader
12051        synchronized (mPackages) {
12052            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12053        }
12054    }
12055
12056    @Override
12057    public void enterSafeMode() {
12058        enforceSystemOrRoot("Only the system can request entering safe mode");
12059
12060        if (!mSystemReady) {
12061            mSafeMode = true;
12062        }
12063    }
12064
12065    @Override
12066    public void systemReady() {
12067        mSystemReady = true;
12068
12069        // Read the compatibilty setting when the system is ready.
12070        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12071                mContext.getContentResolver(),
12072                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12073        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12074        if (DEBUG_SETTINGS) {
12075            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12076        }
12077
12078        synchronized (mPackages) {
12079            // Verify that all of the preferred activity components actually
12080            // exist.  It is possible for applications to be updated and at
12081            // that point remove a previously declared activity component that
12082            // had been set as a preferred activity.  We try to clean this up
12083            // the next time we encounter that preferred activity, but it is
12084            // possible for the user flow to never be able to return to that
12085            // situation so here we do a sanity check to make sure we haven't
12086            // left any junk around.
12087            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12088            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12089                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12090                removed.clear();
12091                for (PreferredActivity pa : pir.filterSet()) {
12092                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12093                        removed.add(pa);
12094                    }
12095                }
12096                if (removed.size() > 0) {
12097                    for (int r=0; r<removed.size(); r++) {
12098                        PreferredActivity pa = removed.get(r);
12099                        Slog.w(TAG, "Removing dangling preferred activity: "
12100                                + pa.mPref.mComponent);
12101                        pir.removeFilter(pa);
12102                    }
12103                    mSettings.writePackageRestrictionsLPr(
12104                            mSettings.mPreferredActivities.keyAt(i));
12105                }
12106            }
12107        }
12108        sUserManager.systemReady();
12109
12110        // Kick off any messages waiting for system ready
12111        if (mPostSystemReadyMessages != null) {
12112            for (Message msg : mPostSystemReadyMessages) {
12113                msg.sendToTarget();
12114            }
12115            mPostSystemReadyMessages = null;
12116        }
12117    }
12118
12119    @Override
12120    public boolean isSafeMode() {
12121        return mSafeMode;
12122    }
12123
12124    @Override
12125    public boolean hasSystemUidErrors() {
12126        return mHasSystemUidErrors;
12127    }
12128
12129    static String arrayToString(int[] array) {
12130        StringBuffer buf = new StringBuffer(128);
12131        buf.append('[');
12132        if (array != null) {
12133            for (int i=0; i<array.length; i++) {
12134                if (i > 0) buf.append(", ");
12135                buf.append(array[i]);
12136            }
12137        }
12138        buf.append(']');
12139        return buf.toString();
12140    }
12141
12142    static class DumpState {
12143        public static final int DUMP_LIBS = 1 << 0;
12144        public static final int DUMP_FEATURES = 1 << 1;
12145        public static final int DUMP_RESOLVERS = 1 << 2;
12146        public static final int DUMP_PERMISSIONS = 1 << 3;
12147        public static final int DUMP_PACKAGES = 1 << 4;
12148        public static final int DUMP_SHARED_USERS = 1 << 5;
12149        public static final int DUMP_MESSAGES = 1 << 6;
12150        public static final int DUMP_PROVIDERS = 1 << 7;
12151        public static final int DUMP_VERIFIERS = 1 << 8;
12152        public static final int DUMP_PREFERRED = 1 << 9;
12153        public static final int DUMP_PREFERRED_XML = 1 << 10;
12154        public static final int DUMP_KEYSETS = 1 << 11;
12155        public static final int DUMP_VERSION = 1 << 12;
12156        public static final int DUMP_INSTALLS = 1 << 13;
12157
12158        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12159
12160        private int mTypes;
12161
12162        private int mOptions;
12163
12164        private boolean mTitlePrinted;
12165
12166        private SharedUserSetting mSharedUser;
12167
12168        public boolean isDumping(int type) {
12169            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12170                return true;
12171            }
12172
12173            return (mTypes & type) != 0;
12174        }
12175
12176        public void setDump(int type) {
12177            mTypes |= type;
12178        }
12179
12180        public boolean isOptionEnabled(int option) {
12181            return (mOptions & option) != 0;
12182        }
12183
12184        public void setOptionEnabled(int option) {
12185            mOptions |= option;
12186        }
12187
12188        public boolean onTitlePrinted() {
12189            final boolean printed = mTitlePrinted;
12190            mTitlePrinted = true;
12191            return printed;
12192        }
12193
12194        public boolean getTitlePrinted() {
12195            return mTitlePrinted;
12196        }
12197
12198        public void setTitlePrinted(boolean enabled) {
12199            mTitlePrinted = enabled;
12200        }
12201
12202        public SharedUserSetting getSharedUser() {
12203            return mSharedUser;
12204        }
12205
12206        public void setSharedUser(SharedUserSetting user) {
12207            mSharedUser = user;
12208        }
12209    }
12210
12211    @Override
12212    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12213        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12214                != PackageManager.PERMISSION_GRANTED) {
12215            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12216                    + Binder.getCallingPid()
12217                    + ", uid=" + Binder.getCallingUid()
12218                    + " without permission "
12219                    + android.Manifest.permission.DUMP);
12220            return;
12221        }
12222
12223        DumpState dumpState = new DumpState();
12224        boolean fullPreferred = false;
12225        boolean checkin = false;
12226
12227        String packageName = null;
12228
12229        int opti = 0;
12230        while (opti < args.length) {
12231            String opt = args[opti];
12232            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12233                break;
12234            }
12235            opti++;
12236
12237            if ("-a".equals(opt)) {
12238                // Right now we only know how to print all.
12239            } else if ("-h".equals(opt)) {
12240                pw.println("Package manager dump options:");
12241                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12242                pw.println("    --checkin: dump for a checkin");
12243                pw.println("    -f: print details of intent filters");
12244                pw.println("    -h: print this help");
12245                pw.println("  cmd may be one of:");
12246                pw.println("    l[ibraries]: list known shared libraries");
12247                pw.println("    f[ibraries]: list device features");
12248                pw.println("    k[eysets]: print known keysets");
12249                pw.println("    r[esolvers]: dump intent resolvers");
12250                pw.println("    perm[issions]: dump permissions");
12251                pw.println("    pref[erred]: print preferred package settings");
12252                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12253                pw.println("    prov[iders]: dump content providers");
12254                pw.println("    p[ackages]: dump installed packages");
12255                pw.println("    s[hared-users]: dump shared user IDs");
12256                pw.println("    m[essages]: print collected runtime messages");
12257                pw.println("    v[erifiers]: print package verifier info");
12258                pw.println("    version: print database version info");
12259                pw.println("    write: write current settings now");
12260                pw.println("    <package.name>: info about given package");
12261                pw.println("    installs: details about install sessions");
12262                return;
12263            } else if ("--checkin".equals(opt)) {
12264                checkin = true;
12265            } else if ("-f".equals(opt)) {
12266                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12267            } else {
12268                pw.println("Unknown argument: " + opt + "; use -h for help");
12269            }
12270        }
12271
12272        // Is the caller requesting to dump a particular piece of data?
12273        if (opti < args.length) {
12274            String cmd = args[opti];
12275            opti++;
12276            // Is this a package name?
12277            if ("android".equals(cmd) || cmd.contains(".")) {
12278                packageName = cmd;
12279                // When dumping a single package, we always dump all of its
12280                // filter information since the amount of data will be reasonable.
12281                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12282            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12283                dumpState.setDump(DumpState.DUMP_LIBS);
12284            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12285                dumpState.setDump(DumpState.DUMP_FEATURES);
12286            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12287                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12288            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12289                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12290            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12291                dumpState.setDump(DumpState.DUMP_PREFERRED);
12292            } else if ("preferred-xml".equals(cmd)) {
12293                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12294                if (opti < args.length && "--full".equals(args[opti])) {
12295                    fullPreferred = true;
12296                    opti++;
12297                }
12298            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12299                dumpState.setDump(DumpState.DUMP_PACKAGES);
12300            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12301                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12302            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12303                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12304            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12305                dumpState.setDump(DumpState.DUMP_MESSAGES);
12306            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12307                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12308            } else if ("version".equals(cmd)) {
12309                dumpState.setDump(DumpState.DUMP_VERSION);
12310            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12311                dumpState.setDump(DumpState.DUMP_KEYSETS);
12312            } else if ("installs".equals(cmd)) {
12313                dumpState.setDump(DumpState.DUMP_INSTALLS);
12314            } else if ("write".equals(cmd)) {
12315                synchronized (mPackages) {
12316                    mSettings.writeLPr();
12317                    pw.println("Settings written.");
12318                    return;
12319                }
12320            }
12321        }
12322
12323        if (checkin) {
12324            pw.println("vers,1");
12325        }
12326
12327        // reader
12328        synchronized (mPackages) {
12329            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12330                if (!checkin) {
12331                    if (dumpState.onTitlePrinted())
12332                        pw.println();
12333                    pw.println("Database versions:");
12334                    pw.print("  SDK Version:");
12335                    pw.print(" internal=");
12336                    pw.print(mSettings.mInternalSdkPlatform);
12337                    pw.print(" external=");
12338                    pw.println(mSettings.mExternalSdkPlatform);
12339                    pw.print("  DB Version:");
12340                    pw.print(" internal=");
12341                    pw.print(mSettings.mInternalDatabaseVersion);
12342                    pw.print(" external=");
12343                    pw.println(mSettings.mExternalDatabaseVersion);
12344                }
12345            }
12346
12347            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12348                if (!checkin) {
12349                    if (dumpState.onTitlePrinted())
12350                        pw.println();
12351                    pw.println("Verifiers:");
12352                    pw.print("  Required: ");
12353                    pw.print(mRequiredVerifierPackage);
12354                    pw.print(" (uid=");
12355                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12356                    pw.println(")");
12357                } else if (mRequiredVerifierPackage != null) {
12358                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12359                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12360                }
12361            }
12362
12363            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12364                boolean printedHeader = false;
12365                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12366                while (it.hasNext()) {
12367                    String name = it.next();
12368                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12369                    if (!checkin) {
12370                        if (!printedHeader) {
12371                            if (dumpState.onTitlePrinted())
12372                                pw.println();
12373                            pw.println("Libraries:");
12374                            printedHeader = true;
12375                        }
12376                        pw.print("  ");
12377                    } else {
12378                        pw.print("lib,");
12379                    }
12380                    pw.print(name);
12381                    if (!checkin) {
12382                        pw.print(" -> ");
12383                    }
12384                    if (ent.path != null) {
12385                        if (!checkin) {
12386                            pw.print("(jar) ");
12387                            pw.print(ent.path);
12388                        } else {
12389                            pw.print(",jar,");
12390                            pw.print(ent.path);
12391                        }
12392                    } else {
12393                        if (!checkin) {
12394                            pw.print("(apk) ");
12395                            pw.print(ent.apk);
12396                        } else {
12397                            pw.print(",apk,");
12398                            pw.print(ent.apk);
12399                        }
12400                    }
12401                    pw.println();
12402                }
12403            }
12404
12405            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12406                if (dumpState.onTitlePrinted())
12407                    pw.println();
12408                if (!checkin) {
12409                    pw.println("Features:");
12410                }
12411                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12412                while (it.hasNext()) {
12413                    String name = it.next();
12414                    if (!checkin) {
12415                        pw.print("  ");
12416                    } else {
12417                        pw.print("feat,");
12418                    }
12419                    pw.println(name);
12420                }
12421            }
12422
12423            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12424                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12425                        : "Activity Resolver Table:", "  ", packageName,
12426                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12427                    dumpState.setTitlePrinted(true);
12428                }
12429                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12430                        : "Receiver Resolver Table:", "  ", packageName,
12431                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12432                    dumpState.setTitlePrinted(true);
12433                }
12434                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12435                        : "Service Resolver Table:", "  ", packageName,
12436                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12437                    dumpState.setTitlePrinted(true);
12438                }
12439                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12440                        : "Provider Resolver Table:", "  ", packageName,
12441                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12442                    dumpState.setTitlePrinted(true);
12443                }
12444            }
12445
12446            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12447                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12448                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12449                    int user = mSettings.mPreferredActivities.keyAt(i);
12450                    if (pir.dump(pw,
12451                            dumpState.getTitlePrinted()
12452                                ? "\nPreferred Activities User " + user + ":"
12453                                : "Preferred Activities User " + user + ":", "  ",
12454                            packageName, true, false)) {
12455                        dumpState.setTitlePrinted(true);
12456                    }
12457                }
12458            }
12459
12460            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12461                pw.flush();
12462                FileOutputStream fout = new FileOutputStream(fd);
12463                BufferedOutputStream str = new BufferedOutputStream(fout);
12464                XmlSerializer serializer = new FastXmlSerializer();
12465                try {
12466                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
12467                    serializer.startDocument(null, true);
12468                    serializer.setFeature(
12469                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12470                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12471                    serializer.endDocument();
12472                    serializer.flush();
12473                } catch (IllegalArgumentException e) {
12474                    pw.println("Failed writing: " + e);
12475                } catch (IllegalStateException e) {
12476                    pw.println("Failed writing: " + e);
12477                } catch (IOException e) {
12478                    pw.println("Failed writing: " + e);
12479                }
12480            }
12481
12482            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12483                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12484                if (packageName == null) {
12485                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12486                        if (iperm == 0) {
12487                            if (dumpState.onTitlePrinted())
12488                                pw.println();
12489                            pw.println("AppOp Permissions:");
12490                        }
12491                        pw.print("  AppOp Permission ");
12492                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12493                        pw.println(":");
12494                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12495                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12496                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12497                        }
12498                    }
12499                }
12500            }
12501
12502            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12503                boolean printedSomething = false;
12504                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12505                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12506                        continue;
12507                    }
12508                    if (!printedSomething) {
12509                        if (dumpState.onTitlePrinted())
12510                            pw.println();
12511                        pw.println("Registered ContentProviders:");
12512                        printedSomething = true;
12513                    }
12514                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12515                    pw.print("    "); pw.println(p.toString());
12516                }
12517                printedSomething = false;
12518                for (Map.Entry<String, PackageParser.Provider> entry :
12519                        mProvidersByAuthority.entrySet()) {
12520                    PackageParser.Provider p = entry.getValue();
12521                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12522                        continue;
12523                    }
12524                    if (!printedSomething) {
12525                        if (dumpState.onTitlePrinted())
12526                            pw.println();
12527                        pw.println("ContentProvider Authorities:");
12528                        printedSomething = true;
12529                    }
12530                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12531                    pw.print("    "); pw.println(p.toString());
12532                    if (p.info != null && p.info.applicationInfo != null) {
12533                        final String appInfo = p.info.applicationInfo.toString();
12534                        pw.print("      applicationInfo="); pw.println(appInfo);
12535                    }
12536                }
12537            }
12538
12539            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12540                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12541            }
12542
12543            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12544                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12545            }
12546
12547            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12548                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
12549            }
12550
12551            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12552                // XXX should handle packageName != null by dumping only install data that
12553                // the given package is involved with.
12554                if (dumpState.onTitlePrinted()) pw.println();
12555                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12556            }
12557
12558            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12559                if (dumpState.onTitlePrinted()) pw.println();
12560                mSettings.dumpReadMessagesLPr(pw, dumpState);
12561
12562                pw.println();
12563                pw.println("Package warning messages:");
12564                BufferedReader in = null;
12565                String line = null;
12566                try {
12567                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12568                    while ((line = in.readLine()) != null) {
12569                        if (line.contains("ignored: updated version")) continue;
12570                        pw.println(line);
12571                    }
12572                } catch (IOException ignored) {
12573                } finally {
12574                    IoUtils.closeQuietly(in);
12575                }
12576            }
12577
12578            if (checkin && dumpState.isDumping(DumpState.DUMP_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.print("msg,");
12586                        pw.println(line);
12587                    }
12588                } catch (IOException ignored) {
12589                } finally {
12590                    IoUtils.closeQuietly(in);
12591                }
12592            }
12593        }
12594    }
12595
12596    // ------- apps on sdcard specific code -------
12597    static final boolean DEBUG_SD_INSTALL = false;
12598
12599    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12600
12601    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12602
12603    private boolean mMediaMounted = false;
12604
12605    static String getEncryptKey() {
12606        try {
12607            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12608                    SD_ENCRYPTION_KEYSTORE_NAME);
12609            if (sdEncKey == null) {
12610                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12611                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12612                if (sdEncKey == null) {
12613                    Slog.e(TAG, "Failed to create encryption keys");
12614                    return null;
12615                }
12616            }
12617            return sdEncKey;
12618        } catch (NoSuchAlgorithmException nsae) {
12619            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12620            return null;
12621        } catch (IOException ioe) {
12622            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12623            return null;
12624        }
12625    }
12626
12627    /*
12628     * Update media status on PackageManager.
12629     */
12630    @Override
12631    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12632        int callingUid = Binder.getCallingUid();
12633        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12634            throw new SecurityException("Media status can only be updated by the system");
12635        }
12636        // reader; this apparently protects mMediaMounted, but should probably
12637        // be a different lock in that case.
12638        synchronized (mPackages) {
12639            Log.i(TAG, "Updating external media status from "
12640                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12641                    + (mediaStatus ? "mounted" : "unmounted"));
12642            if (DEBUG_SD_INSTALL)
12643                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12644                        + ", mMediaMounted=" + mMediaMounted);
12645            if (mediaStatus == mMediaMounted) {
12646                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12647                        : 0, -1);
12648                mHandler.sendMessage(msg);
12649                return;
12650            }
12651            mMediaMounted = mediaStatus;
12652        }
12653        // Queue up an async operation since the package installation may take a
12654        // little while.
12655        mHandler.post(new Runnable() {
12656            public void run() {
12657                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12658            }
12659        });
12660    }
12661
12662    /**
12663     * Called by MountService when the initial ASECs to scan are available.
12664     * Should block until all the ASEC containers are finished being scanned.
12665     */
12666    public void scanAvailableAsecs() {
12667        updateExternalMediaStatusInner(true, false, false);
12668        if (mShouldRestoreconData) {
12669            SELinuxMMAC.setRestoreconDone();
12670            mShouldRestoreconData = false;
12671        }
12672    }
12673
12674    /*
12675     * Collect information of applications on external media, map them against
12676     * existing containers and update information based on current mount status.
12677     * Please note that we always have to report status if reportStatus has been
12678     * set to true especially when unloading packages.
12679     */
12680    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12681            boolean externalStorage) {
12682        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12683        int[] uidArr = EmptyArray.INT;
12684
12685        final String[] list = PackageHelper.getSecureContainerList();
12686        if (ArrayUtils.isEmpty(list)) {
12687            Log.i(TAG, "No secure containers found");
12688        } else {
12689            // Process list of secure containers and categorize them
12690            // as active or stale based on their package internal state.
12691
12692            // reader
12693            synchronized (mPackages) {
12694                for (String cid : list) {
12695                    // Leave stages untouched for now; installer service owns them
12696                    if (PackageInstallerService.isStageName(cid)) continue;
12697
12698                    if (DEBUG_SD_INSTALL)
12699                        Log.i(TAG, "Processing container " + cid);
12700                    String pkgName = getAsecPackageName(cid);
12701                    if (pkgName == null) {
12702                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12703                        continue;
12704                    }
12705                    if (DEBUG_SD_INSTALL)
12706                        Log.i(TAG, "Looking for pkg : " + pkgName);
12707
12708                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12709                    if (ps == null) {
12710                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12711                        continue;
12712                    }
12713
12714                    /*
12715                     * Skip packages that are not external if we're unmounting
12716                     * external storage.
12717                     */
12718                    if (externalStorage && !isMounted && !isExternal(ps)) {
12719                        continue;
12720                    }
12721
12722                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12723                            getAppDexInstructionSets(ps), ps.isForwardLocked());
12724                    // The package status is changed only if the code path
12725                    // matches between settings and the container id.
12726                    if (ps.codePathString != null
12727                            && ps.codePathString.startsWith(args.getCodePath())) {
12728                        if (DEBUG_SD_INSTALL) {
12729                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12730                                    + " at code path: " + ps.codePathString);
12731                        }
12732
12733                        // We do have a valid package installed on sdcard
12734                        processCids.put(args, ps.codePathString);
12735                        final int uid = ps.appId;
12736                        if (uid != -1) {
12737                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12738                        }
12739                    } else {
12740                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12741                                + ps.codePathString);
12742                    }
12743                }
12744            }
12745
12746            Arrays.sort(uidArr);
12747        }
12748
12749        // Process packages with valid entries.
12750        if (isMounted) {
12751            if (DEBUG_SD_INSTALL)
12752                Log.i(TAG, "Loading packages");
12753            loadMediaPackages(processCids, uidArr);
12754            startCleaningPackages();
12755            mInstallerService.onSecureContainersAvailable();
12756        } else {
12757            if (DEBUG_SD_INSTALL)
12758                Log.i(TAG, "Unloading packages");
12759            unloadMediaPackages(processCids, uidArr, reportStatus);
12760        }
12761    }
12762
12763    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12764            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12765        int size = pkgList.size();
12766        if (size > 0) {
12767            // Send broadcasts here
12768            Bundle extras = new Bundle();
12769            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12770                    .toArray(new String[size]));
12771            if (uidArr != null) {
12772                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12773            }
12774            if (replacing) {
12775                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12776            }
12777            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12778                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12779            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12780        }
12781    }
12782
12783   /*
12784     * Look at potentially valid container ids from processCids If package
12785     * information doesn't match the one on record or package scanning fails,
12786     * the cid is added to list of removeCids. We currently don't delete stale
12787     * containers.
12788     */
12789    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12790        ArrayList<String> pkgList = new ArrayList<String>();
12791        Set<AsecInstallArgs> keys = processCids.keySet();
12792
12793        for (AsecInstallArgs args : keys) {
12794            String codePath = processCids.get(args);
12795            if (DEBUG_SD_INSTALL)
12796                Log.i(TAG, "Loading container : " + args.cid);
12797            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12798            try {
12799                // Make sure there are no container errors first.
12800                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12801                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12802                            + " when installing from sdcard");
12803                    continue;
12804                }
12805                // Check code path here.
12806                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12807                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12808                            + " does not match one in settings " + codePath);
12809                    continue;
12810                }
12811                // Parse package
12812                int parseFlags = mDefParseFlags;
12813                if (args.isExternal()) {
12814                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12815                }
12816                if (args.isFwdLocked()) {
12817                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12818                }
12819
12820                synchronized (mInstallLock) {
12821                    PackageParser.Package pkg = null;
12822                    try {
12823                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12824                    } catch (PackageManagerException e) {
12825                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12826                    }
12827                    // Scan the package
12828                    if (pkg != null) {
12829                        /*
12830                         * TODO why is the lock being held? doPostInstall is
12831                         * called in other places without the lock. This needs
12832                         * to be straightened out.
12833                         */
12834                        // writer
12835                        synchronized (mPackages) {
12836                            retCode = PackageManager.INSTALL_SUCCEEDED;
12837                            pkgList.add(pkg.packageName);
12838                            // Post process args
12839                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12840                                    pkg.applicationInfo.uid);
12841                        }
12842                    } else {
12843                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12844                    }
12845                }
12846
12847            } finally {
12848                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12849                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12850                }
12851            }
12852        }
12853        // writer
12854        synchronized (mPackages) {
12855            // If the platform SDK has changed since the last time we booted,
12856            // we need to re-grant app permission to catch any new ones that
12857            // appear. This is really a hack, and means that apps can in some
12858            // cases get permissions that the user didn't initially explicitly
12859            // allow... it would be nice to have some better way to handle
12860            // this situation.
12861            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12862            if (regrantPermissions)
12863                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12864                        + mSdkVersion + "; regranting permissions for external storage");
12865            mSettings.mExternalSdkPlatform = mSdkVersion;
12866
12867            // Make sure group IDs have been assigned, and any permission
12868            // changes in other apps are accounted for
12869            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12870                    | (regrantPermissions
12871                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12872                            : 0));
12873
12874            mSettings.updateExternalDatabaseVersion();
12875
12876            // can downgrade to reader
12877            // Persist settings
12878            mSettings.writeLPr();
12879        }
12880        // Send a broadcast to let everyone know we are done processing
12881        if (pkgList.size() > 0) {
12882            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12883        }
12884    }
12885
12886   /*
12887     * Utility method to unload a list of specified containers
12888     */
12889    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12890        // Just unmount all valid containers.
12891        for (AsecInstallArgs arg : cidArgs) {
12892            synchronized (mInstallLock) {
12893                arg.doPostDeleteLI(false);
12894           }
12895       }
12896   }
12897
12898    /*
12899     * Unload packages mounted on external media. This involves deleting package
12900     * data from internal structures, sending broadcasts about diabled packages,
12901     * gc'ing to free up references, unmounting all secure containers
12902     * corresponding to packages on external media, and posting a
12903     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12904     * that we always have to post this message if status has been requested no
12905     * matter what.
12906     */
12907    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12908            final boolean reportStatus) {
12909        if (DEBUG_SD_INSTALL)
12910            Log.i(TAG, "unloading media packages");
12911        ArrayList<String> pkgList = new ArrayList<String>();
12912        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12913        final Set<AsecInstallArgs> keys = processCids.keySet();
12914        for (AsecInstallArgs args : keys) {
12915            String pkgName = args.getPackageName();
12916            if (DEBUG_SD_INSTALL)
12917                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12918            // Delete package internally
12919            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12920            synchronized (mInstallLock) {
12921                boolean res = deletePackageLI(pkgName, null, false, null, null,
12922                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12923                if (res) {
12924                    pkgList.add(pkgName);
12925                } else {
12926                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12927                    failedList.add(args);
12928                }
12929            }
12930        }
12931
12932        // reader
12933        synchronized (mPackages) {
12934            // We didn't update the settings after removing each package;
12935            // write them now for all packages.
12936            mSettings.writeLPr();
12937        }
12938
12939        // We have to absolutely send UPDATED_MEDIA_STATUS only
12940        // after confirming that all the receivers processed the ordered
12941        // broadcast when packages get disabled, force a gc to clean things up.
12942        // and unload all the containers.
12943        if (pkgList.size() > 0) {
12944            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12945                    new IIntentReceiver.Stub() {
12946                public void performReceive(Intent intent, int resultCode, String data,
12947                        Bundle extras, boolean ordered, boolean sticky,
12948                        int sendingUser) throws RemoteException {
12949                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12950                            reportStatus ? 1 : 0, 1, keys);
12951                    mHandler.sendMessage(msg);
12952                }
12953            });
12954        } else {
12955            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12956                    keys);
12957            mHandler.sendMessage(msg);
12958        }
12959    }
12960
12961    /** Binder call */
12962    @Override
12963    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12964            final int flags) {
12965        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12966        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12967        int returnCode = PackageManager.MOVE_SUCCEEDED;
12968        int currInstallFlags = 0;
12969        int newInstallFlags = 0;
12970
12971        File codeFile = null;
12972        String installerPackageName = null;
12973        String packageAbiOverride = null;
12974
12975        // reader
12976        synchronized (mPackages) {
12977            final PackageParser.Package pkg = mPackages.get(packageName);
12978            final PackageSetting ps = mSettings.mPackages.get(packageName);
12979            if (pkg == null || ps == null) {
12980                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12981            } else {
12982                // Disable moving fwd locked apps and system packages
12983                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12984                    Slog.w(TAG, "Cannot move system application");
12985                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12986                } else if (pkg.mOperationPending) {
12987                    Slog.w(TAG, "Attempt to move package which has pending operations");
12988                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12989                } else {
12990                    // Find install location first
12991                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12992                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12993                        Slog.w(TAG, "Ambigous flags specified for move location.");
12994                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12995                    } else {
12996                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12997                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12998                        currInstallFlags = isExternal(pkg)
12999                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13000
13001                        if (newInstallFlags == currInstallFlags) {
13002                            Slog.w(TAG, "No move required. Trying to move to same location");
13003                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13004                        } else {
13005                            if (pkg.isForwardLocked()) {
13006                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13007                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13008                            }
13009                        }
13010                    }
13011                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13012                        pkg.mOperationPending = true;
13013                    }
13014                }
13015
13016                codeFile = new File(pkg.codePath);
13017                installerPackageName = ps.installerPackageName;
13018                packageAbiOverride = ps.cpuAbiOverrideString;
13019            }
13020        }
13021
13022        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13023            try {
13024                observer.packageMoved(packageName, returnCode);
13025            } catch (RemoteException ignored) {
13026            }
13027            return;
13028        }
13029
13030        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
13031            @Override
13032            public void onUserActionRequired(Intent intent) throws RemoteException {
13033                throw new IllegalStateException();
13034            }
13035
13036            @Override
13037            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
13038                    Bundle extras) throws RemoteException {
13039                Slog.d(TAG, "Install result for move: "
13040                        + PackageManager.installStatusToString(returnCode, msg));
13041
13042                // We usually have a new package now after the install, but if
13043                // we failed we need to clear the pending flag on the original
13044                // package object.
13045                synchronized (mPackages) {
13046                    final PackageParser.Package pkg = mPackages.get(packageName);
13047                    if (pkg != null) {
13048                        pkg.mOperationPending = false;
13049                    }
13050                }
13051
13052                final int status = PackageManager.installStatusToPublicStatus(returnCode);
13053                switch (status) {
13054                    case PackageInstaller.STATUS_SUCCESS:
13055                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
13056                        break;
13057                    case PackageInstaller.STATUS_FAILURE_STORAGE:
13058                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
13059                        break;
13060                    default:
13061                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
13062                        break;
13063                }
13064            }
13065        };
13066
13067        // Treat a move like reinstalling an existing app, which ensures that we
13068        // process everythign uniformly, like unpacking native libraries.
13069        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
13070
13071        final Message msg = mHandler.obtainMessage(INIT_COPY);
13072        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
13073        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
13074                installerPackageName, null, user, packageAbiOverride);
13075        mHandler.sendMessage(msg);
13076    }
13077
13078    @Override
13079    public boolean setInstallLocation(int loc) {
13080        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13081                null);
13082        if (getInstallLocation() == loc) {
13083            return true;
13084        }
13085        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13086                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13087            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13088                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13089            return true;
13090        }
13091        return false;
13092   }
13093
13094    @Override
13095    public int getInstallLocation() {
13096        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13097                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13098                PackageHelper.APP_INSTALL_AUTO);
13099    }
13100
13101    /** Called by UserManagerService */
13102    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13103        mDirtyUsers.remove(userHandle);
13104        mSettings.removeUserLPw(userHandle);
13105        mPendingBroadcasts.remove(userHandle);
13106        if (mInstaller != null) {
13107            // Technically, we shouldn't be doing this with the package lock
13108            // held.  However, this is very rare, and there is already so much
13109            // other disk I/O going on, that we'll let it slide for now.
13110            mInstaller.removeUserDataDirs(userHandle);
13111        }
13112        mUserNeedsBadging.delete(userHandle);
13113        removeUnusedPackagesLILPw(userManager, userHandle);
13114    }
13115
13116    /**
13117     * We're removing userHandle and would like to remove any downloaded packages
13118     * that are no longer in use by any other user.
13119     * @param userHandle the user being removed
13120     */
13121    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13122        final boolean DEBUG_CLEAN_APKS = false;
13123        int [] users = userManager.getUserIdsLPr();
13124        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13125        while (psit.hasNext()) {
13126            PackageSetting ps = psit.next();
13127            if (ps.pkg == null) {
13128                continue;
13129            }
13130            final String packageName = ps.pkg.packageName;
13131            // Skip over if system app
13132            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13133                continue;
13134            }
13135            if (DEBUG_CLEAN_APKS) {
13136                Slog.i(TAG, "Checking package " + packageName);
13137            }
13138            boolean keep = false;
13139            for (int i = 0; i < users.length; i++) {
13140                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13141                    keep = true;
13142                    if (DEBUG_CLEAN_APKS) {
13143                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13144                                + users[i]);
13145                    }
13146                    break;
13147                }
13148            }
13149            if (!keep) {
13150                if (DEBUG_CLEAN_APKS) {
13151                    Slog.i(TAG, "  Removing package " + packageName);
13152                }
13153                mHandler.post(new Runnable() {
13154                    public void run() {
13155                        deletePackageX(packageName, userHandle, 0);
13156                    } //end run
13157                });
13158            }
13159        }
13160    }
13161
13162    /** Called by UserManagerService */
13163    void createNewUserLILPw(int userHandle, File path) {
13164        if (mInstaller != null) {
13165            mInstaller.createUserConfig(userHandle);
13166            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13167        }
13168    }
13169
13170    @Override
13171    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13172        mContext.enforceCallingOrSelfPermission(
13173                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13174                "Only package verification agents can read the verifier device identity");
13175
13176        synchronized (mPackages) {
13177            return mSettings.getVerifierDeviceIdentityLPw();
13178        }
13179    }
13180
13181    @Override
13182    public void setPermissionEnforced(String permission, boolean enforced) {
13183        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13184        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13185            synchronized (mPackages) {
13186                if (mSettings.mReadExternalStorageEnforced == null
13187                        || mSettings.mReadExternalStorageEnforced != enforced) {
13188                    mSettings.mReadExternalStorageEnforced = enforced;
13189                    mSettings.writeLPr();
13190                }
13191            }
13192            // kill any non-foreground processes so we restart them and
13193            // grant/revoke the GID.
13194            final IActivityManager am = ActivityManagerNative.getDefault();
13195            if (am != null) {
13196                final long token = Binder.clearCallingIdentity();
13197                try {
13198                    am.killProcessesBelowForeground("setPermissionEnforcement");
13199                } catch (RemoteException e) {
13200                } finally {
13201                    Binder.restoreCallingIdentity(token);
13202                }
13203            }
13204        } else {
13205            throw new IllegalArgumentException("No selective enforcement for " + permission);
13206        }
13207    }
13208
13209    @Override
13210    @Deprecated
13211    public boolean isPermissionEnforced(String permission) {
13212        return true;
13213    }
13214
13215    @Override
13216    public boolean isStorageLow() {
13217        final long token = Binder.clearCallingIdentity();
13218        try {
13219            final DeviceStorageMonitorInternal
13220                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13221            if (dsm != null) {
13222                return dsm.isMemoryLow();
13223            } else {
13224                return false;
13225            }
13226        } finally {
13227            Binder.restoreCallingIdentity(token);
13228        }
13229    }
13230
13231    @Override
13232    public IPackageInstaller getPackageInstaller() {
13233        return mInstallerService;
13234    }
13235
13236    private boolean userNeedsBadging(int userId) {
13237        int index = mUserNeedsBadging.indexOfKey(userId);
13238        if (index < 0) {
13239            final UserInfo userInfo;
13240            final long token = Binder.clearCallingIdentity();
13241            try {
13242                userInfo = sUserManager.getUserInfo(userId);
13243            } finally {
13244                Binder.restoreCallingIdentity(token);
13245            }
13246            final boolean b;
13247            if (userInfo != null && userInfo.isManagedProfile()) {
13248                b = true;
13249            } else {
13250                b = false;
13251            }
13252            mUserNeedsBadging.put(userId, b);
13253            return b;
13254        }
13255        return mUserNeedsBadging.valueAt(index);
13256    }
13257
13258    @Override
13259    public KeySet getKeySetByAlias(String packageName, String alias) {
13260        if (packageName == null || alias == null) {
13261            return null;
13262        }
13263        synchronized(mPackages) {
13264            final PackageParser.Package pkg = mPackages.get(packageName);
13265            if (pkg == null) {
13266                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13267                throw new IllegalArgumentException("Unknown package: " + packageName);
13268            }
13269            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13270            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13271        }
13272    }
13273
13274    @Override
13275    public KeySet getSigningKeySet(String packageName) {
13276        if (packageName == null) {
13277            return null;
13278        }
13279        synchronized(mPackages) {
13280            final PackageParser.Package pkg = mPackages.get(packageName);
13281            if (pkg == null) {
13282                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13283                throw new IllegalArgumentException("Unknown package: " + packageName);
13284            }
13285            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13286                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13287                throw new SecurityException("May not access signing KeySet of other apps.");
13288            }
13289            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13290            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13291        }
13292    }
13293
13294    @Override
13295    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13296        if (packageName == null || ks == null) {
13297            return false;
13298        }
13299        synchronized(mPackages) {
13300            final PackageParser.Package pkg = mPackages.get(packageName);
13301            if (pkg == null) {
13302                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13303                throw new IllegalArgumentException("Unknown package: " + packageName);
13304            }
13305            IBinder ksh = ks.getToken();
13306            if (ksh instanceof KeySetHandle) {
13307                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13308                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13309            }
13310            return false;
13311        }
13312    }
13313
13314    @Override
13315    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13316        if (packageName == null || ks == null) {
13317            return false;
13318        }
13319        synchronized(mPackages) {
13320            final PackageParser.Package pkg = mPackages.get(packageName);
13321            if (pkg == null) {
13322                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13323                throw new IllegalArgumentException("Unknown package: " + packageName);
13324            }
13325            IBinder ksh = ks.getToken();
13326            if (ksh instanceof KeySetHandle) {
13327                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13328                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13329            }
13330            return false;
13331        }
13332    }
13333
13334    public void getUsageStatsIfNoPackageUsageInfo() {
13335        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
13336            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
13337            if (usm == null) {
13338                throw new IllegalStateException("UsageStatsManager must be initialized");
13339            }
13340            long now = System.currentTimeMillis();
13341            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
13342            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
13343                String packageName = entry.getKey();
13344                PackageParser.Package pkg = mPackages.get(packageName);
13345                if (pkg == null) {
13346                    continue;
13347                }
13348                UsageStats usage = entry.getValue();
13349                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
13350                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
13351            }
13352        }
13353    }
13354
13355    /**
13356     * Check and throw if the given before/after packages would be considered a
13357     * downgrade.
13358     */
13359    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
13360            throws PackageManagerException {
13361        if (after.versionCode < before.mVersionCode) {
13362            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13363                    "Update version code " + after.versionCode + " is older than current "
13364                    + before.mVersionCode);
13365        } else if (after.versionCode == before.mVersionCode) {
13366            if (after.baseRevisionCode < before.baseRevisionCode) {
13367                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13368                        "Update base revision code " + after.baseRevisionCode
13369                        + " is older than current " + before.baseRevisionCode);
13370            }
13371
13372            if (!ArrayUtils.isEmpty(after.splitNames)) {
13373                for (int i = 0; i < after.splitNames.length; i++) {
13374                    final String splitName = after.splitNames[i];
13375                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
13376                    if (j != -1) {
13377                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
13378                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13379                                    "Update split " + splitName + " revision code "
13380                                    + after.splitRevisionCodes[i] + " is older than current "
13381                                    + before.splitRevisionCodes[j]);
13382                        }
13383                    }
13384                }
13385            }
13386        }
13387    }
13388}
13389