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