PackageManagerService.java revision 7f7571308d5dc973e9b1e352d56643a74e99e588
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    static final int SCAN_REQUIRE_KNOWN = 1<<12;
278
279    static final int REMOVE_CHATTY = 1<<16;
280
281    /**
282     * Timeout (in milliseconds) after which the watchdog should declare that
283     * our handler thread is wedged.  The usual default for such things is one
284     * minute but we sometimes do very lengthy I/O operations on this thread,
285     * such as installing multi-gigabyte applications, so ours needs to be longer.
286     */
287    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
288
289    /**
290     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
291     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
292     * settings entry if available, otherwise we use the hardcoded default.  If it's been
293     * more than this long since the last fstrim, we force one during the boot sequence.
294     *
295     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
296     * one gets run at the next available charging+idle time.  This final mandatory
297     * no-fstrim check kicks in only of the other scheduling criteria is never met.
298     */
299    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
300
301    /**
302     * Whether verification is enabled by default.
303     */
304    private static final boolean DEFAULT_VERIFY_ENABLE = true;
305
306    /**
307     * The default maximum time to wait for the verification agent to return in
308     * milliseconds.
309     */
310    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
311
312    /**
313     * The default response for package verification timeout.
314     *
315     * This can be either PackageManager.VERIFICATION_ALLOW or
316     * PackageManager.VERIFICATION_REJECT.
317     */
318    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
319
320    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
321
322    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
323            DEFAULT_CONTAINER_PACKAGE,
324            "com.android.defcontainer.DefaultContainerService");
325
326    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
327
328    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
329
330    final ServiceThread mHandlerThread;
331
332    final PackageHandler mHandler;
333
334    /**
335     * Messages for {@link #mHandler} that need to wait for system ready before
336     * being dispatched.
337     */
338    private ArrayList<Message> mPostSystemReadyMessages;
339
340    final int mSdkVersion = Build.VERSION.SDK_INT;
341
342    final Context mContext;
343    final boolean mFactoryTest;
344    final boolean mOnlyCore;
345    final boolean mLazyDexOpt;
346    final long mDexOptLRUThresholdInMills;
347    final DisplayMetrics mMetrics;
348    final int mDefParseFlags;
349    final String[] mSeparateProcesses;
350    final boolean mIsUpgrade;
351
352    // This is where all application persistent data goes.
353    final File mAppDataDir;
354
355    // This is where all application persistent data goes for secondary users.
356    final File mUserAppDataDir;
357
358    /** The location for ASEC container files on internal storage. */
359    final String mAsecInternalPath;
360
361    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
362    // LOCK HELD.  Can be called with mInstallLock held.
363    final Installer mInstaller;
364
365    /** Directory where installed third-party apps stored */
366    final File mAppInstallDir;
367
368    /**
369     * Directory to which applications installed internally have their
370     * 32 bit native libraries copied.
371     */
372    private File mAppLib32InstallDir;
373
374    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
375    // apps.
376    final File mDrmAppPrivateInstallDir;
377
378    // ----------------------------------------------------------------
379
380    // Lock for state used when installing and doing other long running
381    // operations.  Methods that must be called with this lock held have
382    // the suffix "LI".
383    final Object mInstallLock = new Object();
384
385    // ----------------------------------------------------------------
386
387    // Keys are String (package name), values are Package.  This also serves
388    // as the lock for the global state.  Methods that must be called with
389    // this lock held have the prefix "LP".
390    final ArrayMap<String, PackageParser.Package> mPackages =
391            new ArrayMap<String, PackageParser.Package>();
392
393    // Tracks available target package names -> overlay package paths.
394    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
395        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
396
397    final Settings mSettings;
398    boolean mRestoredSettings;
399
400    // System configuration read by SystemConfig.
401    final int[] mGlobalGids;
402    final SparseArray<ArraySet<String>> mSystemPermissions;
403    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
404
405    // If mac_permissions.xml was found for seinfo labeling.
406    boolean mFoundPolicyFile;
407
408    // If a recursive restorecon of /data/data/<pkg> is needed.
409    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
410
411    public static final class SharedLibraryEntry {
412        public final String path;
413        public final String apk;
414
415        SharedLibraryEntry(String _path, String _apk) {
416            path = _path;
417            apk = _apk;
418        }
419    }
420
421    // Currently known shared libraries.
422    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
423            new ArrayMap<String, SharedLibraryEntry>();
424
425    // All available activities, for your resolving pleasure.
426    final ActivityIntentResolver mActivities =
427            new ActivityIntentResolver();
428
429    // All available receivers, for your resolving pleasure.
430    final ActivityIntentResolver mReceivers =
431            new ActivityIntentResolver();
432
433    // All available services, for your resolving pleasure.
434    final ServiceIntentResolver mServices = new ServiceIntentResolver();
435
436    // All available providers, for your resolving pleasure.
437    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
438
439    // Mapping from provider base names (first directory in content URI codePath)
440    // to the provider information.
441    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
442            new ArrayMap<String, PackageParser.Provider>();
443
444    // Mapping from instrumentation class names to info about them.
445    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
446            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
447
448    // Mapping from permission names to info about them.
449    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
450            new ArrayMap<String, PackageParser.PermissionGroup>();
451
452    // Packages whose data we have transfered into another package, thus
453    // should no longer exist.
454    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
455
456    // Broadcast actions that are only available to the system.
457    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
458
459    /** List of packages waiting for verification. */
460    final SparseArray<PackageVerificationState> mPendingVerification
461            = new SparseArray<PackageVerificationState>();
462
463    /** Set of packages associated with each app op permission. */
464    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
465
466    final PackageInstallerService mInstallerService;
467
468    private final PackageDexOptimizer mPackageDexOptimizer;
469    // Cache of users who need badging.
470    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
471
472    /** Token for keys in mPendingVerification. */
473    private int mPendingVerificationToken = 0;
474
475    volatile boolean mSystemReady;
476    volatile boolean mSafeMode;
477    volatile boolean mHasSystemUidErrors;
478
479    ApplicationInfo mAndroidApplication;
480    final ActivityInfo mResolveActivity = new ActivityInfo();
481    final ResolveInfo mResolveInfo = new ResolveInfo();
482    ComponentName mResolveComponentName;
483    PackageParser.Package mPlatformPackage;
484    ComponentName mCustomResolverComponentName;
485
486    boolean mResolverReplaced = false;
487
488    // Set of pending broadcasts for aggregating enable/disable of components.
489    static class PendingPackageBroadcasts {
490        // for each user id, a map of <package name -> components within that package>
491        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
492
493        public PendingPackageBroadcasts() {
494            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
495        }
496
497        public ArrayList<String> get(int userId, String packageName) {
498            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
499            return packages.get(packageName);
500        }
501
502        public void put(int userId, String packageName, ArrayList<String> components) {
503            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
504            packages.put(packageName, components);
505        }
506
507        public void remove(int userId, String packageName) {
508            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
509            if (packages != null) {
510                packages.remove(packageName);
511            }
512        }
513
514        public void remove(int userId) {
515            mUidMap.remove(userId);
516        }
517
518        public int userIdCount() {
519            return mUidMap.size();
520        }
521
522        public int userIdAt(int n) {
523            return mUidMap.keyAt(n);
524        }
525
526        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
527            return mUidMap.get(userId);
528        }
529
530        public int size() {
531            // total number of pending broadcast entries across all userIds
532            int num = 0;
533            for (int i = 0; i< mUidMap.size(); i++) {
534                num += mUidMap.valueAt(i).size();
535            }
536            return num;
537        }
538
539        public void clear() {
540            mUidMap.clear();
541        }
542
543        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
544            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
545            if (map == null) {
546                map = new ArrayMap<String, ArrayList<String>>();
547                mUidMap.put(userId, map);
548            }
549            return map;
550        }
551    }
552    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
553
554    // Service Connection to remote media container service to copy
555    // package uri's from external media onto secure containers
556    // or internal storage.
557    private IMediaContainerService mContainerService = null;
558
559    static final int SEND_PENDING_BROADCAST = 1;
560    static final int MCS_BOUND = 3;
561    static final int END_COPY = 4;
562    static final int INIT_COPY = 5;
563    static final int MCS_UNBIND = 6;
564    static final int START_CLEANING_PACKAGE = 7;
565    static final int FIND_INSTALL_LOC = 8;
566    static final int POST_INSTALL = 9;
567    static final int MCS_RECONNECT = 10;
568    static final int MCS_GIVE_UP = 11;
569    static final int UPDATED_MEDIA_STATUS = 12;
570    static final int WRITE_SETTINGS = 13;
571    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
572    static final int PACKAGE_VERIFIED = 15;
573    static final int CHECK_PENDING_VERIFICATION = 16;
574
575    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
576
577    // Delay time in millisecs
578    static final int BROADCAST_DELAY = 10 * 1000;
579
580    static UserManagerService sUserManager;
581
582    // Stores a list of users whose package restrictions file needs to be updated
583    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
584
585    final private DefaultContainerConnection mDefContainerConn =
586            new DefaultContainerConnection();
587    class DefaultContainerConnection implements ServiceConnection {
588        public void onServiceConnected(ComponentName name, IBinder service) {
589            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
590            IMediaContainerService imcs =
591                IMediaContainerService.Stub.asInterface(service);
592            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
593        }
594
595        public void onServiceDisconnected(ComponentName name) {
596            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
597        }
598    };
599
600    // Recordkeeping of restore-after-install operations that are currently in flight
601    // between the Package Manager and the Backup Manager
602    class PostInstallData {
603        public InstallArgs args;
604        public PackageInstalledInfo res;
605
606        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
607            args = _a;
608            res = _r;
609        }
610    };
611    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
612    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
613
614    private final String mRequiredVerifierPackage;
615
616    private final PackageUsage mPackageUsage = new PackageUsage();
617
618    private class PackageUsage {
619        private static final int WRITE_INTERVAL
620            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
621
622        private final Object mFileLock = new Object();
623        private final AtomicLong mLastWritten = new AtomicLong(0);
624        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
625
626        private boolean mIsHistoricalPackageUsageAvailable = true;
627
628        boolean isHistoricalPackageUsageAvailable() {
629            return mIsHistoricalPackageUsageAvailable;
630        }
631
632        void write(boolean force) {
633            if (force) {
634                writeInternal();
635                return;
636            }
637            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
638                && !DEBUG_DEXOPT) {
639                return;
640            }
641            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
642                new Thread("PackageUsage_DiskWriter") {
643                    @Override
644                    public void run() {
645                        try {
646                            writeInternal();
647                        } finally {
648                            mBackgroundWriteRunning.set(false);
649                        }
650                    }
651                }.start();
652            }
653        }
654
655        private void writeInternal() {
656            synchronized (mPackages) {
657                synchronized (mFileLock) {
658                    AtomicFile file = getFile();
659                    FileOutputStream f = null;
660                    try {
661                        f = file.startWrite();
662                        BufferedOutputStream out = new BufferedOutputStream(f);
663                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
664                        StringBuilder sb = new StringBuilder();
665                        for (PackageParser.Package pkg : mPackages.values()) {
666                            if (pkg.mLastPackageUsageTimeInMills == 0) {
667                                continue;
668                            }
669                            sb.setLength(0);
670                            sb.append(pkg.packageName);
671                            sb.append(' ');
672                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
673                            sb.append('\n');
674                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
675                        }
676                        out.flush();
677                        file.finishWrite(f);
678                    } catch (IOException e) {
679                        if (f != null) {
680                            file.failWrite(f);
681                        }
682                        Log.e(TAG, "Failed to write package usage times", e);
683                    }
684                }
685            }
686            mLastWritten.set(SystemClock.elapsedRealtime());
687        }
688
689        void readLP() {
690            synchronized (mFileLock) {
691                AtomicFile file = getFile();
692                BufferedInputStream in = null;
693                try {
694                    in = new BufferedInputStream(file.openRead());
695                    StringBuffer sb = new StringBuffer();
696                    while (true) {
697                        String packageName = readToken(in, sb, ' ');
698                        if (packageName == null) {
699                            break;
700                        }
701                        String timeInMillisString = readToken(in, sb, '\n');
702                        if (timeInMillisString == null) {
703                            throw new IOException("Failed to find last usage time for package "
704                                                  + packageName);
705                        }
706                        PackageParser.Package pkg = mPackages.get(packageName);
707                        if (pkg == null) {
708                            continue;
709                        }
710                        long timeInMillis;
711                        try {
712                            timeInMillis = Long.parseLong(timeInMillisString.toString());
713                        } catch (NumberFormatException e) {
714                            throw new IOException("Failed to parse " + timeInMillisString
715                                                  + " as a long.", e);
716                        }
717                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
718                    }
719                } catch (FileNotFoundException expected) {
720                    mIsHistoricalPackageUsageAvailable = false;
721                } catch (IOException e) {
722                    Log.w(TAG, "Failed to read package usage times", e);
723                } finally {
724                    IoUtils.closeQuietly(in);
725                }
726            }
727            mLastWritten.set(SystemClock.elapsedRealtime());
728        }
729
730        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
731                throws IOException {
732            sb.setLength(0);
733            while (true) {
734                int ch = in.read();
735                if (ch == -1) {
736                    if (sb.length() == 0) {
737                        return null;
738                    }
739                    throw new IOException("Unexpected EOF");
740                }
741                if (ch == endOfToken) {
742                    return sb.toString();
743                }
744                sb.append((char)ch);
745            }
746        }
747
748        private AtomicFile getFile() {
749            File dataDir = Environment.getDataDirectory();
750            File systemDir = new File(dataDir, "system");
751            File fname = new File(systemDir, "package-usage.list");
752            return new AtomicFile(fname);
753        }
754    }
755
756    class PackageHandler extends Handler {
757        private boolean mBound = false;
758        final ArrayList<HandlerParams> mPendingInstalls =
759            new ArrayList<HandlerParams>();
760
761        private boolean connectToService() {
762            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
763                    " DefaultContainerService");
764            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
765            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
766            if (mContext.bindServiceAsUser(service, mDefContainerConn,
767                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
768                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
769                mBound = true;
770                return true;
771            }
772            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
773            return false;
774        }
775
776        private void disconnectService() {
777            mContainerService = null;
778            mBound = false;
779            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
780            mContext.unbindService(mDefContainerConn);
781            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
782        }
783
784        PackageHandler(Looper looper) {
785            super(looper);
786        }
787
788        public void handleMessage(Message msg) {
789            try {
790                doHandleMessage(msg);
791            } finally {
792                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
793            }
794        }
795
796        void doHandleMessage(Message msg) {
797            switch (msg.what) {
798                case INIT_COPY: {
799                    HandlerParams params = (HandlerParams) msg.obj;
800                    int idx = mPendingInstalls.size();
801                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
802                    // If a bind was already initiated we dont really
803                    // need to do anything. The pending install
804                    // will be processed later on.
805                    if (!mBound) {
806                        // If this is the only one pending we might
807                        // have to bind to the service again.
808                        if (!connectToService()) {
809                            Slog.e(TAG, "Failed to bind to media container service");
810                            params.serviceError();
811                            return;
812                        } else {
813                            // Once we bind to the service, the first
814                            // pending request will be processed.
815                            mPendingInstalls.add(idx, params);
816                        }
817                    } else {
818                        mPendingInstalls.add(idx, params);
819                        // Already bound to the service. Just make
820                        // sure we trigger off processing the first request.
821                        if (idx == 0) {
822                            mHandler.sendEmptyMessage(MCS_BOUND);
823                        }
824                    }
825                    break;
826                }
827                case MCS_BOUND: {
828                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
829                    if (msg.obj != null) {
830                        mContainerService = (IMediaContainerService) msg.obj;
831                    }
832                    if (mContainerService == null) {
833                        // Something seriously wrong. Bail out
834                        Slog.e(TAG, "Cannot bind to media container service");
835                        for (HandlerParams params : mPendingInstalls) {
836                            // Indicate service bind error
837                            params.serviceError();
838                        }
839                        mPendingInstalls.clear();
840                    } else if (mPendingInstalls.size() > 0) {
841                        HandlerParams params = mPendingInstalls.get(0);
842                        if (params != null) {
843                            if (params.startCopy()) {
844                                // We are done...  look for more work or to
845                                // go idle.
846                                if (DEBUG_SD_INSTALL) Log.i(TAG,
847                                        "Checking for more work or unbind...");
848                                // Delete pending install
849                                if (mPendingInstalls.size() > 0) {
850                                    mPendingInstalls.remove(0);
851                                }
852                                if (mPendingInstalls.size() == 0) {
853                                    if (mBound) {
854                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
855                                                "Posting delayed MCS_UNBIND");
856                                        removeMessages(MCS_UNBIND);
857                                        Message ubmsg = obtainMessage(MCS_UNBIND);
858                                        // Unbind after a little delay, to avoid
859                                        // continual thrashing.
860                                        sendMessageDelayed(ubmsg, 10000);
861                                    }
862                                } else {
863                                    // There are more pending requests in queue.
864                                    // Just post MCS_BOUND message to trigger processing
865                                    // of next pending install.
866                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
867                                            "Posting MCS_BOUND for next work");
868                                    mHandler.sendEmptyMessage(MCS_BOUND);
869                                }
870                            }
871                        }
872                    } else {
873                        // Should never happen ideally.
874                        Slog.w(TAG, "Empty queue");
875                    }
876                    break;
877                }
878                case MCS_RECONNECT: {
879                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
880                    if (mPendingInstalls.size() > 0) {
881                        if (mBound) {
882                            disconnectService();
883                        }
884                        if (!connectToService()) {
885                            Slog.e(TAG, "Failed to bind to media container service");
886                            for (HandlerParams params : mPendingInstalls) {
887                                // Indicate service bind error
888                                params.serviceError();
889                            }
890                            mPendingInstalls.clear();
891                        }
892                    }
893                    break;
894                }
895                case MCS_UNBIND: {
896                    // If there is no actual work left, then time to unbind.
897                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
898
899                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
900                        if (mBound) {
901                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
902
903                            disconnectService();
904                        }
905                    } else if (mPendingInstalls.size() > 0) {
906                        // There are more pending requests in queue.
907                        // Just post MCS_BOUND message to trigger processing
908                        // of next pending install.
909                        mHandler.sendEmptyMessage(MCS_BOUND);
910                    }
911
912                    break;
913                }
914                case MCS_GIVE_UP: {
915                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
916                    mPendingInstalls.remove(0);
917                    break;
918                }
919                case SEND_PENDING_BROADCAST: {
920                    String packages[];
921                    ArrayList<String> components[];
922                    int size = 0;
923                    int uids[];
924                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
925                    synchronized (mPackages) {
926                        if (mPendingBroadcasts == null) {
927                            return;
928                        }
929                        size = mPendingBroadcasts.size();
930                        if (size <= 0) {
931                            // Nothing to be done. Just return
932                            return;
933                        }
934                        packages = new String[size];
935                        components = new ArrayList[size];
936                        uids = new int[size];
937                        int i = 0;  // filling out the above arrays
938
939                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
940                            int packageUserId = mPendingBroadcasts.userIdAt(n);
941                            Iterator<Map.Entry<String, ArrayList<String>>> it
942                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
943                                            .entrySet().iterator();
944                            while (it.hasNext() && i < size) {
945                                Map.Entry<String, ArrayList<String>> ent = it.next();
946                                packages[i] = ent.getKey();
947                                components[i] = ent.getValue();
948                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
949                                uids[i] = (ps != null)
950                                        ? UserHandle.getUid(packageUserId, ps.appId)
951                                        : -1;
952                                i++;
953                            }
954                        }
955                        size = i;
956                        mPendingBroadcasts.clear();
957                    }
958                    // Send broadcasts
959                    for (int i = 0; i < size; i++) {
960                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
961                    }
962                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
963                    break;
964                }
965                case START_CLEANING_PACKAGE: {
966                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
967                    final String packageName = (String)msg.obj;
968                    final int userId = msg.arg1;
969                    final boolean andCode = msg.arg2 != 0;
970                    synchronized (mPackages) {
971                        if (userId == UserHandle.USER_ALL) {
972                            int[] users = sUserManager.getUserIds();
973                            for (int user : users) {
974                                mSettings.addPackageToCleanLPw(
975                                        new PackageCleanItem(user, packageName, andCode));
976                            }
977                        } else {
978                            mSettings.addPackageToCleanLPw(
979                                    new PackageCleanItem(userId, packageName, andCode));
980                        }
981                    }
982                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
983                    startCleaningPackages();
984                } break;
985                case POST_INSTALL: {
986                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
987                    PostInstallData data = mRunningInstalls.get(msg.arg1);
988                    mRunningInstalls.delete(msg.arg1);
989                    boolean deleteOld = false;
990
991                    if (data != null) {
992                        InstallArgs args = data.args;
993                        PackageInstalledInfo res = data.res;
994
995                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
996                            res.removedInfo.sendBroadcast(false, true, false);
997                            Bundle extras = new Bundle(1);
998                            extras.putInt(Intent.EXTRA_UID, res.uid);
999                            // Determine the set of users who are adding this
1000                            // package for the first time vs. those who are seeing
1001                            // an update.
1002                            int[] firstUsers;
1003                            int[] updateUsers = new int[0];
1004                            if (res.origUsers == null || res.origUsers.length == 0) {
1005                                firstUsers = res.newUsers;
1006                            } else {
1007                                firstUsers = new int[0];
1008                                for (int i=0; i<res.newUsers.length; i++) {
1009                                    int user = res.newUsers[i];
1010                                    boolean isNew = true;
1011                                    for (int j=0; j<res.origUsers.length; j++) {
1012                                        if (res.origUsers[j] == user) {
1013                                            isNew = false;
1014                                            break;
1015                                        }
1016                                    }
1017                                    if (isNew) {
1018                                        int[] newFirst = new int[firstUsers.length+1];
1019                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1020                                                firstUsers.length);
1021                                        newFirst[firstUsers.length] = user;
1022                                        firstUsers = newFirst;
1023                                    } else {
1024                                        int[] newUpdate = new int[updateUsers.length+1];
1025                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1026                                                updateUsers.length);
1027                                        newUpdate[updateUsers.length] = user;
1028                                        updateUsers = newUpdate;
1029                                    }
1030                                }
1031                            }
1032                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1033                                    res.pkg.applicationInfo.packageName,
1034                                    extras, null, null, firstUsers);
1035                            final boolean update = res.removedInfo.removedPackage != null;
1036                            if (update) {
1037                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1038                            }
1039                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1040                                    res.pkg.applicationInfo.packageName,
1041                                    extras, null, null, updateUsers);
1042                            if (update) {
1043                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1044                                        res.pkg.applicationInfo.packageName,
1045                                        extras, null, null, updateUsers);
1046                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1047                                        null, null,
1048                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1049
1050                                // treat asec-hosted packages like removable media on upgrade
1051                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1052                                    if (DEBUG_INSTALL) {
1053                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1054                                                + " is ASEC-hosted -> AVAILABLE");
1055                                    }
1056                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1057                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1058                                    pkgList.add(res.pkg.applicationInfo.packageName);
1059                                    sendResourcesChangedBroadcast(true, true,
1060                                            pkgList,uidArray, null);
1061                                }
1062                            }
1063                            if (res.removedInfo.args != null) {
1064                                // Remove the replaced package's older resources safely now
1065                                deleteOld = true;
1066                            }
1067
1068                            // Log current value of "unknown sources" setting
1069                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1070                                getUnknownSourcesSettings());
1071                        }
1072                        // Force a gc to clear up things
1073                        Runtime.getRuntime().gc();
1074                        // We delete after a gc for applications  on sdcard.
1075                        if (deleteOld) {
1076                            synchronized (mInstallLock) {
1077                                res.removedInfo.args.doPostDeleteLI(true);
1078                            }
1079                        }
1080                        if (args.observer != null) {
1081                            try {
1082                                Bundle extras = extrasForInstallResult(res);
1083                                args.observer.onPackageInstalled(res.name, res.returnCode,
1084                                        res.returnMsg, extras);
1085                            } catch (RemoteException e) {
1086                                Slog.i(TAG, "Observer no longer exists.");
1087                            }
1088                        }
1089                    } else {
1090                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1091                    }
1092                } break;
1093                case UPDATED_MEDIA_STATUS: {
1094                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1095                    boolean reportStatus = msg.arg1 == 1;
1096                    boolean doGc = msg.arg2 == 1;
1097                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1098                    if (doGc) {
1099                        // Force a gc to clear up stale containers.
1100                        Runtime.getRuntime().gc();
1101                    }
1102                    if (msg.obj != null) {
1103                        @SuppressWarnings("unchecked")
1104                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1105                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1106                        // Unload containers
1107                        unloadAllContainers(args);
1108                    }
1109                    if (reportStatus) {
1110                        try {
1111                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1112                            PackageHelper.getMountService().finishMediaUpdate();
1113                        } catch (RemoteException e) {
1114                            Log.e(TAG, "MountService not running?");
1115                        }
1116                    }
1117                } break;
1118                case WRITE_SETTINGS: {
1119                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1120                    synchronized (mPackages) {
1121                        removeMessages(WRITE_SETTINGS);
1122                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1123                        mSettings.writeLPr();
1124                        mDirtyUsers.clear();
1125                    }
1126                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1127                } break;
1128                case WRITE_PACKAGE_RESTRICTIONS: {
1129                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1130                    synchronized (mPackages) {
1131                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1132                        for (int userId : mDirtyUsers) {
1133                            mSettings.writePackageRestrictionsLPr(userId);
1134                        }
1135                        mDirtyUsers.clear();
1136                    }
1137                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1138                } break;
1139                case CHECK_PENDING_VERIFICATION: {
1140                    final int verificationId = msg.arg1;
1141                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1142
1143                    if ((state != null) && !state.timeoutExtended()) {
1144                        final InstallArgs args = state.getInstallArgs();
1145                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1146
1147                        Slog.i(TAG, "Verification timed out for " + originUri);
1148                        mPendingVerification.remove(verificationId);
1149
1150                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1151
1152                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1153                            Slog.i(TAG, "Continuing with installation of " + originUri);
1154                            state.setVerifierResponse(Binder.getCallingUid(),
1155                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1156                            broadcastPackageVerified(verificationId, originUri,
1157                                    PackageManager.VERIFICATION_ALLOW,
1158                                    state.getInstallArgs().getUser());
1159                            try {
1160                                ret = args.copyApk(mContainerService, true);
1161                            } catch (RemoteException e) {
1162                                Slog.e(TAG, "Could not contact the ContainerService");
1163                            }
1164                        } else {
1165                            broadcastPackageVerified(verificationId, originUri,
1166                                    PackageManager.VERIFICATION_REJECT,
1167                                    state.getInstallArgs().getUser());
1168                        }
1169
1170                        processPendingInstall(args, ret);
1171                        mHandler.sendEmptyMessage(MCS_UNBIND);
1172                    }
1173                    break;
1174                }
1175                case PACKAGE_VERIFIED: {
1176                    final int verificationId = msg.arg1;
1177
1178                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1179                    if (state == null) {
1180                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1181                        break;
1182                    }
1183
1184                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1185
1186                    state.setVerifierResponse(response.callerUid, response.code);
1187
1188                    if (state.isVerificationComplete()) {
1189                        mPendingVerification.remove(verificationId);
1190
1191                        final InstallArgs args = state.getInstallArgs();
1192                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1193
1194                        int ret;
1195                        if (state.isInstallAllowed()) {
1196                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1197                            broadcastPackageVerified(verificationId, originUri,
1198                                    response.code, state.getInstallArgs().getUser());
1199                            try {
1200                                ret = args.copyApk(mContainerService, true);
1201                            } catch (RemoteException e) {
1202                                Slog.e(TAG, "Could not contact the ContainerService");
1203                            }
1204                        } else {
1205                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1206                        }
1207
1208                        processPendingInstall(args, ret);
1209
1210                        mHandler.sendEmptyMessage(MCS_UNBIND);
1211                    }
1212
1213                    break;
1214                }
1215            }
1216        }
1217    }
1218
1219    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1220        Bundle extras = null;
1221        switch (res.returnCode) {
1222            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1223                extras = new Bundle();
1224                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1225                        res.origPermission);
1226                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1227                        res.origPackage);
1228                break;
1229            }
1230        }
1231        return extras;
1232    }
1233
1234    void scheduleWriteSettingsLocked() {
1235        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1236            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1237        }
1238    }
1239
1240    void scheduleWritePackageRestrictionsLocked(int userId) {
1241        if (!sUserManager.exists(userId)) return;
1242        mDirtyUsers.add(userId);
1243        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1244            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1245        }
1246    }
1247
1248    public static final PackageManagerService main(Context context, Installer installer,
1249            boolean factoryTest, boolean onlyCore) {
1250        PackageManagerService m = new PackageManagerService(context, installer,
1251                factoryTest, onlyCore);
1252        ServiceManager.addService("package", m);
1253        return m;
1254    }
1255
1256    static String[] splitString(String str, char sep) {
1257        int count = 1;
1258        int i = 0;
1259        while ((i=str.indexOf(sep, i)) >= 0) {
1260            count++;
1261            i++;
1262        }
1263
1264        String[] res = new String[count];
1265        i=0;
1266        count = 0;
1267        int lastI=0;
1268        while ((i=str.indexOf(sep, i)) >= 0) {
1269            res[count] = str.substring(lastI, i);
1270            count++;
1271            i++;
1272            lastI = i;
1273        }
1274        res[count] = str.substring(lastI, str.length());
1275        return res;
1276    }
1277
1278    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1279        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1280                Context.DISPLAY_SERVICE);
1281        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1282    }
1283
1284    public PackageManagerService(Context context, Installer installer,
1285            boolean factoryTest, boolean onlyCore) {
1286        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1287                SystemClock.uptimeMillis());
1288
1289        if (mSdkVersion <= 0) {
1290            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1291        }
1292
1293        mContext = context;
1294        mFactoryTest = factoryTest;
1295        mOnlyCore = onlyCore;
1296        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1297        mMetrics = new DisplayMetrics();
1298        mSettings = new Settings(context);
1299        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1300                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1301        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1302                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1303        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1304                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1305        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1306                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1307        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1308                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1309        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1310                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1311
1312        // TODO: add a property to control this?
1313        long dexOptLRUThresholdInMinutes;
1314        if (mLazyDexOpt) {
1315            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1316        } else {
1317            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1318        }
1319        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1320
1321        String separateProcesses = SystemProperties.get("debug.separate_processes");
1322        if (separateProcesses != null && separateProcesses.length() > 0) {
1323            if ("*".equals(separateProcesses)) {
1324                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1325                mSeparateProcesses = null;
1326                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1327            } else {
1328                mDefParseFlags = 0;
1329                mSeparateProcesses = separateProcesses.split(",");
1330                Slog.w(TAG, "Running with debug.separate_processes: "
1331                        + separateProcesses);
1332            }
1333        } else {
1334            mDefParseFlags = 0;
1335            mSeparateProcesses = null;
1336        }
1337
1338        mInstaller = installer;
1339        mPackageDexOptimizer = new PackageDexOptimizer(this);
1340
1341        getDefaultDisplayMetrics(context, mMetrics);
1342
1343        SystemConfig systemConfig = SystemConfig.getInstance();
1344        mGlobalGids = systemConfig.getGlobalGids();
1345        mSystemPermissions = systemConfig.getSystemPermissions();
1346        mAvailableFeatures = systemConfig.getAvailableFeatures();
1347
1348        synchronized (mInstallLock) {
1349        // writer
1350        synchronized (mPackages) {
1351            mHandlerThread = new ServiceThread(TAG,
1352                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1353            mHandlerThread.start();
1354            mHandler = new PackageHandler(mHandlerThread.getLooper());
1355            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1356
1357            File dataDir = Environment.getDataDirectory();
1358            mAppDataDir = new File(dataDir, "data");
1359            mAppInstallDir = new File(dataDir, "app");
1360            mAppLib32InstallDir = new File(dataDir, "app-lib");
1361            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1362            mUserAppDataDir = new File(dataDir, "user");
1363            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1364
1365            sUserManager = new UserManagerService(context, this,
1366                    mInstallLock, mPackages);
1367
1368            // Propagate permission configuration in to package manager.
1369            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1370                    = systemConfig.getPermissions();
1371            for (int i=0; i<permConfig.size(); i++) {
1372                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1373                BasePermission bp = mSettings.mPermissions.get(perm.name);
1374                if (bp == null) {
1375                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1376                    mSettings.mPermissions.put(perm.name, bp);
1377                }
1378                if (perm.gids != null) {
1379                    bp.gids = appendInts(bp.gids, perm.gids);
1380                }
1381            }
1382
1383            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1384            for (int i=0; i<libConfig.size(); i++) {
1385                mSharedLibraries.put(libConfig.keyAt(i),
1386                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1387            }
1388
1389            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1390
1391            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1392                    mSdkVersion, mOnlyCore);
1393
1394            String customResolverActivity = Resources.getSystem().getString(
1395                    R.string.config_customResolverActivity);
1396            if (TextUtils.isEmpty(customResolverActivity)) {
1397                customResolverActivity = null;
1398            } else {
1399                mCustomResolverComponentName = ComponentName.unflattenFromString(
1400                        customResolverActivity);
1401            }
1402
1403            long startTime = SystemClock.uptimeMillis();
1404
1405            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1406                    startTime);
1407
1408            // Set flag to monitor and not change apk file paths when
1409            // scanning install directories.
1410            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1411
1412            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1413
1414            /**
1415             * Add everything in the in the boot class path to the
1416             * list of process files because dexopt will have been run
1417             * if necessary during zygote startup.
1418             */
1419            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1420            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1421
1422            if (bootClassPath != null) {
1423                String[] bootClassPathElements = splitString(bootClassPath, ':');
1424                for (String element : bootClassPathElements) {
1425                    alreadyDexOpted.add(element);
1426                }
1427            } else {
1428                Slog.w(TAG, "No BOOTCLASSPATH found!");
1429            }
1430
1431            if (systemServerClassPath != null) {
1432                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1433                for (String element : systemServerClassPathElements) {
1434                    alreadyDexOpted.add(element);
1435                }
1436            } else {
1437                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1438            }
1439
1440            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1441            final String[] dexCodeInstructionSets =
1442                    getDexCodeInstructionSets(
1443                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1444
1445            /**
1446             * Ensure all external libraries have had dexopt run on them.
1447             */
1448            if (mSharedLibraries.size() > 0) {
1449                // NOTE: For now, we're compiling these system "shared libraries"
1450                // (and framework jars) into all available architectures. It's possible
1451                // to compile them only when we come across an app that uses them (there's
1452                // already logic for that in scanPackageLI) but that adds some complexity.
1453                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1454                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1455                        final String lib = libEntry.path;
1456                        if (lib == null) {
1457                            continue;
1458                        }
1459
1460                        try {
1461                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1462                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1463                                alreadyDexOpted.add(lib);
1464                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1465                            }
1466                        } catch (FileNotFoundException e) {
1467                            Slog.w(TAG, "Library not found: " + lib);
1468                        } catch (IOException e) {
1469                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1470                                    + e.getMessage());
1471                        }
1472                    }
1473                }
1474            }
1475
1476            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1477
1478            // Gross hack for now: we know this file doesn't contain any
1479            // code, so don't dexopt it to avoid the resulting log spew.
1480            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1481
1482            // Gross hack for now: we know this file is only part of
1483            // the boot class path for art, so don't dexopt it to
1484            // avoid the resulting log spew.
1485            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1486
1487            /**
1488             * And there are a number of commands implemented in Java, which
1489             * we currently need to do the dexopt on so that they can be
1490             * run from a non-root shell.
1491             */
1492            String[] frameworkFiles = frameworkDir.list();
1493            if (frameworkFiles != null) {
1494                // TODO: We could compile these only for the most preferred ABI. We should
1495                // first double check that the dex files for these commands are not referenced
1496                // by other system apps.
1497                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1498                    for (int i=0; i<frameworkFiles.length; i++) {
1499                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1500                        String path = libPath.getPath();
1501                        // Skip the file if we already did it.
1502                        if (alreadyDexOpted.contains(path)) {
1503                            continue;
1504                        }
1505                        // Skip the file if it is not a type we want to dexopt.
1506                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1507                            continue;
1508                        }
1509                        try {
1510                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1511                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1512                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1513                            }
1514                        } catch (FileNotFoundException e) {
1515                            Slog.w(TAG, "Jar not found: " + path);
1516                        } catch (IOException e) {
1517                            Slog.w(TAG, "Exception reading jar: " + path, e);
1518                        }
1519                    }
1520                }
1521            }
1522
1523            // Collect vendor overlay packages.
1524            // (Do this before scanning any apps.)
1525            // For security and version matching reason, only consider
1526            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1527            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1528            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1529                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1530
1531            // Find base frameworks (resource packages without code).
1532            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1533                    | PackageParser.PARSE_IS_SYSTEM_DIR
1534                    | PackageParser.PARSE_IS_PRIVILEGED,
1535                    scanFlags | SCAN_NO_DEX, 0);
1536
1537            // Collected privileged system packages.
1538            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1539            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1540                    | PackageParser.PARSE_IS_SYSTEM_DIR
1541                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1542
1543            // Collect ordinary system packages.
1544            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1545            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1546                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1547
1548            // Collect all vendor packages.
1549            File vendorAppDir = new File("/vendor/app");
1550            try {
1551                vendorAppDir = vendorAppDir.getCanonicalFile();
1552            } catch (IOException e) {
1553                // failed to look up canonical path, continue with original one
1554            }
1555            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1556                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1557
1558            // Collect all OEM packages.
1559            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1560            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1561                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1562
1563            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1564            mInstaller.moveFiles();
1565
1566            // Prune any system packages that no longer exist.
1567            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1568            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1569            if (!mOnlyCore) {
1570                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1571                while (psit.hasNext()) {
1572                    PackageSetting ps = psit.next();
1573
1574                    /*
1575                     * If this is not a system app, it can't be a
1576                     * disable system app.
1577                     */
1578                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1579                        continue;
1580                    }
1581
1582                    /*
1583                     * If the package is scanned, it's not erased.
1584                     */
1585                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1586                    if (scannedPkg != null) {
1587                        /*
1588                         * If the system app is both scanned and in the
1589                         * disabled packages list, then it must have been
1590                         * added via OTA. Remove it from the currently
1591                         * scanned package so the previously user-installed
1592                         * application can be scanned.
1593                         */
1594                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1595                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1596                                    + ps.name + "; removing system app.  Last known codePath="
1597                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1598                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1599                                    + scannedPkg.mVersionCode);
1600                            removePackageLI(ps, true);
1601                            expectingBetter.put(ps.name, ps.codePath);
1602                        }
1603
1604                        continue;
1605                    }
1606
1607                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1608                        psit.remove();
1609                        logCriticalInfo(Log.WARN, "System package " + ps.name
1610                                + " no longer exists; wiping its data");
1611                        removeDataDirsLI(ps.name);
1612                    } else {
1613                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1614                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1615                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1616                        }
1617                    }
1618                }
1619            }
1620
1621            //look for any incomplete package installations
1622            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1623            //clean up list
1624            for(int i = 0; i < deletePkgsList.size(); i++) {
1625                //clean up here
1626                cleanupInstallFailedPackage(deletePkgsList.get(i));
1627            }
1628            //delete tmp files
1629            deleteTempPackageFiles();
1630
1631            // Remove any shared userIDs that have no associated packages
1632            mSettings.pruneSharedUsersLPw();
1633
1634            if (!mOnlyCore) {
1635                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1636                        SystemClock.uptimeMillis());
1637                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
1638
1639                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1640                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
1641
1642                /**
1643                 * Remove disable package settings for any updated system
1644                 * apps that were removed via an OTA. If they're not a
1645                 * previously-updated app, remove them completely.
1646                 * Otherwise, just revoke their system-level permissions.
1647                 */
1648                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1649                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1650                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1651
1652                    String msg;
1653                    if (deletedPkg == null) {
1654                        msg = "Updated system package " + deletedAppName
1655                                + " no longer exists; wiping its data";
1656                        removeDataDirsLI(deletedAppName);
1657                    } else {
1658                        msg = "Updated system app + " + deletedAppName
1659                                + " no longer present; removing system privileges for "
1660                                + deletedAppName;
1661
1662                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1663
1664                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1665                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1666                    }
1667                    logCriticalInfo(Log.WARN, msg);
1668                }
1669
1670                /**
1671                 * Make sure all system apps that we expected to appear on
1672                 * the userdata partition actually showed up. If they never
1673                 * appeared, crawl back and revive the system version.
1674                 */
1675                for (int i = 0; i < expectingBetter.size(); i++) {
1676                    final String packageName = expectingBetter.keyAt(i);
1677                    if (!mPackages.containsKey(packageName)) {
1678                        final File scanFile = expectingBetter.valueAt(i);
1679
1680                        logCriticalInfo(Log.WARN, "Expected better " + packageName
1681                                + " but never showed up; reverting to system");
1682
1683                        final int reparseFlags;
1684                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
1685                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1686                                    | PackageParser.PARSE_IS_SYSTEM_DIR
1687                                    | PackageParser.PARSE_IS_PRIVILEGED;
1688                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
1689                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1690                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1691                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
1692                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1693                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1694                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
1695                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1696                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1697                        } else {
1698                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
1699                            continue;
1700                        }
1701
1702                        mSettings.enableSystemPackageLPw(packageName);
1703
1704                        try {
1705                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
1706                        } catch (PackageManagerException e) {
1707                            Slog.e(TAG, "Failed to parse original system package: "
1708                                    + e.getMessage());
1709                        }
1710                    }
1711                }
1712            }
1713
1714            // Now that we know all of the shared libraries, update all clients to have
1715            // the correct library paths.
1716            updateAllSharedLibrariesLPw();
1717
1718            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1719                // NOTE: We ignore potential failures here during a system scan (like
1720                // the rest of the commands above) because there's precious little we
1721                // can do about it. A settings error is reported, though.
1722                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1723                        false /* force dexopt */, false /* defer dexopt */);
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            // Give priority to system apps.
4633            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4634                PackageParser.Package pkg = it.next();
4635                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
4636                    if (DEBUG_DEXOPT) {
4637                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
4638                    }
4639                    sortedPkgs.add(pkg);
4640                    it.remove();
4641                }
4642            }
4643            // Give priority to updated system apps.
4644            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4645                PackageParser.Package pkg = it.next();
4646                if (pkg.isUpdatedSystemApp()) {
4647                    if (DEBUG_DEXOPT) {
4648                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
4649                    }
4650                    sortedPkgs.add(pkg);
4651                    it.remove();
4652                }
4653            }
4654            // Give priority to apps that listen for boot complete.
4655            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
4656            pkgNames = getPackageNamesForIntent(intent);
4657            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4658                PackageParser.Package pkg = it.next();
4659                if (pkgNames.contains(pkg.packageName)) {
4660                    if (DEBUG_DEXOPT) {
4661                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
4662                    }
4663                    sortedPkgs.add(pkg);
4664                    it.remove();
4665                }
4666            }
4667            // Filter out packages that aren't recently used.
4668            filterRecentlyUsedApps(pkgs);
4669            // Add all remaining apps.
4670            for (PackageParser.Package pkg : pkgs) {
4671                if (DEBUG_DEXOPT) {
4672                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
4673                }
4674                sortedPkgs.add(pkg);
4675            }
4676
4677            // If we want to be lazy, filter everything that wasn't recently used.
4678            if (mLazyDexOpt) {
4679                filterRecentlyUsedApps(sortedPkgs);
4680            }
4681
4682            int i = 0;
4683            int total = sortedPkgs.size();
4684            File dataDir = Environment.getDataDirectory();
4685            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
4686            if (lowThreshold == 0) {
4687                throw new IllegalStateException("Invalid low memory threshold");
4688            }
4689            for (PackageParser.Package pkg : sortedPkgs) {
4690                long usableSpace = dataDir.getUsableSpace();
4691                if (usableSpace < lowThreshold) {
4692                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
4693                    break;
4694                }
4695                performBootDexOpt(pkg, ++i, total);
4696            }
4697        }
4698    }
4699
4700    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
4701        // Filter out packages that aren't recently used.
4702        //
4703        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4704        // should do a full dexopt.
4705        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4706            int total = pkgs.size();
4707            int skipped = 0;
4708            long now = System.currentTimeMillis();
4709            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4710                PackageParser.Package pkg = i.next();
4711                long then = pkg.mLastPackageUsageTimeInMills;
4712                if (then + mDexOptLRUThresholdInMills < now) {
4713                    if (DEBUG_DEXOPT) {
4714                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4715                              ((then == 0) ? "never" : new Date(then)));
4716                    }
4717                    i.remove();
4718                    skipped++;
4719                }
4720            }
4721            if (DEBUG_DEXOPT) {
4722                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4723            }
4724        }
4725    }
4726
4727    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
4728        List<ResolveInfo> ris = null;
4729        try {
4730            ris = AppGlobals.getPackageManager().queryIntentReceivers(
4731                    intent, null, 0, UserHandle.USER_OWNER);
4732        } catch (RemoteException e) {
4733        }
4734        ArraySet<String> pkgNames = new ArraySet<String>();
4735        if (ris != null) {
4736            for (ResolveInfo ri : ris) {
4737                pkgNames.add(ri.activityInfo.packageName);
4738            }
4739        }
4740        return pkgNames;
4741    }
4742
4743    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
4744        if (DEBUG_DEXOPT) {
4745            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
4746        }
4747        if (!isFirstBoot()) {
4748            try {
4749                ActivityManagerNative.getDefault().showBootMessage(
4750                        mContext.getResources().getString(R.string.android_upgrading_apk,
4751                                curr, total), true);
4752            } catch (RemoteException e) {
4753            }
4754        }
4755        PackageParser.Package p = pkg;
4756        synchronized (mInstallLock) {
4757            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
4758                    false /* force dex */, false /* defer */, true /* include dependencies */);
4759        }
4760    }
4761
4762    @Override
4763    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4764        return performDexOpt(packageName, instructionSet, false);
4765    }
4766
4767    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4768        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4769        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4770        if (!dexopt && !updateUsage) {
4771            // We aren't going to dexopt or update usage, so bail early.
4772            return false;
4773        }
4774        PackageParser.Package p;
4775        final String targetInstructionSet;
4776        synchronized (mPackages) {
4777            p = mPackages.get(packageName);
4778            if (p == null) {
4779                return false;
4780            }
4781            if (updateUsage) {
4782                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4783            }
4784            mPackageUsage.write(false);
4785            if (!dexopt) {
4786                // We aren't going to dexopt, so bail early.
4787                return false;
4788            }
4789
4790            targetInstructionSet = instructionSet != null ? instructionSet :
4791                    getPrimaryInstructionSet(p.applicationInfo);
4792            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4793                return false;
4794            }
4795        }
4796
4797        synchronized (mInstallLock) {
4798            final String[] instructionSets = new String[] { targetInstructionSet };
4799            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
4800                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
4801            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
4802        }
4803    }
4804
4805    public ArraySet<String> getPackagesThatNeedDexOpt() {
4806        ArraySet<String> pkgs = null;
4807        synchronized (mPackages) {
4808            for (PackageParser.Package p : mPackages.values()) {
4809                if (DEBUG_DEXOPT) {
4810                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4811                }
4812                if (!p.mDexOptPerformed.isEmpty()) {
4813                    continue;
4814                }
4815                if (pkgs == null) {
4816                    pkgs = new ArraySet<String>();
4817                }
4818                pkgs.add(p.packageName);
4819            }
4820        }
4821        return pkgs;
4822    }
4823
4824    public void shutdown() {
4825        mPackageUsage.write(true);
4826    }
4827
4828    @Override
4829    public void forceDexOpt(String packageName) {
4830        enforceSystemOrRoot("forceDexOpt");
4831
4832        PackageParser.Package pkg;
4833        synchronized (mPackages) {
4834            pkg = mPackages.get(packageName);
4835            if (pkg == null) {
4836                throw new IllegalArgumentException("Missing package: " + packageName);
4837            }
4838        }
4839
4840        synchronized (mInstallLock) {
4841            final String[] instructionSets = new String[] {
4842                    getPrimaryInstructionSet(pkg.applicationInfo) };
4843            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
4844                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
4845            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
4846                throw new IllegalStateException("Failed to dexopt: " + res);
4847            }
4848        }
4849    }
4850
4851    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4852        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4853            Slog.w(TAG, "Unable to update from " + oldPkg.name
4854                    + " to " + newPkg.packageName
4855                    + ": old package not in system partition");
4856            return false;
4857        } else if (mPackages.get(oldPkg.name) != null) {
4858            Slog.w(TAG, "Unable to update from " + oldPkg.name
4859                    + " to " + newPkg.packageName
4860                    + ": old package still exists");
4861            return false;
4862        }
4863        return true;
4864    }
4865
4866    private File getDataPathForPackage(String packageName, int userId) {
4867        /*
4868         * Until we fully support multiple users, return the directory we
4869         * previously would have. The PackageManagerTests will need to be
4870         * revised when this is changed back..
4871         */
4872        if (userId == 0) {
4873            return new File(mAppDataDir, packageName);
4874        } else {
4875            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4876                + File.separator + packageName);
4877        }
4878    }
4879
4880    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4881        int[] users = sUserManager.getUserIds();
4882        int res = mInstaller.install(packageName, uid, uid, seinfo);
4883        if (res < 0) {
4884            return res;
4885        }
4886        for (int user : users) {
4887            if (user != 0) {
4888                res = mInstaller.createUserData(packageName,
4889                        UserHandle.getUid(user, uid), user, seinfo);
4890                if (res < 0) {
4891                    return res;
4892                }
4893            }
4894        }
4895        return res;
4896    }
4897
4898    private int removeDataDirsLI(String packageName) {
4899        int[] users = sUserManager.getUserIds();
4900        int res = 0;
4901        for (int user : users) {
4902            int resInner = mInstaller.remove(packageName, user);
4903            if (resInner < 0) {
4904                res = resInner;
4905            }
4906        }
4907
4908        return res;
4909    }
4910
4911    private int deleteCodeCacheDirsLI(String packageName) {
4912        int[] users = sUserManager.getUserIds();
4913        int res = 0;
4914        for (int user : users) {
4915            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4916            if (resInner < 0) {
4917                res = resInner;
4918            }
4919        }
4920        return res;
4921    }
4922
4923    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4924            PackageParser.Package changingLib) {
4925        if (file.path != null) {
4926            usesLibraryFiles.add(file.path);
4927            return;
4928        }
4929        PackageParser.Package p = mPackages.get(file.apk);
4930        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4931            // If we are doing this while in the middle of updating a library apk,
4932            // then we need to make sure to use that new apk for determining the
4933            // dependencies here.  (We haven't yet finished committing the new apk
4934            // to the package manager state.)
4935            if (p == null || p.packageName.equals(changingLib.packageName)) {
4936                p = changingLib;
4937            }
4938        }
4939        if (p != null) {
4940            usesLibraryFiles.addAll(p.getAllCodePaths());
4941        }
4942    }
4943
4944    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4945            PackageParser.Package changingLib) throws PackageManagerException {
4946        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4947            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4948            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4949            for (int i=0; i<N; i++) {
4950                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4951                if (file == null) {
4952                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4953                            "Package " + pkg.packageName + " requires unavailable shared library "
4954                            + pkg.usesLibraries.get(i) + "; failing!");
4955                }
4956                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4957            }
4958            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4959            for (int i=0; i<N; i++) {
4960                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4961                if (file == null) {
4962                    Slog.w(TAG, "Package " + pkg.packageName
4963                            + " desires unavailable shared library "
4964                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4965                } else {
4966                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4967                }
4968            }
4969            N = usesLibraryFiles.size();
4970            if (N > 0) {
4971                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4972            } else {
4973                pkg.usesLibraryFiles = null;
4974            }
4975        }
4976    }
4977
4978    private static boolean hasString(List<String> list, List<String> which) {
4979        if (list == null) {
4980            return false;
4981        }
4982        for (int i=list.size()-1; i>=0; i--) {
4983            for (int j=which.size()-1; j>=0; j--) {
4984                if (which.get(j).equals(list.get(i))) {
4985                    return true;
4986                }
4987            }
4988        }
4989        return false;
4990    }
4991
4992    private void updateAllSharedLibrariesLPw() {
4993        for (PackageParser.Package pkg : mPackages.values()) {
4994            try {
4995                updateSharedLibrariesLPw(pkg, null);
4996            } catch (PackageManagerException e) {
4997                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4998            }
4999        }
5000    }
5001
5002    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5003            PackageParser.Package changingPkg) {
5004        ArrayList<PackageParser.Package> res = null;
5005        for (PackageParser.Package pkg : mPackages.values()) {
5006            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5007                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5008                if (res == null) {
5009                    res = new ArrayList<PackageParser.Package>();
5010                }
5011                res.add(pkg);
5012                try {
5013                    updateSharedLibrariesLPw(pkg, changingPkg);
5014                } catch (PackageManagerException e) {
5015                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5016                }
5017            }
5018        }
5019        return res;
5020    }
5021
5022    /**
5023     * Derive the value of the {@code cpuAbiOverride} based on the provided
5024     * value and an optional stored value from the package settings.
5025     */
5026    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5027        String cpuAbiOverride = null;
5028
5029        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5030            cpuAbiOverride = null;
5031        } else if (abiOverride != null) {
5032            cpuAbiOverride = abiOverride;
5033        } else if (settings != null) {
5034            cpuAbiOverride = settings.cpuAbiOverrideString;
5035        }
5036
5037        return cpuAbiOverride;
5038    }
5039
5040    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5041            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5042        boolean success = false;
5043        try {
5044            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5045                    currentTime, user);
5046            success = true;
5047            return res;
5048        } finally {
5049            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5050                removeDataDirsLI(pkg.packageName);
5051            }
5052        }
5053    }
5054
5055    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5056            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5057        final File scanFile = new File(pkg.codePath);
5058        if (pkg.applicationInfo.getCodePath() == null ||
5059                pkg.applicationInfo.getResourcePath() == null) {
5060            // Bail out. The resource and code paths haven't been set.
5061            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5062                    "Code and resource paths haven't been set correctly");
5063        }
5064
5065        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5066            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5067        } else {
5068            // Only allow system apps to be flagged as core apps.
5069            pkg.coreApp = false;
5070        }
5071
5072        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5073            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5074        }
5075
5076        if (mCustomResolverComponentName != null &&
5077                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5078            setUpCustomResolverActivity(pkg);
5079        }
5080
5081        if (pkg.packageName.equals("android")) {
5082            synchronized (mPackages) {
5083                if (mAndroidApplication != null) {
5084                    Slog.w(TAG, "*************************************************");
5085                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5086                    Slog.w(TAG, " file=" + scanFile);
5087                    Slog.w(TAG, "*************************************************");
5088                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5089                            "Core android package being redefined.  Skipping.");
5090                }
5091
5092                // Set up information for our fall-back user intent resolution activity.
5093                mPlatformPackage = pkg;
5094                pkg.mVersionCode = mSdkVersion;
5095                mAndroidApplication = pkg.applicationInfo;
5096
5097                if (!mResolverReplaced) {
5098                    mResolveActivity.applicationInfo = mAndroidApplication;
5099                    mResolveActivity.name = ResolverActivity.class.getName();
5100                    mResolveActivity.packageName = mAndroidApplication.packageName;
5101                    mResolveActivity.processName = "system:ui";
5102                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5103                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5104                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5105                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5106                    mResolveActivity.exported = true;
5107                    mResolveActivity.enabled = true;
5108                    mResolveInfo.activityInfo = mResolveActivity;
5109                    mResolveInfo.priority = 0;
5110                    mResolveInfo.preferredOrder = 0;
5111                    mResolveInfo.match = 0;
5112                    mResolveComponentName = new ComponentName(
5113                            mAndroidApplication.packageName, mResolveActivity.name);
5114                }
5115            }
5116        }
5117
5118        if (DEBUG_PACKAGE_SCANNING) {
5119            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5120                Log.d(TAG, "Scanning package " + pkg.packageName);
5121        }
5122
5123        if (mPackages.containsKey(pkg.packageName)
5124                || mSharedLibraries.containsKey(pkg.packageName)) {
5125            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5126                    "Application package " + pkg.packageName
5127                    + " already installed.  Skipping duplicate.");
5128        }
5129
5130        // If we're only installing presumed-existing packages, require that the
5131        // scanned APK is both already known and at the path previously established
5132        // for it.  Previously unknown packages we pick up normally, but if we have an
5133        // a priori expectation about this package's install presence, enforce it.
5134        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
5135            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
5136            if (known != null) {
5137                if (DEBUG_PACKAGE_SCANNING) {
5138                    Log.d(TAG, "Examining " + pkg.codePath
5139                            + " and requiring known paths " + known.codePathString
5140                            + " & " + known.resourcePathString);
5141                }
5142                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
5143                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
5144                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
5145                            "Application package " + pkg.packageName
5146                            + " found at " + pkg.applicationInfo.getCodePath()
5147                            + " but expected at " + known.codePathString + "; ignoring.");
5148                }
5149            }
5150        }
5151
5152        // Initialize package source and resource directories
5153        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5154        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5155
5156        SharedUserSetting suid = null;
5157        PackageSetting pkgSetting = null;
5158
5159        if (!isSystemApp(pkg)) {
5160            // Only system apps can use these features.
5161            pkg.mOriginalPackages = null;
5162            pkg.mRealPackage = null;
5163            pkg.mAdoptPermissions = null;
5164        }
5165
5166        // writer
5167        synchronized (mPackages) {
5168            if (pkg.mSharedUserId != null) {
5169                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5170                if (suid == null) {
5171                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5172                            "Creating application package " + pkg.packageName
5173                            + " for shared user failed");
5174                }
5175                if (DEBUG_PACKAGE_SCANNING) {
5176                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5177                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5178                                + "): packages=" + suid.packages);
5179                }
5180            }
5181
5182            // Check if we are renaming from an original package name.
5183            PackageSetting origPackage = null;
5184            String realName = null;
5185            if (pkg.mOriginalPackages != null) {
5186                // This package may need to be renamed to a previously
5187                // installed name.  Let's check on that...
5188                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5189                if (pkg.mOriginalPackages.contains(renamed)) {
5190                    // This package had originally been installed as the
5191                    // original name, and we have already taken care of
5192                    // transitioning to the new one.  Just update the new
5193                    // one to continue using the old name.
5194                    realName = pkg.mRealPackage;
5195                    if (!pkg.packageName.equals(renamed)) {
5196                        // Callers into this function may have already taken
5197                        // care of renaming the package; only do it here if
5198                        // it is not already done.
5199                        pkg.setPackageName(renamed);
5200                    }
5201
5202                } else {
5203                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5204                        if ((origPackage = mSettings.peekPackageLPr(
5205                                pkg.mOriginalPackages.get(i))) != null) {
5206                            // We do have the package already installed under its
5207                            // original name...  should we use it?
5208                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5209                                // New package is not compatible with original.
5210                                origPackage = null;
5211                                continue;
5212                            } else if (origPackage.sharedUser != null) {
5213                                // Make sure uid is compatible between packages.
5214                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5215                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5216                                            + " to " + pkg.packageName + ": old uid "
5217                                            + origPackage.sharedUser.name
5218                                            + " differs from " + pkg.mSharedUserId);
5219                                    origPackage = null;
5220                                    continue;
5221                                }
5222                            } else {
5223                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5224                                        + pkg.packageName + " to old name " + origPackage.name);
5225                            }
5226                            break;
5227                        }
5228                    }
5229                }
5230            }
5231
5232            if (mTransferedPackages.contains(pkg.packageName)) {
5233                Slog.w(TAG, "Package " + pkg.packageName
5234                        + " was transferred to another, but its .apk remains");
5235            }
5236
5237            // Just create the setting, don't add it yet. For already existing packages
5238            // the PkgSetting exists already and doesn't have to be created.
5239            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5240                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5241                    pkg.applicationInfo.primaryCpuAbi,
5242                    pkg.applicationInfo.secondaryCpuAbi,
5243                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
5244                    user, false);
5245            if (pkgSetting == null) {
5246                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5247                        "Creating application package " + pkg.packageName + " failed");
5248            }
5249
5250            if (pkgSetting.origPackage != null) {
5251                // If we are first transitioning from an original package,
5252                // fix up the new package's name now.  We need to do this after
5253                // looking up the package under its new name, so getPackageLP
5254                // can take care of fiddling things correctly.
5255                pkg.setPackageName(origPackage.name);
5256
5257                // File a report about this.
5258                String msg = "New package " + pkgSetting.realName
5259                        + " renamed to replace old package " + pkgSetting.name;
5260                reportSettingsProblem(Log.WARN, msg);
5261
5262                // Make a note of it.
5263                mTransferedPackages.add(origPackage.name);
5264
5265                // No longer need to retain this.
5266                pkgSetting.origPackage = null;
5267            }
5268
5269            if (realName != null) {
5270                // Make a note of it.
5271                mTransferedPackages.add(pkg.packageName);
5272            }
5273
5274            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5275                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5276            }
5277
5278            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5279                // Check all shared libraries and map to their actual file path.
5280                // We only do this here for apps not on a system dir, because those
5281                // are the only ones that can fail an install due to this.  We
5282                // will take care of the system apps by updating all of their
5283                // library paths after the scan is done.
5284                updateSharedLibrariesLPw(pkg, null);
5285            }
5286
5287            if (mFoundPolicyFile) {
5288                SELinuxMMAC.assignSeinfoValue(pkg);
5289            }
5290
5291            pkg.applicationInfo.uid = pkgSetting.appId;
5292            pkg.mExtras = pkgSetting;
5293            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5294                try {
5295                    verifySignaturesLP(pkgSetting, pkg);
5296                    // We just determined the app is signed correctly, so bring
5297                    // over the latest parsed certs.
5298                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5299                } catch (PackageManagerException e) {
5300                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5301                        throw e;
5302                    }
5303                    // The signature has changed, but this package is in the system
5304                    // image...  let's recover!
5305                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5306                    // However...  if this package is part of a shared user, but it
5307                    // doesn't match the signature of the shared user, let's fail.
5308                    // What this means is that you can't change the signatures
5309                    // associated with an overall shared user, which doesn't seem all
5310                    // that unreasonable.
5311                    if (pkgSetting.sharedUser != null) {
5312                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5313                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5314                            throw new PackageManagerException(
5315                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5316                                            "Signature mismatch for shared user : "
5317                                            + pkgSetting.sharedUser);
5318                        }
5319                    }
5320                    // File a report about this.
5321                    String msg = "System package " + pkg.packageName
5322                        + " signature changed; retaining data.";
5323                    reportSettingsProblem(Log.WARN, msg);
5324                }
5325            } else {
5326                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5327                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5328                            + pkg.packageName + " upgrade keys do not match the "
5329                            + "previously installed version");
5330                } else {
5331                    // We just determined the app is signed correctly, so bring
5332                    // over the latest parsed certs.
5333                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5334                }
5335            }
5336            // Verify that this new package doesn't have any content providers
5337            // that conflict with existing packages.  Only do this if the
5338            // package isn't already installed, since we don't want to break
5339            // things that are installed.
5340            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5341                final int N = pkg.providers.size();
5342                int i;
5343                for (i=0; i<N; i++) {
5344                    PackageParser.Provider p = pkg.providers.get(i);
5345                    if (p.info.authority != null) {
5346                        String names[] = p.info.authority.split(";");
5347                        for (int j = 0; j < names.length; j++) {
5348                            if (mProvidersByAuthority.containsKey(names[j])) {
5349                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5350                                final String otherPackageName =
5351                                        ((other != null && other.getComponentName() != null) ?
5352                                                other.getComponentName().getPackageName() : "?");
5353                                throw new PackageManagerException(
5354                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5355                                                "Can't install because provider name " + names[j]
5356                                                + " (in package " + pkg.applicationInfo.packageName
5357                                                + ") is already used by " + otherPackageName);
5358                            }
5359                        }
5360                    }
5361                }
5362            }
5363
5364            if (pkg.mAdoptPermissions != null) {
5365                // This package wants to adopt ownership of permissions from
5366                // another package.
5367                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5368                    final String origName = pkg.mAdoptPermissions.get(i);
5369                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5370                    if (orig != null) {
5371                        if (verifyPackageUpdateLPr(orig, pkg)) {
5372                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5373                                    + pkg.packageName);
5374                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5375                        }
5376                    }
5377                }
5378            }
5379        }
5380
5381        final String pkgName = pkg.packageName;
5382
5383        final long scanFileTime = scanFile.lastModified();
5384        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5385        pkg.applicationInfo.processName = fixProcessName(
5386                pkg.applicationInfo.packageName,
5387                pkg.applicationInfo.processName,
5388                pkg.applicationInfo.uid);
5389
5390        File dataPath;
5391        if (mPlatformPackage == pkg) {
5392            // The system package is special.
5393            dataPath = new File(Environment.getDataDirectory(), "system");
5394
5395            pkg.applicationInfo.dataDir = dataPath.getPath();
5396
5397        } else {
5398            // This is a normal package, need to make its data directory.
5399            dataPath = getDataPathForPackage(pkg.packageName, 0);
5400
5401            boolean uidError = false;
5402            if (dataPath.exists()) {
5403                int currentUid = 0;
5404                try {
5405                    StructStat stat = Os.stat(dataPath.getPath());
5406                    currentUid = stat.st_uid;
5407                } catch (ErrnoException e) {
5408                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5409                }
5410
5411                // If we have mismatched owners for the data path, we have a problem.
5412                if (currentUid != pkg.applicationInfo.uid) {
5413                    boolean recovered = false;
5414                    if (currentUid == 0) {
5415                        // The directory somehow became owned by root.  Wow.
5416                        // This is probably because the system was stopped while
5417                        // installd was in the middle of messing with its libs
5418                        // directory.  Ask installd to fix that.
5419                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5420                                pkg.applicationInfo.uid);
5421                        if (ret >= 0) {
5422                            recovered = true;
5423                            String msg = "Package " + pkg.packageName
5424                                    + " unexpectedly changed to uid 0; recovered to " +
5425                                    + pkg.applicationInfo.uid;
5426                            reportSettingsProblem(Log.WARN, msg);
5427                        }
5428                    }
5429                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5430                            || (scanFlags&SCAN_BOOTING) != 0)) {
5431                        // If this is a system app, we can at least delete its
5432                        // current data so the application will still work.
5433                        int ret = removeDataDirsLI(pkgName);
5434                        if (ret >= 0) {
5435                            // TODO: Kill the processes first
5436                            // Old data gone!
5437                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5438                                    ? "System package " : "Third party package ";
5439                            String msg = prefix + pkg.packageName
5440                                    + " has changed from uid: "
5441                                    + currentUid + " to "
5442                                    + pkg.applicationInfo.uid + "; old data erased";
5443                            reportSettingsProblem(Log.WARN, msg);
5444                            recovered = true;
5445
5446                            // And now re-install the app.
5447                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5448                                                   pkg.applicationInfo.seinfo);
5449                            if (ret == -1) {
5450                                // Ack should not happen!
5451                                msg = prefix + pkg.packageName
5452                                        + " could not have data directory re-created after delete.";
5453                                reportSettingsProblem(Log.WARN, msg);
5454                                throw new PackageManagerException(
5455                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5456                            }
5457                        }
5458                        if (!recovered) {
5459                            mHasSystemUidErrors = true;
5460                        }
5461                    } else if (!recovered) {
5462                        // If we allow this install to proceed, we will be broken.
5463                        // Abort, abort!
5464                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5465                                "scanPackageLI");
5466                    }
5467                    if (!recovered) {
5468                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5469                            + pkg.applicationInfo.uid + "/fs_"
5470                            + currentUid;
5471                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5472                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5473                        String msg = "Package " + pkg.packageName
5474                                + " has mismatched uid: "
5475                                + currentUid + " on disk, "
5476                                + pkg.applicationInfo.uid + " in settings";
5477                        // writer
5478                        synchronized (mPackages) {
5479                            mSettings.mReadMessages.append(msg);
5480                            mSettings.mReadMessages.append('\n');
5481                            uidError = true;
5482                            if (!pkgSetting.uidError) {
5483                                reportSettingsProblem(Log.ERROR, msg);
5484                            }
5485                        }
5486                    }
5487                }
5488                pkg.applicationInfo.dataDir = dataPath.getPath();
5489                if (mShouldRestoreconData) {
5490                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5491                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5492                                pkg.applicationInfo.uid);
5493                }
5494            } else {
5495                if (DEBUG_PACKAGE_SCANNING) {
5496                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5497                        Log.v(TAG, "Want this data dir: " + dataPath);
5498                }
5499                //invoke installer to do the actual installation
5500                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5501                                           pkg.applicationInfo.seinfo);
5502                if (ret < 0) {
5503                    // Error from installer
5504                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5505                            "Unable to create data dirs [errorCode=" + ret + "]");
5506                }
5507
5508                if (dataPath.exists()) {
5509                    pkg.applicationInfo.dataDir = dataPath.getPath();
5510                } else {
5511                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5512                    pkg.applicationInfo.dataDir = null;
5513                }
5514            }
5515
5516            pkgSetting.uidError = uidError;
5517        }
5518
5519        final String path = scanFile.getPath();
5520        final String codePath = pkg.applicationInfo.getCodePath();
5521        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5522        if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5523            setBundledAppAbisAndRoots(pkg, pkgSetting);
5524
5525            // If we haven't found any native libraries for the app, check if it has
5526            // renderscript code. We'll need to force the app to 32 bit if it has
5527            // renderscript bitcode.
5528            if (pkg.applicationInfo.primaryCpuAbi == null
5529                    && pkg.applicationInfo.secondaryCpuAbi == null
5530                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5531                NativeLibraryHelper.Handle handle = null;
5532                try {
5533                    handle = NativeLibraryHelper.Handle.create(scanFile);
5534                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5535                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5536                    }
5537                } catch (IOException ioe) {
5538                    Slog.w(TAG, "Error scanning system app : " + ioe);
5539                } finally {
5540                    IoUtils.closeQuietly(handle);
5541                }
5542            }
5543
5544            setNativeLibraryPaths(pkg);
5545        } else {
5546            // TODO: We can probably be smarter about this stuff. For installed apps,
5547            // we can calculate this information at install time once and for all. For
5548            // system apps, we can probably assume that this information doesn't change
5549            // after the first boot scan. As things stand, we do lots of unnecessary work.
5550
5551            // Give ourselves some initial paths; we'll come back for another
5552            // pass once we've determined ABI below.
5553            setNativeLibraryPaths(pkg);
5554
5555            final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg);
5556            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5557            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5558
5559            NativeLibraryHelper.Handle handle = null;
5560            try {
5561                handle = NativeLibraryHelper.Handle.create(scanFile);
5562                // TODO(multiArch): This can be null for apps that didn't go through the
5563                // usual installation process. We can calculate it again, like we
5564                // do during install time.
5565                //
5566                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5567                // unnecessary.
5568                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5569
5570                // Null out the abis so that they can be recalculated.
5571                pkg.applicationInfo.primaryCpuAbi = null;
5572                pkg.applicationInfo.secondaryCpuAbi = null;
5573                if (isMultiArch(pkg.applicationInfo)) {
5574                    // Warn if we've set an abiOverride for multi-lib packages..
5575                    // By definition, we need to copy both 32 and 64 bit libraries for
5576                    // such packages.
5577                    if (pkg.cpuAbiOverride != null
5578                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5579                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5580                    }
5581
5582                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5583                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5584                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5585                        if (isAsec) {
5586                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5587                        } else {
5588                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5589                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5590                                    useIsaSpecificSubdirs);
5591                        }
5592                    }
5593
5594                    maybeThrowExceptionForMultiArchCopy(
5595                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5596
5597                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5598                        if (isAsec) {
5599                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5600                        } else {
5601                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5602                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5603                                    useIsaSpecificSubdirs);
5604                        }
5605                    }
5606
5607                    maybeThrowExceptionForMultiArchCopy(
5608                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5609
5610                    if (abi64 >= 0) {
5611                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5612                    }
5613
5614                    if (abi32 >= 0) {
5615                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5616                        if (abi64 >= 0) {
5617                            pkg.applicationInfo.secondaryCpuAbi = abi;
5618                        } else {
5619                            pkg.applicationInfo.primaryCpuAbi = abi;
5620                        }
5621                    }
5622                } else {
5623                    String[] abiList = (cpuAbiOverride != null) ?
5624                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5625
5626                    // Enable gross and lame hacks for apps that are built with old
5627                    // SDK tools. We must scan their APKs for renderscript bitcode and
5628                    // not launch them if it's present. Don't bother checking on devices
5629                    // that don't have 64 bit support.
5630                    boolean needsRenderScriptOverride = false;
5631                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5632                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5633                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5634                        needsRenderScriptOverride = true;
5635                    }
5636
5637                    final int copyRet;
5638                    if (isAsec) {
5639                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5640                    } else {
5641                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5642                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5643                    }
5644
5645                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5646                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5647                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5648                    }
5649
5650                    if (copyRet >= 0) {
5651                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5652                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5653                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5654                    } else if (needsRenderScriptOverride) {
5655                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5656                    }
5657                }
5658            } catch (IOException ioe) {
5659                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5660            } finally {
5661                IoUtils.closeQuietly(handle);
5662            }
5663
5664            // Now that we've calculated the ABIs and determined if it's an internal app,
5665            // we will go ahead and populate the nativeLibraryPath.
5666            setNativeLibraryPaths(pkg);
5667
5668            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5669            final int[] userIds = sUserManager.getUserIds();
5670            synchronized (mInstallLock) {
5671                // Create a native library symlink only if we have native libraries
5672                // and if the native libraries are 32 bit libraries. We do not provide
5673                // this symlink for 64 bit libraries.
5674                if (pkg.applicationInfo.primaryCpuAbi != null &&
5675                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5676                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5677                    for (int userId : userIds) {
5678                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5679                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5680                                    "Failed linking native library dir (user=" + userId + ")");
5681                        }
5682                    }
5683                }
5684            }
5685        }
5686
5687        // This is a special case for the "system" package, where the ABI is
5688        // dictated by the zygote configuration (and init.rc). We should keep track
5689        // of this ABI so that we can deal with "normal" applications that run under
5690        // the same UID correctly.
5691        if (mPlatformPackage == pkg) {
5692            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5693                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5694        }
5695
5696        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5697        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5698        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5699        // Copy the derived override back to the parsed package, so that we can
5700        // update the package settings accordingly.
5701        pkg.cpuAbiOverride = cpuAbiOverride;
5702
5703        if (DEBUG_ABI_SELECTION) {
5704            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5705                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5706                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5707        }
5708
5709        // Push the derived path down into PackageSettings so we know what to
5710        // clean up at uninstall time.
5711        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5712
5713        if (DEBUG_ABI_SELECTION) {
5714            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5715                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5716                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5717        }
5718
5719        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5720            // We don't do this here during boot because we can do it all
5721            // at once after scanning all existing packages.
5722            //
5723            // We also do this *before* we perform dexopt on this package, so that
5724            // we can avoid redundant dexopts, and also to make sure we've got the
5725            // code and package path correct.
5726            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5727                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5728        }
5729
5730        if ((scanFlags & SCAN_NO_DEX) == 0) {
5731            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
5732                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
5733            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
5734                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5735            }
5736        }
5737        if (mFactoryTest && pkg.requestedPermissions.contains(
5738                android.Manifest.permission.FACTORY_TEST)) {
5739            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5740        }
5741
5742        ArrayList<PackageParser.Package> clientLibPkgs = null;
5743
5744        // writer
5745        synchronized (mPackages) {
5746            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5747                // Only system apps can add new shared libraries.
5748                if (pkg.libraryNames != null) {
5749                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5750                        String name = pkg.libraryNames.get(i);
5751                        boolean allowed = false;
5752                        if (pkg.isUpdatedSystemApp()) {
5753                            // New library entries can only be added through the
5754                            // system image.  This is important to get rid of a lot
5755                            // of nasty edge cases: for example if we allowed a non-
5756                            // system update of the app to add a library, then uninstalling
5757                            // the update would make the library go away, and assumptions
5758                            // we made such as through app install filtering would now
5759                            // have allowed apps on the device which aren't compatible
5760                            // with it.  Better to just have the restriction here, be
5761                            // conservative, and create many fewer cases that can negatively
5762                            // impact the user experience.
5763                            final PackageSetting sysPs = mSettings
5764                                    .getDisabledSystemPkgLPr(pkg.packageName);
5765                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5766                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5767                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5768                                        allowed = true;
5769                                        allowed = true;
5770                                        break;
5771                                    }
5772                                }
5773                            }
5774                        } else {
5775                            allowed = true;
5776                        }
5777                        if (allowed) {
5778                            if (!mSharedLibraries.containsKey(name)) {
5779                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5780                            } else if (!name.equals(pkg.packageName)) {
5781                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5782                                        + name + " already exists; skipping");
5783                            }
5784                        } else {
5785                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5786                                    + name + " that is not declared on system image; skipping");
5787                        }
5788                    }
5789                    if ((scanFlags&SCAN_BOOTING) == 0) {
5790                        // If we are not booting, we need to update any applications
5791                        // that are clients of our shared library.  If we are booting,
5792                        // this will all be done once the scan is complete.
5793                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5794                    }
5795                }
5796            }
5797        }
5798
5799        // We also need to dexopt any apps that are dependent on this library.  Note that
5800        // if these fail, we should abort the install since installing the library will
5801        // result in some apps being broken.
5802        if (clientLibPkgs != null) {
5803            if ((scanFlags & SCAN_NO_DEX) == 0) {
5804                for (int i = 0; i < clientLibPkgs.size(); i++) {
5805                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5806                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
5807                            null /* instruction sets */, forceDex,
5808                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
5809                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
5810                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5811                                "scanPackageLI failed to dexopt clientLibPkgs");
5812                    }
5813                }
5814            }
5815        }
5816
5817        // Request the ActivityManager to kill the process(only for existing packages)
5818        // so that we do not end up in a confused state while the user is still using the older
5819        // version of the application while the new one gets installed.
5820        if ((scanFlags & SCAN_REPLACING) != 0) {
5821            killApplication(pkg.applicationInfo.packageName,
5822                        pkg.applicationInfo.uid, "update pkg");
5823        }
5824
5825        // Also need to kill any apps that are dependent on the library.
5826        if (clientLibPkgs != null) {
5827            for (int i=0; i<clientLibPkgs.size(); i++) {
5828                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5829                killApplication(clientPkg.applicationInfo.packageName,
5830                        clientPkg.applicationInfo.uid, "update lib");
5831            }
5832        }
5833
5834        // writer
5835        synchronized (mPackages) {
5836            // We don't expect installation to fail beyond this point
5837
5838            // Add the new setting to mSettings
5839            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5840            // Add the new setting to mPackages
5841            mPackages.put(pkg.applicationInfo.packageName, pkg);
5842            // Make sure we don't accidentally delete its data.
5843            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5844            while (iter.hasNext()) {
5845                PackageCleanItem item = iter.next();
5846                if (pkgName.equals(item.packageName)) {
5847                    iter.remove();
5848                }
5849            }
5850
5851            // Take care of first install / last update times.
5852            if (currentTime != 0) {
5853                if (pkgSetting.firstInstallTime == 0) {
5854                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5855                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5856                    pkgSetting.lastUpdateTime = currentTime;
5857                }
5858            } else if (pkgSetting.firstInstallTime == 0) {
5859                // We need *something*.  Take time time stamp of the file.
5860                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5861            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5862                if (scanFileTime != pkgSetting.timeStamp) {
5863                    // A package on the system image has changed; consider this
5864                    // to be an update.
5865                    pkgSetting.lastUpdateTime = scanFileTime;
5866                }
5867            }
5868
5869            // Add the package's KeySets to the global KeySetManagerService
5870            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5871            try {
5872                // Old KeySetData no longer valid.
5873                ksms.removeAppKeySetDataLPw(pkg.packageName);
5874                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5875                if (pkg.mKeySetMapping != null) {
5876                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5877                            pkg.mKeySetMapping.entrySet()) {
5878                        if (entry.getValue() != null) {
5879                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5880                                                          entry.getValue(), entry.getKey());
5881                        }
5882                    }
5883                    if (pkg.mUpgradeKeySets != null) {
5884                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5885                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5886                        }
5887                    }
5888                }
5889            } catch (NullPointerException e) {
5890                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5891            } catch (IllegalArgumentException e) {
5892                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5893            }
5894
5895            int N = pkg.providers.size();
5896            StringBuilder r = null;
5897            int i;
5898            for (i=0; i<N; i++) {
5899                PackageParser.Provider p = pkg.providers.get(i);
5900                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5901                        p.info.processName, pkg.applicationInfo.uid);
5902                mProviders.addProvider(p);
5903                p.syncable = p.info.isSyncable;
5904                if (p.info.authority != null) {
5905                    String names[] = p.info.authority.split(";");
5906                    p.info.authority = null;
5907                    for (int j = 0; j < names.length; j++) {
5908                        if (j == 1 && p.syncable) {
5909                            // We only want the first authority for a provider to possibly be
5910                            // syncable, so if we already added this provider using a different
5911                            // authority clear the syncable flag. We copy the provider before
5912                            // changing it because the mProviders object contains a reference
5913                            // to a provider that we don't want to change.
5914                            // Only do this for the second authority since the resulting provider
5915                            // object can be the same for all future authorities for this provider.
5916                            p = new PackageParser.Provider(p);
5917                            p.syncable = false;
5918                        }
5919                        if (!mProvidersByAuthority.containsKey(names[j])) {
5920                            mProvidersByAuthority.put(names[j], p);
5921                            if (p.info.authority == null) {
5922                                p.info.authority = names[j];
5923                            } else {
5924                                p.info.authority = p.info.authority + ";" + names[j];
5925                            }
5926                            if (DEBUG_PACKAGE_SCANNING) {
5927                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5928                                    Log.d(TAG, "Registered content provider: " + names[j]
5929                                            + ", className = " + p.info.name + ", isSyncable = "
5930                                            + p.info.isSyncable);
5931                            }
5932                        } else {
5933                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5934                            Slog.w(TAG, "Skipping provider name " + names[j] +
5935                                    " (in package " + pkg.applicationInfo.packageName +
5936                                    "): name already used by "
5937                                    + ((other != null && other.getComponentName() != null)
5938                                            ? other.getComponentName().getPackageName() : "?"));
5939                        }
5940                    }
5941                }
5942                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5943                    if (r == null) {
5944                        r = new StringBuilder(256);
5945                    } else {
5946                        r.append(' ');
5947                    }
5948                    r.append(p.info.name);
5949                }
5950            }
5951            if (r != null) {
5952                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5953            }
5954
5955            N = pkg.services.size();
5956            r = null;
5957            for (i=0; i<N; i++) {
5958                PackageParser.Service s = pkg.services.get(i);
5959                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5960                        s.info.processName, pkg.applicationInfo.uid);
5961                mServices.addService(s);
5962                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5963                    if (r == null) {
5964                        r = new StringBuilder(256);
5965                    } else {
5966                        r.append(' ');
5967                    }
5968                    r.append(s.info.name);
5969                }
5970            }
5971            if (r != null) {
5972                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5973            }
5974
5975            N = pkg.receivers.size();
5976            r = null;
5977            for (i=0; i<N; i++) {
5978                PackageParser.Activity a = pkg.receivers.get(i);
5979                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5980                        a.info.processName, pkg.applicationInfo.uid);
5981                mReceivers.addActivity(a, "receiver");
5982                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5983                    if (r == null) {
5984                        r = new StringBuilder(256);
5985                    } else {
5986                        r.append(' ');
5987                    }
5988                    r.append(a.info.name);
5989                }
5990            }
5991            if (r != null) {
5992                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5993            }
5994
5995            N = pkg.activities.size();
5996            r = null;
5997            for (i=0; i<N; i++) {
5998                PackageParser.Activity a = pkg.activities.get(i);
5999                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6000                        a.info.processName, pkg.applicationInfo.uid);
6001                mActivities.addActivity(a, "activity");
6002                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6003                    if (r == null) {
6004                        r = new StringBuilder(256);
6005                    } else {
6006                        r.append(' ');
6007                    }
6008                    r.append(a.info.name);
6009                }
6010            }
6011            if (r != null) {
6012                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6013            }
6014
6015            N = pkg.permissionGroups.size();
6016            r = null;
6017            for (i=0; i<N; i++) {
6018                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6019                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6020                if (cur == null) {
6021                    mPermissionGroups.put(pg.info.name, pg);
6022                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6023                        if (r == null) {
6024                            r = new StringBuilder(256);
6025                        } else {
6026                            r.append(' ');
6027                        }
6028                        r.append(pg.info.name);
6029                    }
6030                } else {
6031                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6032                            + pg.info.packageName + " ignored: original from "
6033                            + cur.info.packageName);
6034                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6035                        if (r == null) {
6036                            r = new StringBuilder(256);
6037                        } else {
6038                            r.append(' ');
6039                        }
6040                        r.append("DUP:");
6041                        r.append(pg.info.name);
6042                    }
6043                }
6044            }
6045            if (r != null) {
6046                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6047            }
6048
6049            N = pkg.permissions.size();
6050            r = null;
6051            for (i=0; i<N; i++) {
6052                PackageParser.Permission p = pkg.permissions.get(i);
6053                ArrayMap<String, BasePermission> permissionMap =
6054                        p.tree ? mSettings.mPermissionTrees
6055                        : mSettings.mPermissions;
6056                p.group = mPermissionGroups.get(p.info.group);
6057                if (p.info.group == null || p.group != null) {
6058                    BasePermission bp = permissionMap.get(p.info.name);
6059
6060                    // Allow system apps to redefine non-system permissions
6061                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6062                        final boolean currentOwnerIsSystem = (bp.perm != null
6063                                && isSystemApp(bp.perm.owner));
6064                        if (isSystemApp(p.owner)) {
6065                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6066                                // It's a built-in permission and no owner, take ownership now
6067                                bp.packageSetting = pkgSetting;
6068                                bp.perm = p;
6069                                bp.uid = pkg.applicationInfo.uid;
6070                                bp.sourcePackage = p.info.packageName;
6071                            } else if (!currentOwnerIsSystem) {
6072                                String msg = "New decl " + p.owner + " of permission  "
6073                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6074                                reportSettingsProblem(Log.WARN, msg);
6075                                bp = null;
6076                            }
6077                        }
6078                    }
6079
6080                    if (bp == null) {
6081                        bp = new BasePermission(p.info.name, p.info.packageName,
6082                                BasePermission.TYPE_NORMAL);
6083                        permissionMap.put(p.info.name, bp);
6084                    }
6085
6086                    if (bp.perm == null) {
6087                        if (bp.sourcePackage == null
6088                                || bp.sourcePackage.equals(p.info.packageName)) {
6089                            BasePermission tree = findPermissionTreeLP(p.info.name);
6090                            if (tree == null
6091                                    || tree.sourcePackage.equals(p.info.packageName)) {
6092                                bp.packageSetting = pkgSetting;
6093                                bp.perm = p;
6094                                bp.uid = pkg.applicationInfo.uid;
6095                                bp.sourcePackage = p.info.packageName;
6096                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6097                                    if (r == null) {
6098                                        r = new StringBuilder(256);
6099                                    } else {
6100                                        r.append(' ');
6101                                    }
6102                                    r.append(p.info.name);
6103                                }
6104                            } else {
6105                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6106                                        + p.info.packageName + " ignored: base tree "
6107                                        + tree.name + " is from package "
6108                                        + tree.sourcePackage);
6109                            }
6110                        } else {
6111                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6112                                    + p.info.packageName + " ignored: original from "
6113                                    + bp.sourcePackage);
6114                        }
6115                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6116                        if (r == null) {
6117                            r = new StringBuilder(256);
6118                        } else {
6119                            r.append(' ');
6120                        }
6121                        r.append("DUP:");
6122                        r.append(p.info.name);
6123                    }
6124                    if (bp.perm == p) {
6125                        bp.protectionLevel = p.info.protectionLevel;
6126                    }
6127                } else {
6128                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6129                            + p.info.packageName + " ignored: no group "
6130                            + p.group);
6131                }
6132            }
6133            if (r != null) {
6134                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6135            }
6136
6137            N = pkg.instrumentation.size();
6138            r = null;
6139            for (i=0; i<N; i++) {
6140                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6141                a.info.packageName = pkg.applicationInfo.packageName;
6142                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6143                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6144                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6145                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6146                a.info.dataDir = pkg.applicationInfo.dataDir;
6147
6148                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6149                // need other information about the application, like the ABI and what not ?
6150                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6151                mInstrumentation.put(a.getComponentName(), a);
6152                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6153                    if (r == null) {
6154                        r = new StringBuilder(256);
6155                    } else {
6156                        r.append(' ');
6157                    }
6158                    r.append(a.info.name);
6159                }
6160            }
6161            if (r != null) {
6162                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6163            }
6164
6165            if (pkg.protectedBroadcasts != null) {
6166                N = pkg.protectedBroadcasts.size();
6167                for (i=0; i<N; i++) {
6168                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6169                }
6170            }
6171
6172            pkgSetting.setTimeStamp(scanFileTime);
6173
6174            // Create idmap files for pairs of (packages, overlay packages).
6175            // Note: "android", ie framework-res.apk, is handled by native layers.
6176            if (pkg.mOverlayTarget != null) {
6177                // This is an overlay package.
6178                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6179                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6180                        mOverlays.put(pkg.mOverlayTarget,
6181                                new ArrayMap<String, PackageParser.Package>());
6182                    }
6183                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6184                    map.put(pkg.packageName, pkg);
6185                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6186                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6187                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6188                                "scanPackageLI failed to createIdmap");
6189                    }
6190                }
6191            } else if (mOverlays.containsKey(pkg.packageName) &&
6192                    !pkg.packageName.equals("android")) {
6193                // This is a regular package, with one or more known overlay packages.
6194                createIdmapsForPackageLI(pkg);
6195            }
6196        }
6197
6198        return pkg;
6199    }
6200
6201    /**
6202     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6203     * i.e, so that all packages can be run inside a single process if required.
6204     *
6205     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6206     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6207     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6208     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6209     * updating a package that belongs to a shared user.
6210     *
6211     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6212     * adds unnecessary complexity.
6213     */
6214    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6215            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6216        String requiredInstructionSet = null;
6217        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6218            requiredInstructionSet = VMRuntime.getInstructionSet(
6219                     scannedPackage.applicationInfo.primaryCpuAbi);
6220        }
6221
6222        PackageSetting requirer = null;
6223        for (PackageSetting ps : packagesForUser) {
6224            // If packagesForUser contains scannedPackage, we skip it. This will happen
6225            // when scannedPackage is an update of an existing package. Without this check,
6226            // we will never be able to change the ABI of any package belonging to a shared
6227            // user, even if it's compatible with other packages.
6228            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6229                if (ps.primaryCpuAbiString == null) {
6230                    continue;
6231                }
6232
6233                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6234                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6235                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6236                    // this but there's not much we can do.
6237                    String errorMessage = "Instruction set mismatch, "
6238                            + ((requirer == null) ? "[caller]" : requirer)
6239                            + " requires " + requiredInstructionSet + " whereas " + ps
6240                            + " requires " + instructionSet;
6241                    Slog.w(TAG, errorMessage);
6242                }
6243
6244                if (requiredInstructionSet == null) {
6245                    requiredInstructionSet = instructionSet;
6246                    requirer = ps;
6247                }
6248            }
6249        }
6250
6251        if (requiredInstructionSet != null) {
6252            String adjustedAbi;
6253            if (requirer != null) {
6254                // requirer != null implies that either scannedPackage was null or that scannedPackage
6255                // did not require an ABI, in which case we have to adjust scannedPackage to match
6256                // the ABI of the set (which is the same as requirer's ABI)
6257                adjustedAbi = requirer.primaryCpuAbiString;
6258                if (scannedPackage != null) {
6259                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6260                }
6261            } else {
6262                // requirer == null implies that we're updating all ABIs in the set to
6263                // match scannedPackage.
6264                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6265            }
6266
6267            for (PackageSetting ps : packagesForUser) {
6268                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6269                    if (ps.primaryCpuAbiString != null) {
6270                        continue;
6271                    }
6272
6273                    ps.primaryCpuAbiString = adjustedAbi;
6274                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6275                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6276                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6277
6278                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
6279                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
6280                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6281                            ps.primaryCpuAbiString = null;
6282                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6283                            return;
6284                        } else {
6285                            mInstaller.rmdex(ps.codePathString,
6286                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
6287                        }
6288                    }
6289                }
6290            }
6291        }
6292    }
6293
6294    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6295        synchronized (mPackages) {
6296            mResolverReplaced = true;
6297            // Set up information for custom user intent resolution activity.
6298            mResolveActivity.applicationInfo = pkg.applicationInfo;
6299            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6300            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6301            mResolveActivity.processName = pkg.applicationInfo.packageName;
6302            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6303            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6304                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6305            mResolveActivity.theme = 0;
6306            mResolveActivity.exported = true;
6307            mResolveActivity.enabled = true;
6308            mResolveInfo.activityInfo = mResolveActivity;
6309            mResolveInfo.priority = 0;
6310            mResolveInfo.preferredOrder = 0;
6311            mResolveInfo.match = 0;
6312            mResolveComponentName = mCustomResolverComponentName;
6313            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6314                    mResolveComponentName);
6315        }
6316    }
6317
6318    private static String calculateBundledApkRoot(final String codePathString) {
6319        final File codePath = new File(codePathString);
6320        final File codeRoot;
6321        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6322            codeRoot = Environment.getRootDirectory();
6323        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6324            codeRoot = Environment.getOemDirectory();
6325        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6326            codeRoot = Environment.getVendorDirectory();
6327        } else {
6328            // Unrecognized code path; take its top real segment as the apk root:
6329            // e.g. /something/app/blah.apk => /something
6330            try {
6331                File f = codePath.getCanonicalFile();
6332                File parent = f.getParentFile();    // non-null because codePath is a file
6333                File tmp;
6334                while ((tmp = parent.getParentFile()) != null) {
6335                    f = parent;
6336                    parent = tmp;
6337                }
6338                codeRoot = f;
6339                Slog.w(TAG, "Unrecognized code path "
6340                        + codePath + " - using " + codeRoot);
6341            } catch (IOException e) {
6342                // Can't canonicalize the code path -- shenanigans?
6343                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6344                return Environment.getRootDirectory().getPath();
6345            }
6346        }
6347        return codeRoot.getPath();
6348    }
6349
6350    /**
6351     * Derive and set the location of native libraries for the given package,
6352     * which varies depending on where and how the package was installed.
6353     */
6354    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6355        final ApplicationInfo info = pkg.applicationInfo;
6356        final String codePath = pkg.codePath;
6357        final File codeFile = new File(codePath);
6358        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
6359        final boolean asecApp = info.isForwardLocked() || isExternal(info);
6360
6361        info.nativeLibraryRootDir = null;
6362        info.nativeLibraryRootRequiresIsa = false;
6363        info.nativeLibraryDir = null;
6364        info.secondaryNativeLibraryDir = null;
6365
6366        if (isApkFile(codeFile)) {
6367            // Monolithic install
6368            if (bundledApp) {
6369                // If "/system/lib64/apkname" exists, assume that is the per-package
6370                // native library directory to use; otherwise use "/system/lib/apkname".
6371                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6372                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6373                        getPrimaryInstructionSet(info));
6374
6375                // This is a bundled system app so choose the path based on the ABI.
6376                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6377                // is just the default path.
6378                final String apkName = deriveCodePathName(codePath);
6379                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6380                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6381                        apkName).getAbsolutePath();
6382
6383                if (info.secondaryCpuAbi != null) {
6384                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6385                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6386                            secondaryLibDir, apkName).getAbsolutePath();
6387                }
6388            } else if (asecApp) {
6389                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6390                        .getAbsolutePath();
6391            } else {
6392                final String apkName = deriveCodePathName(codePath);
6393                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6394                        .getAbsolutePath();
6395            }
6396
6397            info.nativeLibraryRootRequiresIsa = false;
6398            info.nativeLibraryDir = info.nativeLibraryRootDir;
6399        } else {
6400            // Cluster install
6401            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6402            info.nativeLibraryRootRequiresIsa = true;
6403
6404            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6405                    getPrimaryInstructionSet(info)).getAbsolutePath();
6406
6407            if (info.secondaryCpuAbi != null) {
6408                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6409                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6410            }
6411        }
6412    }
6413
6414    /**
6415     * Calculate the abis and roots for a bundled app. These can uniquely
6416     * be determined from the contents of the system partition, i.e whether
6417     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6418     * of this information, and instead assume that the system was built
6419     * sensibly.
6420     */
6421    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6422                                           PackageSetting pkgSetting) {
6423        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6424
6425        // If "/system/lib64/apkname" exists, assume that is the per-package
6426        // native library directory to use; otherwise use "/system/lib/apkname".
6427        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6428        setBundledAppAbi(pkg, apkRoot, apkName);
6429        // pkgSetting might be null during rescan following uninstall of updates
6430        // to a bundled app, so accommodate that possibility.  The settings in
6431        // that case will be established later from the parsed package.
6432        //
6433        // If the settings aren't null, sync them up with what we've just derived.
6434        // note that apkRoot isn't stored in the package settings.
6435        if (pkgSetting != null) {
6436            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6437            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6438        }
6439    }
6440
6441    /**
6442     * Deduces the ABI of a bundled app and sets the relevant fields on the
6443     * parsed pkg object.
6444     *
6445     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6446     *        under which system libraries are installed.
6447     * @param apkName the name of the installed package.
6448     */
6449    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6450        final File codeFile = new File(pkg.codePath);
6451
6452        final boolean has64BitLibs;
6453        final boolean has32BitLibs;
6454        if (isApkFile(codeFile)) {
6455            // Monolithic install
6456            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6457            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6458        } else {
6459            // Cluster install
6460            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6461            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6462                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6463                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6464                has64BitLibs = (new File(rootDir, isa)).exists();
6465            } else {
6466                has64BitLibs = false;
6467            }
6468            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6469                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6470                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6471                has32BitLibs = (new File(rootDir, isa)).exists();
6472            } else {
6473                has32BitLibs = false;
6474            }
6475        }
6476
6477        if (has64BitLibs && !has32BitLibs) {
6478            // The package has 64 bit libs, but not 32 bit libs. Its primary
6479            // ABI should be 64 bit. We can safely assume here that the bundled
6480            // native libraries correspond to the most preferred ABI in the list.
6481
6482            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6483            pkg.applicationInfo.secondaryCpuAbi = null;
6484        } else if (has32BitLibs && !has64BitLibs) {
6485            // The package has 32 bit libs but not 64 bit libs. Its primary
6486            // ABI should be 32 bit.
6487
6488            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6489            pkg.applicationInfo.secondaryCpuAbi = null;
6490        } else if (has32BitLibs && has64BitLibs) {
6491            // The application has both 64 and 32 bit bundled libraries. We check
6492            // here that the app declares multiArch support, and warn if it doesn't.
6493            //
6494            // We will be lenient here and record both ABIs. The primary will be the
6495            // ABI that's higher on the list, i.e, a device that's configured to prefer
6496            // 64 bit apps will see a 64 bit primary ABI,
6497
6498            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6499                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6500            }
6501
6502            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6503                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6504                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6505            } else {
6506                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6507                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6508            }
6509        } else {
6510            pkg.applicationInfo.primaryCpuAbi = null;
6511            pkg.applicationInfo.secondaryCpuAbi = null;
6512        }
6513    }
6514
6515    private void killApplication(String pkgName, int appId, String reason) {
6516        // Request the ActivityManager to kill the process(only for existing packages)
6517        // so that we do not end up in a confused state while the user is still using the older
6518        // version of the application while the new one gets installed.
6519        IActivityManager am = ActivityManagerNative.getDefault();
6520        if (am != null) {
6521            try {
6522                am.killApplicationWithAppId(pkgName, appId, reason);
6523            } catch (RemoteException e) {
6524            }
6525        }
6526    }
6527
6528    void removePackageLI(PackageSetting ps, boolean chatty) {
6529        if (DEBUG_INSTALL) {
6530            if (chatty)
6531                Log.d(TAG, "Removing package " + ps.name);
6532        }
6533
6534        // writer
6535        synchronized (mPackages) {
6536            mPackages.remove(ps.name);
6537            final PackageParser.Package pkg = ps.pkg;
6538            if (pkg != null) {
6539                cleanPackageDataStructuresLILPw(pkg, chatty);
6540            }
6541        }
6542    }
6543
6544    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6545        if (DEBUG_INSTALL) {
6546            if (chatty)
6547                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6548        }
6549
6550        // writer
6551        synchronized (mPackages) {
6552            mPackages.remove(pkg.applicationInfo.packageName);
6553            cleanPackageDataStructuresLILPw(pkg, chatty);
6554        }
6555    }
6556
6557    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6558        int N = pkg.providers.size();
6559        StringBuilder r = null;
6560        int i;
6561        for (i=0; i<N; i++) {
6562            PackageParser.Provider p = pkg.providers.get(i);
6563            mProviders.removeProvider(p);
6564            if (p.info.authority == null) {
6565
6566                /* There was another ContentProvider with this authority when
6567                 * this app was installed so this authority is null,
6568                 * Ignore it as we don't have to unregister the provider.
6569                 */
6570                continue;
6571            }
6572            String names[] = p.info.authority.split(";");
6573            for (int j = 0; j < names.length; j++) {
6574                if (mProvidersByAuthority.get(names[j]) == p) {
6575                    mProvidersByAuthority.remove(names[j]);
6576                    if (DEBUG_REMOVE) {
6577                        if (chatty)
6578                            Log.d(TAG, "Unregistered content provider: " + names[j]
6579                                    + ", className = " + p.info.name + ", isSyncable = "
6580                                    + p.info.isSyncable);
6581                    }
6582                }
6583            }
6584            if (DEBUG_REMOVE && chatty) {
6585                if (r == null) {
6586                    r = new StringBuilder(256);
6587                } else {
6588                    r.append(' ');
6589                }
6590                r.append(p.info.name);
6591            }
6592        }
6593        if (r != null) {
6594            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6595        }
6596
6597        N = pkg.services.size();
6598        r = null;
6599        for (i=0; i<N; i++) {
6600            PackageParser.Service s = pkg.services.get(i);
6601            mServices.removeService(s);
6602            if (chatty) {
6603                if (r == null) {
6604                    r = new StringBuilder(256);
6605                } else {
6606                    r.append(' ');
6607                }
6608                r.append(s.info.name);
6609            }
6610        }
6611        if (r != null) {
6612            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6613        }
6614
6615        N = pkg.receivers.size();
6616        r = null;
6617        for (i=0; i<N; i++) {
6618            PackageParser.Activity a = pkg.receivers.get(i);
6619            mReceivers.removeActivity(a, "receiver");
6620            if (DEBUG_REMOVE && chatty) {
6621                if (r == null) {
6622                    r = new StringBuilder(256);
6623                } else {
6624                    r.append(' ');
6625                }
6626                r.append(a.info.name);
6627            }
6628        }
6629        if (r != null) {
6630            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6631        }
6632
6633        N = pkg.activities.size();
6634        r = null;
6635        for (i=0; i<N; i++) {
6636            PackageParser.Activity a = pkg.activities.get(i);
6637            mActivities.removeActivity(a, "activity");
6638            if (DEBUG_REMOVE && chatty) {
6639                if (r == null) {
6640                    r = new StringBuilder(256);
6641                } else {
6642                    r.append(' ');
6643                }
6644                r.append(a.info.name);
6645            }
6646        }
6647        if (r != null) {
6648            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6649        }
6650
6651        N = pkg.permissions.size();
6652        r = null;
6653        for (i=0; i<N; i++) {
6654            PackageParser.Permission p = pkg.permissions.get(i);
6655            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6656            if (bp == null) {
6657                bp = mSettings.mPermissionTrees.get(p.info.name);
6658            }
6659            if (bp != null && bp.perm == p) {
6660                bp.perm = null;
6661                if (DEBUG_REMOVE && chatty) {
6662                    if (r == null) {
6663                        r = new StringBuilder(256);
6664                    } else {
6665                        r.append(' ');
6666                    }
6667                    r.append(p.info.name);
6668                }
6669            }
6670            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6671                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6672                if (appOpPerms != null) {
6673                    appOpPerms.remove(pkg.packageName);
6674                }
6675            }
6676        }
6677        if (r != null) {
6678            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6679        }
6680
6681        N = pkg.requestedPermissions.size();
6682        r = null;
6683        for (i=0; i<N; i++) {
6684            String perm = pkg.requestedPermissions.get(i);
6685            BasePermission bp = mSettings.mPermissions.get(perm);
6686            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6687                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6688                if (appOpPerms != null) {
6689                    appOpPerms.remove(pkg.packageName);
6690                    if (appOpPerms.isEmpty()) {
6691                        mAppOpPermissionPackages.remove(perm);
6692                    }
6693                }
6694            }
6695        }
6696        if (r != null) {
6697            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6698        }
6699
6700        N = pkg.instrumentation.size();
6701        r = null;
6702        for (i=0; i<N; i++) {
6703            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6704            mInstrumentation.remove(a.getComponentName());
6705            if (DEBUG_REMOVE && chatty) {
6706                if (r == null) {
6707                    r = new StringBuilder(256);
6708                } else {
6709                    r.append(' ');
6710                }
6711                r.append(a.info.name);
6712            }
6713        }
6714        if (r != null) {
6715            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6716        }
6717
6718        r = null;
6719        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6720            // Only system apps can hold shared libraries.
6721            if (pkg.libraryNames != null) {
6722                for (i=0; i<pkg.libraryNames.size(); i++) {
6723                    String name = pkg.libraryNames.get(i);
6724                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6725                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6726                        mSharedLibraries.remove(name);
6727                        if (DEBUG_REMOVE && chatty) {
6728                            if (r == null) {
6729                                r = new StringBuilder(256);
6730                            } else {
6731                                r.append(' ');
6732                            }
6733                            r.append(name);
6734                        }
6735                    }
6736                }
6737            }
6738        }
6739        if (r != null) {
6740            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6741        }
6742    }
6743
6744    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6745        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6746            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6747                return true;
6748            }
6749        }
6750        return false;
6751    }
6752
6753    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6754    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6755    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6756
6757    private void updatePermissionsLPw(String changingPkg,
6758            PackageParser.Package pkgInfo, int flags) {
6759        // Make sure there are no dangling permission trees.
6760        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6761        while (it.hasNext()) {
6762            final BasePermission bp = it.next();
6763            if (bp.packageSetting == null) {
6764                // We may not yet have parsed the package, so just see if
6765                // we still know about its settings.
6766                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6767            }
6768            if (bp.packageSetting == null) {
6769                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6770                        + " from package " + bp.sourcePackage);
6771                it.remove();
6772            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6773                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6774                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6775                            + " from package " + bp.sourcePackage);
6776                    flags |= UPDATE_PERMISSIONS_ALL;
6777                    it.remove();
6778                }
6779            }
6780        }
6781
6782        // Make sure all dynamic permissions have been assigned to a package,
6783        // and make sure there are no dangling permissions.
6784        it = mSettings.mPermissions.values().iterator();
6785        while (it.hasNext()) {
6786            final BasePermission bp = it.next();
6787            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6788                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6789                        + bp.name + " pkg=" + bp.sourcePackage
6790                        + " info=" + bp.pendingInfo);
6791                if (bp.packageSetting == null && bp.pendingInfo != null) {
6792                    final BasePermission tree = findPermissionTreeLP(bp.name);
6793                    if (tree != null && tree.perm != null) {
6794                        bp.packageSetting = tree.packageSetting;
6795                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6796                                new PermissionInfo(bp.pendingInfo));
6797                        bp.perm.info.packageName = tree.perm.info.packageName;
6798                        bp.perm.info.name = bp.name;
6799                        bp.uid = tree.uid;
6800                    }
6801                }
6802            }
6803            if (bp.packageSetting == null) {
6804                // We may not yet have parsed the package, so just see if
6805                // we still know about its settings.
6806                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6807            }
6808            if (bp.packageSetting == null) {
6809                Slog.w(TAG, "Removing dangling permission: " + bp.name
6810                        + " from package " + bp.sourcePackage);
6811                it.remove();
6812            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6813                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6814                    Slog.i(TAG, "Removing old permission: " + bp.name
6815                            + " from package " + bp.sourcePackage);
6816                    flags |= UPDATE_PERMISSIONS_ALL;
6817                    it.remove();
6818                }
6819            }
6820        }
6821
6822        // Now update the permissions for all packages, in particular
6823        // replace the granted permissions of the system packages.
6824        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6825            for (PackageParser.Package pkg : mPackages.values()) {
6826                if (pkg != pkgInfo) {
6827                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6828                            changingPkg);
6829                }
6830            }
6831        }
6832
6833        if (pkgInfo != null) {
6834            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6835        }
6836    }
6837
6838    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6839            String packageOfInterest) {
6840        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6841        if (ps == null) {
6842            return;
6843        }
6844        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6845        ArraySet<String> origPermissions = gp.grantedPermissions;
6846        boolean changedPermission = false;
6847
6848        if (replace) {
6849            ps.permissionsFixed = false;
6850            if (gp == ps) {
6851                origPermissions = new ArraySet<String>(gp.grantedPermissions);
6852                gp.grantedPermissions.clear();
6853                gp.gids = mGlobalGids;
6854            }
6855        }
6856
6857        if (gp.gids == null) {
6858            gp.gids = mGlobalGids;
6859        }
6860
6861        final int N = pkg.requestedPermissions.size();
6862        for (int i=0; i<N; i++) {
6863            final String name = pkg.requestedPermissions.get(i);
6864            final boolean required = pkg.requestedPermissionsRequired.get(i);
6865            final BasePermission bp = mSettings.mPermissions.get(name);
6866            if (DEBUG_INSTALL) {
6867                if (gp != ps) {
6868                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6869                }
6870            }
6871
6872            if (bp == null || bp.packageSetting == null) {
6873                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6874                    Slog.w(TAG, "Unknown permission " + name
6875                            + " in package " + pkg.packageName);
6876                }
6877                continue;
6878            }
6879
6880            final String perm = bp.name;
6881            boolean allowed;
6882            boolean allowedSig = false;
6883            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6884                // Keep track of app op permissions.
6885                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6886                if (pkgs == null) {
6887                    pkgs = new ArraySet<>();
6888                    mAppOpPermissionPackages.put(bp.name, pkgs);
6889                }
6890                pkgs.add(pkg.packageName);
6891            }
6892            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6893            if (level == PermissionInfo.PROTECTION_NORMAL
6894                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6895                // We grant a normal or dangerous permission if any of the following
6896                // are true:
6897                // 1) The permission is required
6898                // 2) The permission is optional, but was granted in the past
6899                // 3) The permission is optional, but was requested by an
6900                //    app in /system (not /data)
6901                //
6902                // Otherwise, reject the permission.
6903                allowed = (required || origPermissions.contains(perm)
6904                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6905            } else if (bp.packageSetting == null) {
6906                // This permission is invalid; skip it.
6907                allowed = false;
6908            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6909                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6910                if (allowed) {
6911                    allowedSig = true;
6912                }
6913            } else {
6914                allowed = false;
6915            }
6916            if (DEBUG_INSTALL) {
6917                if (gp != ps) {
6918                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6919                }
6920            }
6921            if (allowed) {
6922                if (!isSystemApp(ps) && ps.permissionsFixed) {
6923                    // If this is an existing, non-system package, then
6924                    // we can't add any new permissions to it.
6925                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6926                        // Except...  if this is a permission that was added
6927                        // to the platform (note: need to only do this when
6928                        // updating the platform).
6929                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6930                    }
6931                }
6932                if (allowed) {
6933                    if (!gp.grantedPermissions.contains(perm)) {
6934                        changedPermission = true;
6935                        gp.grantedPermissions.add(perm);
6936                        gp.gids = appendInts(gp.gids, bp.gids);
6937                    } else if (!ps.haveGids) {
6938                        gp.gids = appendInts(gp.gids, bp.gids);
6939                    }
6940                } else {
6941                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6942                        Slog.w(TAG, "Not granting permission " + perm
6943                                + " to package " + pkg.packageName
6944                                + " because it was previously installed without");
6945                    }
6946                }
6947            } else {
6948                if (gp.grantedPermissions.remove(perm)) {
6949                    changedPermission = true;
6950                    gp.gids = removeInts(gp.gids, bp.gids);
6951                    Slog.i(TAG, "Un-granting permission " + perm
6952                            + " from package " + pkg.packageName
6953                            + " (protectionLevel=" + bp.protectionLevel
6954                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6955                            + ")");
6956                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6957                    // Don't print warning for app op permissions, since it is fine for them
6958                    // not to be granted, there is a UI for the user to decide.
6959                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6960                        Slog.w(TAG, "Not granting permission " + perm
6961                                + " to package " + pkg.packageName
6962                                + " (protectionLevel=" + bp.protectionLevel
6963                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6964                                + ")");
6965                    }
6966                }
6967            }
6968        }
6969
6970        if ((changedPermission || replace) && !ps.permissionsFixed &&
6971                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6972            // This is the first that we have heard about this package, so the
6973            // permissions we have now selected are fixed until explicitly
6974            // changed.
6975            ps.permissionsFixed = true;
6976        }
6977        ps.haveGids = true;
6978    }
6979
6980    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6981        boolean allowed = false;
6982        final int NP = PackageParser.NEW_PERMISSIONS.length;
6983        for (int ip=0; ip<NP; ip++) {
6984            final PackageParser.NewPermissionInfo npi
6985                    = PackageParser.NEW_PERMISSIONS[ip];
6986            if (npi.name.equals(perm)
6987                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6988                allowed = true;
6989                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6990                        + pkg.packageName);
6991                break;
6992            }
6993        }
6994        return allowed;
6995    }
6996
6997    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6998                                          BasePermission bp, ArraySet<String> origPermissions) {
6999        boolean allowed;
7000        allowed = (compareSignatures(
7001                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7002                        == PackageManager.SIGNATURE_MATCH)
7003                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7004                        == PackageManager.SIGNATURE_MATCH);
7005        if (!allowed && (bp.protectionLevel
7006                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7007            if (isSystemApp(pkg)) {
7008                // For updated system applications, a system permission
7009                // is granted only if it had been defined by the original application.
7010                if (pkg.isUpdatedSystemApp()) {
7011                    final PackageSetting sysPs = mSettings
7012                            .getDisabledSystemPkgLPr(pkg.packageName);
7013                    final GrantedPermissions origGp = sysPs.sharedUser != null
7014                            ? sysPs.sharedUser : sysPs;
7015
7016                    if (origGp.grantedPermissions.contains(perm)) {
7017                        // If the original was granted this permission, we take
7018                        // that grant decision as read and propagate it to the
7019                        // update.
7020                        if (sysPs.isPrivileged()) {
7021                            allowed = true;
7022                        }
7023                    } else {
7024                        // The system apk may have been updated with an older
7025                        // version of the one on the data partition, but which
7026                        // granted a new system permission that it didn't have
7027                        // before.  In this case we do want to allow the app to
7028                        // now get the new permission if the ancestral apk is
7029                        // privileged to get it.
7030                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7031                            for (int j=0;
7032                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7033                                if (perm.equals(
7034                                        sysPs.pkg.requestedPermissions.get(j))) {
7035                                    allowed = true;
7036                                    break;
7037                                }
7038                            }
7039                        }
7040                    }
7041                } else {
7042                    allowed = isPrivilegedApp(pkg);
7043                }
7044            }
7045        }
7046        if (!allowed && (bp.protectionLevel
7047                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7048            // For development permissions, a development permission
7049            // is granted only if it was already granted.
7050            allowed = origPermissions.contains(perm);
7051        }
7052        return allowed;
7053    }
7054
7055    final class ActivityIntentResolver
7056            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7057        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7058                boolean defaultOnly, int userId) {
7059            if (!sUserManager.exists(userId)) return null;
7060            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7061            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7062        }
7063
7064        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7065                int userId) {
7066            if (!sUserManager.exists(userId)) return null;
7067            mFlags = flags;
7068            return super.queryIntent(intent, resolvedType,
7069                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7070        }
7071
7072        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7073                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7074            if (!sUserManager.exists(userId)) return null;
7075            if (packageActivities == null) {
7076                return null;
7077            }
7078            mFlags = flags;
7079            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7080            final int N = packageActivities.size();
7081            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7082                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7083
7084            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7085            for (int i = 0; i < N; ++i) {
7086                intentFilters = packageActivities.get(i).intents;
7087                if (intentFilters != null && intentFilters.size() > 0) {
7088                    PackageParser.ActivityIntentInfo[] array =
7089                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7090                    intentFilters.toArray(array);
7091                    listCut.add(array);
7092                }
7093            }
7094            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7095        }
7096
7097        public final void addActivity(PackageParser.Activity a, String type) {
7098            final boolean systemApp = a.info.applicationInfo.isSystemApp();
7099            mActivities.put(a.getComponentName(), a);
7100            if (DEBUG_SHOW_INFO)
7101                Log.v(
7102                TAG, "  " + type + " " +
7103                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7104            if (DEBUG_SHOW_INFO)
7105                Log.v(TAG, "    Class=" + a.info.name);
7106            final int NI = a.intents.size();
7107            for (int j=0; j<NI; j++) {
7108                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7109                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7110                    intent.setPriority(0);
7111                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7112                            + a.className + " with priority > 0, forcing to 0");
7113                }
7114                if (DEBUG_SHOW_INFO) {
7115                    Log.v(TAG, "    IntentFilter:");
7116                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7117                }
7118                if (!intent.debugCheck()) {
7119                    Log.w(TAG, "==> For Activity " + a.info.name);
7120                }
7121                addFilter(intent);
7122            }
7123        }
7124
7125        public final void removeActivity(PackageParser.Activity a, String type) {
7126            mActivities.remove(a.getComponentName());
7127            if (DEBUG_SHOW_INFO) {
7128                Log.v(TAG, "  " + type + " "
7129                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7130                                : a.info.name) + ":");
7131                Log.v(TAG, "    Class=" + a.info.name);
7132            }
7133            final int NI = a.intents.size();
7134            for (int j=0; j<NI; j++) {
7135                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7136                if (DEBUG_SHOW_INFO) {
7137                    Log.v(TAG, "    IntentFilter:");
7138                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7139                }
7140                removeFilter(intent);
7141            }
7142        }
7143
7144        @Override
7145        protected boolean allowFilterResult(
7146                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7147            ActivityInfo filterAi = filter.activity.info;
7148            for (int i=dest.size()-1; i>=0; i--) {
7149                ActivityInfo destAi = dest.get(i).activityInfo;
7150                if (destAi.name == filterAi.name
7151                        && destAi.packageName == filterAi.packageName) {
7152                    return false;
7153                }
7154            }
7155            return true;
7156        }
7157
7158        @Override
7159        protected ActivityIntentInfo[] newArray(int size) {
7160            return new ActivityIntentInfo[size];
7161        }
7162
7163        @Override
7164        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7165            if (!sUserManager.exists(userId)) return true;
7166            PackageParser.Package p = filter.activity.owner;
7167            if (p != null) {
7168                PackageSetting ps = (PackageSetting)p.mExtras;
7169                if (ps != null) {
7170                    // System apps are never considered stopped for purposes of
7171                    // filtering, because there may be no way for the user to
7172                    // actually re-launch them.
7173                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7174                            && ps.getStopped(userId);
7175                }
7176            }
7177            return false;
7178        }
7179
7180        @Override
7181        protected boolean isPackageForFilter(String packageName,
7182                PackageParser.ActivityIntentInfo info) {
7183            return packageName.equals(info.activity.owner.packageName);
7184        }
7185
7186        @Override
7187        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7188                int match, int userId) {
7189            if (!sUserManager.exists(userId)) return null;
7190            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7191                return null;
7192            }
7193            final PackageParser.Activity activity = info.activity;
7194            if (mSafeMode && (activity.info.applicationInfo.flags
7195                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7196                return null;
7197            }
7198            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7199            if (ps == null) {
7200                return null;
7201            }
7202            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7203                    ps.readUserState(userId), userId);
7204            if (ai == null) {
7205                return null;
7206            }
7207            final ResolveInfo res = new ResolveInfo();
7208            res.activityInfo = ai;
7209            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7210                res.filter = info;
7211            }
7212            res.priority = info.getPriority();
7213            res.preferredOrder = activity.owner.mPreferredOrder;
7214            //System.out.println("Result: " + res.activityInfo.className +
7215            //                   " = " + res.priority);
7216            res.match = match;
7217            res.isDefault = info.hasDefault;
7218            res.labelRes = info.labelRes;
7219            res.nonLocalizedLabel = info.nonLocalizedLabel;
7220            if (userNeedsBadging(userId)) {
7221                res.noResourceId = true;
7222            } else {
7223                res.icon = info.icon;
7224            }
7225            res.system = res.activityInfo.applicationInfo.isSystemApp();
7226            return res;
7227        }
7228
7229        @Override
7230        protected void sortResults(List<ResolveInfo> results) {
7231            Collections.sort(results, mResolvePrioritySorter);
7232        }
7233
7234        @Override
7235        protected void dumpFilter(PrintWriter out, String prefix,
7236                PackageParser.ActivityIntentInfo filter) {
7237            out.print(prefix); out.print(
7238                    Integer.toHexString(System.identityHashCode(filter.activity)));
7239                    out.print(' ');
7240                    filter.activity.printComponentShortName(out);
7241                    out.print(" filter ");
7242                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7243        }
7244
7245        @Override
7246        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7247            return filter.activity;
7248        }
7249
7250        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7251            PackageParser.Activity activity = (PackageParser.Activity)label;
7252            out.print(prefix); out.print(
7253                    Integer.toHexString(System.identityHashCode(activity)));
7254                    out.print(' ');
7255                    activity.printComponentShortName(out);
7256            if (count > 1) {
7257                out.print(" ("); out.print(count); out.print(" filters)");
7258            }
7259            out.println();
7260        }
7261
7262//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7263//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7264//            final List<ResolveInfo> retList = Lists.newArrayList();
7265//            while (i.hasNext()) {
7266//                final ResolveInfo resolveInfo = i.next();
7267//                if (isEnabledLP(resolveInfo.activityInfo)) {
7268//                    retList.add(resolveInfo);
7269//                }
7270//            }
7271//            return retList;
7272//        }
7273
7274        // Keys are String (activity class name), values are Activity.
7275        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
7276                = new ArrayMap<ComponentName, PackageParser.Activity>();
7277        private int mFlags;
7278    }
7279
7280    private final class ServiceIntentResolver
7281            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7282        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7283                boolean defaultOnly, int userId) {
7284            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7285            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7286        }
7287
7288        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7289                int userId) {
7290            if (!sUserManager.exists(userId)) return null;
7291            mFlags = flags;
7292            return super.queryIntent(intent, resolvedType,
7293                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7294        }
7295
7296        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7297                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7298            if (!sUserManager.exists(userId)) return null;
7299            if (packageServices == null) {
7300                return null;
7301            }
7302            mFlags = flags;
7303            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7304            final int N = packageServices.size();
7305            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7306                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7307
7308            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7309            for (int i = 0; i < N; ++i) {
7310                intentFilters = packageServices.get(i).intents;
7311                if (intentFilters != null && intentFilters.size() > 0) {
7312                    PackageParser.ServiceIntentInfo[] array =
7313                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7314                    intentFilters.toArray(array);
7315                    listCut.add(array);
7316                }
7317            }
7318            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7319        }
7320
7321        public final void addService(PackageParser.Service s) {
7322            mServices.put(s.getComponentName(), s);
7323            if (DEBUG_SHOW_INFO) {
7324                Log.v(TAG, "  "
7325                        + (s.info.nonLocalizedLabel != null
7326                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7327                Log.v(TAG, "    Class=" + s.info.name);
7328            }
7329            final int NI = s.intents.size();
7330            int j;
7331            for (j=0; j<NI; j++) {
7332                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7333                if (DEBUG_SHOW_INFO) {
7334                    Log.v(TAG, "    IntentFilter:");
7335                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7336                }
7337                if (!intent.debugCheck()) {
7338                    Log.w(TAG, "==> For Service " + s.info.name);
7339                }
7340                addFilter(intent);
7341            }
7342        }
7343
7344        public final void removeService(PackageParser.Service s) {
7345            mServices.remove(s.getComponentName());
7346            if (DEBUG_SHOW_INFO) {
7347                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7348                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7349                Log.v(TAG, "    Class=" + s.info.name);
7350            }
7351            final int NI = s.intents.size();
7352            int j;
7353            for (j=0; j<NI; j++) {
7354                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7355                if (DEBUG_SHOW_INFO) {
7356                    Log.v(TAG, "    IntentFilter:");
7357                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7358                }
7359                removeFilter(intent);
7360            }
7361        }
7362
7363        @Override
7364        protected boolean allowFilterResult(
7365                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7366            ServiceInfo filterSi = filter.service.info;
7367            for (int i=dest.size()-1; i>=0; i--) {
7368                ServiceInfo destAi = dest.get(i).serviceInfo;
7369                if (destAi.name == filterSi.name
7370                        && destAi.packageName == filterSi.packageName) {
7371                    return false;
7372                }
7373            }
7374            return true;
7375        }
7376
7377        @Override
7378        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7379            return new PackageParser.ServiceIntentInfo[size];
7380        }
7381
7382        @Override
7383        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7384            if (!sUserManager.exists(userId)) return true;
7385            PackageParser.Package p = filter.service.owner;
7386            if (p != null) {
7387                PackageSetting ps = (PackageSetting)p.mExtras;
7388                if (ps != null) {
7389                    // System apps are never considered stopped for purposes of
7390                    // filtering, because there may be no way for the user to
7391                    // actually re-launch them.
7392                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7393                            && ps.getStopped(userId);
7394                }
7395            }
7396            return false;
7397        }
7398
7399        @Override
7400        protected boolean isPackageForFilter(String packageName,
7401                PackageParser.ServiceIntentInfo info) {
7402            return packageName.equals(info.service.owner.packageName);
7403        }
7404
7405        @Override
7406        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7407                int match, int userId) {
7408            if (!sUserManager.exists(userId)) return null;
7409            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7410            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7411                return null;
7412            }
7413            final PackageParser.Service service = info.service;
7414            if (mSafeMode && (service.info.applicationInfo.flags
7415                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7416                return null;
7417            }
7418            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7419            if (ps == null) {
7420                return null;
7421            }
7422            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7423                    ps.readUserState(userId), userId);
7424            if (si == null) {
7425                return null;
7426            }
7427            final ResolveInfo res = new ResolveInfo();
7428            res.serviceInfo = si;
7429            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7430                res.filter = filter;
7431            }
7432            res.priority = info.getPriority();
7433            res.preferredOrder = service.owner.mPreferredOrder;
7434            //System.out.println("Result: " + res.activityInfo.className +
7435            //                   " = " + res.priority);
7436            res.match = match;
7437            res.isDefault = info.hasDefault;
7438            res.labelRes = info.labelRes;
7439            res.nonLocalizedLabel = info.nonLocalizedLabel;
7440            res.icon = info.icon;
7441            res.system = res.serviceInfo.applicationInfo.isSystemApp();
7442            return res;
7443        }
7444
7445        @Override
7446        protected void sortResults(List<ResolveInfo> results) {
7447            Collections.sort(results, mResolvePrioritySorter);
7448        }
7449
7450        @Override
7451        protected void dumpFilter(PrintWriter out, String prefix,
7452                PackageParser.ServiceIntentInfo filter) {
7453            out.print(prefix); out.print(
7454                    Integer.toHexString(System.identityHashCode(filter.service)));
7455                    out.print(' ');
7456                    filter.service.printComponentShortName(out);
7457                    out.print(" filter ");
7458                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7459        }
7460
7461        @Override
7462        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
7463            return filter.service;
7464        }
7465
7466        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7467            PackageParser.Service service = (PackageParser.Service)label;
7468            out.print(prefix); out.print(
7469                    Integer.toHexString(System.identityHashCode(service)));
7470                    out.print(' ');
7471                    service.printComponentShortName(out);
7472            if (count > 1) {
7473                out.print(" ("); out.print(count); out.print(" filters)");
7474            }
7475            out.println();
7476        }
7477
7478//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7479//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7480//            final List<ResolveInfo> retList = Lists.newArrayList();
7481//            while (i.hasNext()) {
7482//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7483//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7484//                    retList.add(resolveInfo);
7485//                }
7486//            }
7487//            return retList;
7488//        }
7489
7490        // Keys are String (activity class name), values are Activity.
7491        private final ArrayMap<ComponentName, PackageParser.Service> mServices
7492                = new ArrayMap<ComponentName, PackageParser.Service>();
7493        private int mFlags;
7494    };
7495
7496    private final class ProviderIntentResolver
7497            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7498        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7499                boolean defaultOnly, int userId) {
7500            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7501            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7502        }
7503
7504        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7505                int userId) {
7506            if (!sUserManager.exists(userId))
7507                return null;
7508            mFlags = flags;
7509            return super.queryIntent(intent, resolvedType,
7510                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7511        }
7512
7513        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7514                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7515            if (!sUserManager.exists(userId))
7516                return null;
7517            if (packageProviders == null) {
7518                return null;
7519            }
7520            mFlags = flags;
7521            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7522            final int N = packageProviders.size();
7523            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7524                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7525
7526            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7527            for (int i = 0; i < N; ++i) {
7528                intentFilters = packageProviders.get(i).intents;
7529                if (intentFilters != null && intentFilters.size() > 0) {
7530                    PackageParser.ProviderIntentInfo[] array =
7531                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7532                    intentFilters.toArray(array);
7533                    listCut.add(array);
7534                }
7535            }
7536            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7537        }
7538
7539        public final void addProvider(PackageParser.Provider p) {
7540            if (mProviders.containsKey(p.getComponentName())) {
7541                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7542                return;
7543            }
7544
7545            mProviders.put(p.getComponentName(), p);
7546            if (DEBUG_SHOW_INFO) {
7547                Log.v(TAG, "  "
7548                        + (p.info.nonLocalizedLabel != null
7549                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7550                Log.v(TAG, "    Class=" + p.info.name);
7551            }
7552            final int NI = p.intents.size();
7553            int j;
7554            for (j = 0; j < NI; j++) {
7555                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7556                if (DEBUG_SHOW_INFO) {
7557                    Log.v(TAG, "    IntentFilter:");
7558                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7559                }
7560                if (!intent.debugCheck()) {
7561                    Log.w(TAG, "==> For Provider " + p.info.name);
7562                }
7563                addFilter(intent);
7564            }
7565        }
7566
7567        public final void removeProvider(PackageParser.Provider p) {
7568            mProviders.remove(p.getComponentName());
7569            if (DEBUG_SHOW_INFO) {
7570                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7571                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7572                Log.v(TAG, "    Class=" + p.info.name);
7573            }
7574            final int NI = p.intents.size();
7575            int j;
7576            for (j = 0; j < NI; j++) {
7577                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7578                if (DEBUG_SHOW_INFO) {
7579                    Log.v(TAG, "    IntentFilter:");
7580                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7581                }
7582                removeFilter(intent);
7583            }
7584        }
7585
7586        @Override
7587        protected boolean allowFilterResult(
7588                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7589            ProviderInfo filterPi = filter.provider.info;
7590            for (int i = dest.size() - 1; i >= 0; i--) {
7591                ProviderInfo destPi = dest.get(i).providerInfo;
7592                if (destPi.name == filterPi.name
7593                        && destPi.packageName == filterPi.packageName) {
7594                    return false;
7595                }
7596            }
7597            return true;
7598        }
7599
7600        @Override
7601        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7602            return new PackageParser.ProviderIntentInfo[size];
7603        }
7604
7605        @Override
7606        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7607            if (!sUserManager.exists(userId))
7608                return true;
7609            PackageParser.Package p = filter.provider.owner;
7610            if (p != null) {
7611                PackageSetting ps = (PackageSetting) p.mExtras;
7612                if (ps != null) {
7613                    // System apps are never considered stopped for purposes of
7614                    // filtering, because there may be no way for the user to
7615                    // actually re-launch them.
7616                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7617                            && ps.getStopped(userId);
7618                }
7619            }
7620            return false;
7621        }
7622
7623        @Override
7624        protected boolean isPackageForFilter(String packageName,
7625                PackageParser.ProviderIntentInfo info) {
7626            return packageName.equals(info.provider.owner.packageName);
7627        }
7628
7629        @Override
7630        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7631                int match, int userId) {
7632            if (!sUserManager.exists(userId))
7633                return null;
7634            final PackageParser.ProviderIntentInfo info = filter;
7635            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7636                return null;
7637            }
7638            final PackageParser.Provider provider = info.provider;
7639            if (mSafeMode && (provider.info.applicationInfo.flags
7640                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7641                return null;
7642            }
7643            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7644            if (ps == null) {
7645                return null;
7646            }
7647            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7648                    ps.readUserState(userId), userId);
7649            if (pi == null) {
7650                return null;
7651            }
7652            final ResolveInfo res = new ResolveInfo();
7653            res.providerInfo = pi;
7654            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7655                res.filter = filter;
7656            }
7657            res.priority = info.getPriority();
7658            res.preferredOrder = provider.owner.mPreferredOrder;
7659            res.match = match;
7660            res.isDefault = info.hasDefault;
7661            res.labelRes = info.labelRes;
7662            res.nonLocalizedLabel = info.nonLocalizedLabel;
7663            res.icon = info.icon;
7664            res.system = res.providerInfo.applicationInfo.isSystemApp();
7665            return res;
7666        }
7667
7668        @Override
7669        protected void sortResults(List<ResolveInfo> results) {
7670            Collections.sort(results, mResolvePrioritySorter);
7671        }
7672
7673        @Override
7674        protected void dumpFilter(PrintWriter out, String prefix,
7675                PackageParser.ProviderIntentInfo filter) {
7676            out.print(prefix);
7677            out.print(
7678                    Integer.toHexString(System.identityHashCode(filter.provider)));
7679            out.print(' ');
7680            filter.provider.printComponentShortName(out);
7681            out.print(" filter ");
7682            out.println(Integer.toHexString(System.identityHashCode(filter)));
7683        }
7684
7685        @Override
7686        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
7687            return filter.provider;
7688        }
7689
7690        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7691            PackageParser.Provider provider = (PackageParser.Provider)label;
7692            out.print(prefix); out.print(
7693                    Integer.toHexString(System.identityHashCode(provider)));
7694                    out.print(' ');
7695                    provider.printComponentShortName(out);
7696            if (count > 1) {
7697                out.print(" ("); out.print(count); out.print(" filters)");
7698            }
7699            out.println();
7700        }
7701
7702        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
7703                = new ArrayMap<ComponentName, PackageParser.Provider>();
7704        private int mFlags;
7705    };
7706
7707    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7708            new Comparator<ResolveInfo>() {
7709        public int compare(ResolveInfo r1, ResolveInfo r2) {
7710            int v1 = r1.priority;
7711            int v2 = r2.priority;
7712            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7713            if (v1 != v2) {
7714                return (v1 > v2) ? -1 : 1;
7715            }
7716            v1 = r1.preferredOrder;
7717            v2 = r2.preferredOrder;
7718            if (v1 != v2) {
7719                return (v1 > v2) ? -1 : 1;
7720            }
7721            if (r1.isDefault != r2.isDefault) {
7722                return r1.isDefault ? -1 : 1;
7723            }
7724            v1 = r1.match;
7725            v2 = r2.match;
7726            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7727            if (v1 != v2) {
7728                return (v1 > v2) ? -1 : 1;
7729            }
7730            if (r1.system != r2.system) {
7731                return r1.system ? -1 : 1;
7732            }
7733            return 0;
7734        }
7735    };
7736
7737    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7738            new Comparator<ProviderInfo>() {
7739        public int compare(ProviderInfo p1, ProviderInfo p2) {
7740            final int v1 = p1.initOrder;
7741            final int v2 = p2.initOrder;
7742            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7743        }
7744    };
7745
7746    static final void sendPackageBroadcast(String action, String pkg,
7747            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7748            int[] userIds) {
7749        IActivityManager am = ActivityManagerNative.getDefault();
7750        if (am != null) {
7751            try {
7752                if (userIds == null) {
7753                    userIds = am.getRunningUserIds();
7754                }
7755                for (int id : userIds) {
7756                    final Intent intent = new Intent(action,
7757                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7758                    if (extras != null) {
7759                        intent.putExtras(extras);
7760                    }
7761                    if (targetPkg != null) {
7762                        intent.setPackage(targetPkg);
7763                    }
7764                    // Modify the UID when posting to other users
7765                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7766                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7767                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7768                        intent.putExtra(Intent.EXTRA_UID, uid);
7769                    }
7770                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7771                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7772                    if (DEBUG_BROADCASTS) {
7773                        RuntimeException here = new RuntimeException("here");
7774                        here.fillInStackTrace();
7775                        Slog.d(TAG, "Sending to user " + id + ": "
7776                                + intent.toShortString(false, true, false, false)
7777                                + " " + intent.getExtras(), here);
7778                    }
7779                    am.broadcastIntent(null, intent, null, finishedReceiver,
7780                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7781                            finishedReceiver != null, false, id);
7782                }
7783            } catch (RemoteException ex) {
7784            }
7785        }
7786    }
7787
7788    /**
7789     * Check if the external storage media is available. This is true if there
7790     * is a mounted external storage medium or if the external storage is
7791     * emulated.
7792     */
7793    private boolean isExternalMediaAvailable() {
7794        return mMediaMounted || Environment.isExternalStorageEmulated();
7795    }
7796
7797    @Override
7798    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7799        // writer
7800        synchronized (mPackages) {
7801            if (!isExternalMediaAvailable()) {
7802                // If the external storage is no longer mounted at this point,
7803                // the caller may not have been able to delete all of this
7804                // packages files and can not delete any more.  Bail.
7805                return null;
7806            }
7807            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7808            if (lastPackage != null) {
7809                pkgs.remove(lastPackage);
7810            }
7811            if (pkgs.size() > 0) {
7812                return pkgs.get(0);
7813            }
7814        }
7815        return null;
7816    }
7817
7818    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7819        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7820                userId, andCode ? 1 : 0, packageName);
7821        if (mSystemReady) {
7822            msg.sendToTarget();
7823        } else {
7824            if (mPostSystemReadyMessages == null) {
7825                mPostSystemReadyMessages = new ArrayList<>();
7826            }
7827            mPostSystemReadyMessages.add(msg);
7828        }
7829    }
7830
7831    void startCleaningPackages() {
7832        // reader
7833        synchronized (mPackages) {
7834            if (!isExternalMediaAvailable()) {
7835                return;
7836            }
7837            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7838                return;
7839            }
7840        }
7841        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7842        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7843        IActivityManager am = ActivityManagerNative.getDefault();
7844        if (am != null) {
7845            try {
7846                am.startService(null, intent, null, UserHandle.USER_OWNER);
7847            } catch (RemoteException e) {
7848            }
7849        }
7850    }
7851
7852    @Override
7853    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7854            int installFlags, String installerPackageName, VerificationParams verificationParams,
7855            String packageAbiOverride) {
7856        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7857                packageAbiOverride, UserHandle.getCallingUserId());
7858    }
7859
7860    @Override
7861    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7862            int installFlags, String installerPackageName, VerificationParams verificationParams,
7863            String packageAbiOverride, int userId) {
7864        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
7865
7866        final int callingUid = Binder.getCallingUid();
7867        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
7868
7869        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7870            try {
7871                if (observer != null) {
7872                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7873                }
7874            } catch (RemoteException re) {
7875            }
7876            return;
7877        }
7878
7879        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
7880            installFlags |= PackageManager.INSTALL_FROM_ADB;
7881
7882        } else {
7883            // Caller holds INSTALL_PACKAGES permission, so we're less strict
7884            // about installerPackageName.
7885
7886            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
7887            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
7888        }
7889
7890        UserHandle user;
7891        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7892            user = UserHandle.ALL;
7893        } else {
7894            user = new UserHandle(userId);
7895        }
7896
7897        verificationParams.setInstallerUid(callingUid);
7898
7899        final File originFile = new File(originPath);
7900        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7901
7902        final Message msg = mHandler.obtainMessage(INIT_COPY);
7903        msg.obj = new InstallParams(origin, observer, installFlags,
7904                installerPackageName, verificationParams, user, packageAbiOverride);
7905        mHandler.sendMessage(msg);
7906    }
7907
7908    void installStage(String packageName, File stagedDir, String stagedCid,
7909            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7910            String installerPackageName, int installerUid, UserHandle user) {
7911        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7912                params.referrerUri, installerUid, null);
7913
7914        final OriginInfo origin;
7915        if (stagedDir != null) {
7916            origin = OriginInfo.fromStagedFile(stagedDir);
7917        } else {
7918            origin = OriginInfo.fromStagedContainer(stagedCid);
7919        }
7920
7921        final Message msg = mHandler.obtainMessage(INIT_COPY);
7922        msg.obj = new InstallParams(origin, observer, params.installFlags,
7923                installerPackageName, verifParams, user, params.abiOverride);
7924        mHandler.sendMessage(msg);
7925    }
7926
7927    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7928        Bundle extras = new Bundle(1);
7929        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7930
7931        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7932                packageName, extras, null, null, new int[] {userId});
7933        try {
7934            IActivityManager am = ActivityManagerNative.getDefault();
7935            final boolean isSystem =
7936                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7937            if (isSystem && am.isUserRunning(userId, false)) {
7938                // The just-installed/enabled app is bundled on the system, so presumed
7939                // to be able to run automatically without needing an explicit launch.
7940                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7941                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7942                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7943                        .setPackage(packageName);
7944                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7945                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7946            }
7947        } catch (RemoteException e) {
7948            // shouldn't happen
7949            Slog.w(TAG, "Unable to bootstrap installed package", e);
7950        }
7951    }
7952
7953    @Override
7954    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7955            int userId) {
7956        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7957        PackageSetting pkgSetting;
7958        final int uid = Binder.getCallingUid();
7959        enforceCrossUserPermission(uid, userId, true, true,
7960                "setApplicationHiddenSetting for user " + userId);
7961
7962        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7963            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7964            return false;
7965        }
7966
7967        long callingId = Binder.clearCallingIdentity();
7968        try {
7969            boolean sendAdded = false;
7970            boolean sendRemoved = false;
7971            // writer
7972            synchronized (mPackages) {
7973                pkgSetting = mSettings.mPackages.get(packageName);
7974                if (pkgSetting == null) {
7975                    return false;
7976                }
7977                if (pkgSetting.getHidden(userId) != hidden) {
7978                    pkgSetting.setHidden(hidden, userId);
7979                    mSettings.writePackageRestrictionsLPr(userId);
7980                    if (hidden) {
7981                        sendRemoved = true;
7982                    } else {
7983                        sendAdded = true;
7984                    }
7985                }
7986            }
7987            if (sendAdded) {
7988                sendPackageAddedForUser(packageName, pkgSetting, userId);
7989                return true;
7990            }
7991            if (sendRemoved) {
7992                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7993                        "hiding pkg");
7994                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7995            }
7996        } finally {
7997            Binder.restoreCallingIdentity(callingId);
7998        }
7999        return false;
8000    }
8001
8002    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8003            int userId) {
8004        final PackageRemovedInfo info = new PackageRemovedInfo();
8005        info.removedPackage = packageName;
8006        info.removedUsers = new int[] {userId};
8007        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8008        info.sendBroadcast(false, false, false);
8009    }
8010
8011    /**
8012     * Returns true if application is not found or there was an error. Otherwise it returns
8013     * the hidden state of the package for the given user.
8014     */
8015    @Override
8016    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8017        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8018        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8019                false, "getApplicationHidden for user " + userId);
8020        PackageSetting pkgSetting;
8021        long callingId = Binder.clearCallingIdentity();
8022        try {
8023            // writer
8024            synchronized (mPackages) {
8025                pkgSetting = mSettings.mPackages.get(packageName);
8026                if (pkgSetting == null) {
8027                    return true;
8028                }
8029                return pkgSetting.getHidden(userId);
8030            }
8031        } finally {
8032            Binder.restoreCallingIdentity(callingId);
8033        }
8034    }
8035
8036    /**
8037     * @hide
8038     */
8039    @Override
8040    public int installExistingPackageAsUser(String packageName, int userId) {
8041        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8042                null);
8043        PackageSetting pkgSetting;
8044        final int uid = Binder.getCallingUid();
8045        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8046                + userId);
8047        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8048            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8049        }
8050
8051        long callingId = Binder.clearCallingIdentity();
8052        try {
8053            boolean sendAdded = false;
8054            Bundle extras = new Bundle(1);
8055
8056            // writer
8057            synchronized (mPackages) {
8058                pkgSetting = mSettings.mPackages.get(packageName);
8059                if (pkgSetting == null) {
8060                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8061                }
8062                if (!pkgSetting.getInstalled(userId)) {
8063                    pkgSetting.setInstalled(true, userId);
8064                    pkgSetting.setHidden(false, userId);
8065                    mSettings.writePackageRestrictionsLPr(userId);
8066                    sendAdded = true;
8067                }
8068            }
8069
8070            if (sendAdded) {
8071                sendPackageAddedForUser(packageName, pkgSetting, userId);
8072            }
8073        } finally {
8074            Binder.restoreCallingIdentity(callingId);
8075        }
8076
8077        return PackageManager.INSTALL_SUCCEEDED;
8078    }
8079
8080    boolean isUserRestricted(int userId, String restrictionKey) {
8081        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8082        if (restrictions.getBoolean(restrictionKey, false)) {
8083            Log.w(TAG, "User is restricted: " + restrictionKey);
8084            return true;
8085        }
8086        return false;
8087    }
8088
8089    @Override
8090    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8091        mContext.enforceCallingOrSelfPermission(
8092                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8093                "Only package verification agents can verify applications");
8094
8095        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8096        final PackageVerificationResponse response = new PackageVerificationResponse(
8097                verificationCode, Binder.getCallingUid());
8098        msg.arg1 = id;
8099        msg.obj = response;
8100        mHandler.sendMessage(msg);
8101    }
8102
8103    @Override
8104    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8105            long millisecondsToDelay) {
8106        mContext.enforceCallingOrSelfPermission(
8107                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8108                "Only package verification agents can extend verification timeouts");
8109
8110        final PackageVerificationState state = mPendingVerification.get(id);
8111        final PackageVerificationResponse response = new PackageVerificationResponse(
8112                verificationCodeAtTimeout, Binder.getCallingUid());
8113
8114        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8115            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8116        }
8117        if (millisecondsToDelay < 0) {
8118            millisecondsToDelay = 0;
8119        }
8120        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8121                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8122            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8123        }
8124
8125        if ((state != null) && !state.timeoutExtended()) {
8126            state.extendTimeout();
8127
8128            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8129            msg.arg1 = id;
8130            msg.obj = response;
8131            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8132        }
8133    }
8134
8135    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8136            int verificationCode, UserHandle user) {
8137        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8138        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8139        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8140        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8141        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8142
8143        mContext.sendBroadcastAsUser(intent, user,
8144                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8145    }
8146
8147    private ComponentName matchComponentForVerifier(String packageName,
8148            List<ResolveInfo> receivers) {
8149        ActivityInfo targetReceiver = null;
8150
8151        final int NR = receivers.size();
8152        for (int i = 0; i < NR; i++) {
8153            final ResolveInfo info = receivers.get(i);
8154            if (info.activityInfo == null) {
8155                continue;
8156            }
8157
8158            if (packageName.equals(info.activityInfo.packageName)) {
8159                targetReceiver = info.activityInfo;
8160                break;
8161            }
8162        }
8163
8164        if (targetReceiver == null) {
8165            return null;
8166        }
8167
8168        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8169    }
8170
8171    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8172            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8173        if (pkgInfo.verifiers.length == 0) {
8174            return null;
8175        }
8176
8177        final int N = pkgInfo.verifiers.length;
8178        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8179        for (int i = 0; i < N; i++) {
8180            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8181
8182            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8183                    receivers);
8184            if (comp == null) {
8185                continue;
8186            }
8187
8188            final int verifierUid = getUidForVerifier(verifierInfo);
8189            if (verifierUid == -1) {
8190                continue;
8191            }
8192
8193            if (DEBUG_VERIFY) {
8194                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8195                        + " with the correct signature");
8196            }
8197            sufficientVerifiers.add(comp);
8198            verificationState.addSufficientVerifier(verifierUid);
8199        }
8200
8201        return sufficientVerifiers;
8202    }
8203
8204    private int getUidForVerifier(VerifierInfo verifierInfo) {
8205        synchronized (mPackages) {
8206            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8207            if (pkg == null) {
8208                return -1;
8209            } else if (pkg.mSignatures.length != 1) {
8210                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8211                        + " has more than one signature; ignoring");
8212                return -1;
8213            }
8214
8215            /*
8216             * If the public key of the package's signature does not match
8217             * our expected public key, then this is a different package and
8218             * we should skip.
8219             */
8220
8221            final byte[] expectedPublicKey;
8222            try {
8223                final Signature verifierSig = pkg.mSignatures[0];
8224                final PublicKey publicKey = verifierSig.getPublicKey();
8225                expectedPublicKey = publicKey.getEncoded();
8226            } catch (CertificateException e) {
8227                return -1;
8228            }
8229
8230            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8231
8232            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8233                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8234                        + " does not have the expected public key; ignoring");
8235                return -1;
8236            }
8237
8238            return pkg.applicationInfo.uid;
8239        }
8240    }
8241
8242    @Override
8243    public void finishPackageInstall(int token) {
8244        enforceSystemOrRoot("Only the system is allowed to finish installs");
8245
8246        if (DEBUG_INSTALL) {
8247            Slog.v(TAG, "BM finishing package install for " + token);
8248        }
8249
8250        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8251        mHandler.sendMessage(msg);
8252    }
8253
8254    /**
8255     * Get the verification agent timeout.
8256     *
8257     * @return verification timeout in milliseconds
8258     */
8259    private long getVerificationTimeout() {
8260        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8261                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8262                DEFAULT_VERIFICATION_TIMEOUT);
8263    }
8264
8265    /**
8266     * Get the default verification agent response code.
8267     *
8268     * @return default verification response code
8269     */
8270    private int getDefaultVerificationResponse() {
8271        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8272                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8273                DEFAULT_VERIFICATION_RESPONSE);
8274    }
8275
8276    /**
8277     * Check whether or not package verification has been enabled.
8278     *
8279     * @return true if verification should be performed
8280     */
8281    private boolean isVerificationEnabled(int userId, int installFlags) {
8282        if (!DEFAULT_VERIFY_ENABLE) {
8283            return false;
8284        }
8285
8286        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8287
8288        // Check if installing from ADB
8289        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8290            // Do not run verification in a test harness environment
8291            if (ActivityManager.isRunningInTestHarness()) {
8292                return false;
8293            }
8294            if (ensureVerifyAppsEnabled) {
8295                return true;
8296            }
8297            // Check if the developer does not want package verification for ADB installs
8298            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8299                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8300                return false;
8301            }
8302        }
8303
8304        if (ensureVerifyAppsEnabled) {
8305            return true;
8306        }
8307
8308        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8309                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8310    }
8311
8312    /**
8313     * Get the "allow unknown sources" setting.
8314     *
8315     * @return the current "allow unknown sources" setting
8316     */
8317    private int getUnknownSourcesSettings() {
8318        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8319                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8320                -1);
8321    }
8322
8323    @Override
8324    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8325        final int uid = Binder.getCallingUid();
8326        // writer
8327        synchronized (mPackages) {
8328            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8329            if (targetPackageSetting == null) {
8330                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8331            }
8332
8333            PackageSetting installerPackageSetting;
8334            if (installerPackageName != null) {
8335                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8336                if (installerPackageSetting == null) {
8337                    throw new IllegalArgumentException("Unknown installer package: "
8338                            + installerPackageName);
8339                }
8340            } else {
8341                installerPackageSetting = null;
8342            }
8343
8344            Signature[] callerSignature;
8345            Object obj = mSettings.getUserIdLPr(uid);
8346            if (obj != null) {
8347                if (obj instanceof SharedUserSetting) {
8348                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8349                } else if (obj instanceof PackageSetting) {
8350                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8351                } else {
8352                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8353                }
8354            } else {
8355                throw new SecurityException("Unknown calling uid " + uid);
8356            }
8357
8358            // Verify: can't set installerPackageName to a package that is
8359            // not signed with the same cert as the caller.
8360            if (installerPackageSetting != null) {
8361                if (compareSignatures(callerSignature,
8362                        installerPackageSetting.signatures.mSignatures)
8363                        != PackageManager.SIGNATURE_MATCH) {
8364                    throw new SecurityException(
8365                            "Caller does not have same cert as new installer package "
8366                            + installerPackageName);
8367                }
8368            }
8369
8370            // Verify: if target already has an installer package, it must
8371            // be signed with the same cert as the caller.
8372            if (targetPackageSetting.installerPackageName != null) {
8373                PackageSetting setting = mSettings.mPackages.get(
8374                        targetPackageSetting.installerPackageName);
8375                // If the currently set package isn't valid, then it's always
8376                // okay to change it.
8377                if (setting != null) {
8378                    if (compareSignatures(callerSignature,
8379                            setting.signatures.mSignatures)
8380                            != PackageManager.SIGNATURE_MATCH) {
8381                        throw new SecurityException(
8382                                "Caller does not have same cert as old installer package "
8383                                + targetPackageSetting.installerPackageName);
8384                    }
8385                }
8386            }
8387
8388            // Okay!
8389            targetPackageSetting.installerPackageName = installerPackageName;
8390            scheduleWriteSettingsLocked();
8391        }
8392    }
8393
8394    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8395        // Queue up an async operation since the package installation may take a little while.
8396        mHandler.post(new Runnable() {
8397            public void run() {
8398                mHandler.removeCallbacks(this);
8399                 // Result object to be returned
8400                PackageInstalledInfo res = new PackageInstalledInfo();
8401                res.returnCode = currentStatus;
8402                res.uid = -1;
8403                res.pkg = null;
8404                res.removedInfo = new PackageRemovedInfo();
8405                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8406                    args.doPreInstall(res.returnCode);
8407                    synchronized (mInstallLock) {
8408                        installPackageLI(args, res);
8409                    }
8410                    args.doPostInstall(res.returnCode, res.uid);
8411                }
8412
8413                // A restore should be performed at this point if (a) the install
8414                // succeeded, (b) the operation is not an update, and (c) the new
8415                // package has not opted out of backup participation.
8416                final boolean update = res.removedInfo.removedPackage != null;
8417                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8418                boolean doRestore = !update
8419                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8420
8421                // Set up the post-install work request bookkeeping.  This will be used
8422                // and cleaned up by the post-install event handling regardless of whether
8423                // there's a restore pass performed.  Token values are >= 1.
8424                int token;
8425                if (mNextInstallToken < 0) mNextInstallToken = 1;
8426                token = mNextInstallToken++;
8427
8428                PostInstallData data = new PostInstallData(args, res);
8429                mRunningInstalls.put(token, data);
8430                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8431
8432                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8433                    // Pass responsibility to the Backup Manager.  It will perform a
8434                    // restore if appropriate, then pass responsibility back to the
8435                    // Package Manager to run the post-install observer callbacks
8436                    // and broadcasts.
8437                    IBackupManager bm = IBackupManager.Stub.asInterface(
8438                            ServiceManager.getService(Context.BACKUP_SERVICE));
8439                    if (bm != null) {
8440                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8441                                + " to BM for possible restore");
8442                        try {
8443                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
8444                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8445                            } else {
8446                                doRestore = false;
8447                            }
8448                        } catch (RemoteException e) {
8449                            // can't happen; the backup manager is local
8450                        } catch (Exception e) {
8451                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8452                            doRestore = false;
8453                        }
8454                    } else {
8455                        Slog.e(TAG, "Backup Manager not found!");
8456                        doRestore = false;
8457                    }
8458                }
8459
8460                if (!doRestore) {
8461                    // No restore possible, or the Backup Manager was mysteriously not
8462                    // available -- just fire the post-install work request directly.
8463                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8464                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8465                    mHandler.sendMessage(msg);
8466                }
8467            }
8468        });
8469    }
8470
8471    private abstract class HandlerParams {
8472        private static final int MAX_RETRIES = 4;
8473
8474        /**
8475         * Number of times startCopy() has been attempted and had a non-fatal
8476         * error.
8477         */
8478        private int mRetries = 0;
8479
8480        /** User handle for the user requesting the information or installation. */
8481        private final UserHandle mUser;
8482
8483        HandlerParams(UserHandle user) {
8484            mUser = user;
8485        }
8486
8487        UserHandle getUser() {
8488            return mUser;
8489        }
8490
8491        final boolean startCopy() {
8492            boolean res;
8493            try {
8494                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8495
8496                if (++mRetries > MAX_RETRIES) {
8497                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8498                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8499                    handleServiceError();
8500                    return false;
8501                } else {
8502                    handleStartCopy();
8503                    res = true;
8504                }
8505            } catch (RemoteException e) {
8506                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8507                mHandler.sendEmptyMessage(MCS_RECONNECT);
8508                res = false;
8509            }
8510            handleReturnCode();
8511            return res;
8512        }
8513
8514        final void serviceError() {
8515            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8516            handleServiceError();
8517            handleReturnCode();
8518        }
8519
8520        abstract void handleStartCopy() throws RemoteException;
8521        abstract void handleServiceError();
8522        abstract void handleReturnCode();
8523    }
8524
8525    class MeasureParams extends HandlerParams {
8526        private final PackageStats mStats;
8527        private boolean mSuccess;
8528
8529        private final IPackageStatsObserver mObserver;
8530
8531        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8532            super(new UserHandle(stats.userHandle));
8533            mObserver = observer;
8534            mStats = stats;
8535        }
8536
8537        @Override
8538        public String toString() {
8539            return "MeasureParams{"
8540                + Integer.toHexString(System.identityHashCode(this))
8541                + " " + mStats.packageName + "}";
8542        }
8543
8544        @Override
8545        void handleStartCopy() throws RemoteException {
8546            synchronized (mInstallLock) {
8547                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8548            }
8549
8550            if (mSuccess) {
8551                final boolean mounted;
8552                if (Environment.isExternalStorageEmulated()) {
8553                    mounted = true;
8554                } else {
8555                    final String status = Environment.getExternalStorageState();
8556                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8557                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8558                }
8559
8560                if (mounted) {
8561                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8562
8563                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8564                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8565
8566                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8567                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8568
8569                    // Always subtract cache size, since it's a subdirectory
8570                    mStats.externalDataSize -= mStats.externalCacheSize;
8571
8572                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8573                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8574
8575                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8576                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8577                }
8578            }
8579        }
8580
8581        @Override
8582        void handleReturnCode() {
8583            if (mObserver != null) {
8584                try {
8585                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8586                } catch (RemoteException e) {
8587                    Slog.i(TAG, "Observer no longer exists.");
8588                }
8589            }
8590        }
8591
8592        @Override
8593        void handleServiceError() {
8594            Slog.e(TAG, "Could not measure application " + mStats.packageName
8595                            + " external storage");
8596        }
8597    }
8598
8599    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8600            throws RemoteException {
8601        long result = 0;
8602        for (File path : paths) {
8603            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8604        }
8605        return result;
8606    }
8607
8608    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8609        for (File path : paths) {
8610            try {
8611                mcs.clearDirectory(path.getAbsolutePath());
8612            } catch (RemoteException e) {
8613            }
8614        }
8615    }
8616
8617    static class OriginInfo {
8618        /**
8619         * Location where install is coming from, before it has been
8620         * copied/renamed into place. This could be a single monolithic APK
8621         * file, or a cluster directory. This location may be untrusted.
8622         */
8623        final File file;
8624        final String cid;
8625
8626        /**
8627         * Flag indicating that {@link #file} or {@link #cid} has already been
8628         * staged, meaning downstream users don't need to defensively copy the
8629         * contents.
8630         */
8631        final boolean staged;
8632
8633        /**
8634         * Flag indicating that {@link #file} or {@link #cid} is an already
8635         * installed app that is being moved.
8636         */
8637        final boolean existing;
8638
8639        final String resolvedPath;
8640        final File resolvedFile;
8641
8642        static OriginInfo fromNothing() {
8643            return new OriginInfo(null, null, false, false);
8644        }
8645
8646        static OriginInfo fromUntrustedFile(File file) {
8647            return new OriginInfo(file, null, false, false);
8648        }
8649
8650        static OriginInfo fromExistingFile(File file) {
8651            return new OriginInfo(file, null, false, true);
8652        }
8653
8654        static OriginInfo fromStagedFile(File file) {
8655            return new OriginInfo(file, null, true, false);
8656        }
8657
8658        static OriginInfo fromStagedContainer(String cid) {
8659            return new OriginInfo(null, cid, true, false);
8660        }
8661
8662        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8663            this.file = file;
8664            this.cid = cid;
8665            this.staged = staged;
8666            this.existing = existing;
8667
8668            if (cid != null) {
8669                resolvedPath = PackageHelper.getSdDir(cid);
8670                resolvedFile = new File(resolvedPath);
8671            } else if (file != null) {
8672                resolvedPath = file.getAbsolutePath();
8673                resolvedFile = file;
8674            } else {
8675                resolvedPath = null;
8676                resolvedFile = null;
8677            }
8678        }
8679    }
8680
8681    class InstallParams extends HandlerParams {
8682        final OriginInfo origin;
8683        final IPackageInstallObserver2 observer;
8684        int installFlags;
8685        final String installerPackageName;
8686        final VerificationParams verificationParams;
8687        private InstallArgs mArgs;
8688        private int mRet;
8689        final String packageAbiOverride;
8690
8691        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8692                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8693                String packageAbiOverride) {
8694            super(user);
8695            this.origin = origin;
8696            this.observer = observer;
8697            this.installFlags = installFlags;
8698            this.installerPackageName = installerPackageName;
8699            this.verificationParams = verificationParams;
8700            this.packageAbiOverride = packageAbiOverride;
8701        }
8702
8703        @Override
8704        public String toString() {
8705            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8706                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8707        }
8708
8709        public ManifestDigest getManifestDigest() {
8710            if (verificationParams == null) {
8711                return null;
8712            }
8713            return verificationParams.getManifestDigest();
8714        }
8715
8716        private int installLocationPolicy(PackageInfoLite pkgLite) {
8717            String packageName = pkgLite.packageName;
8718            int installLocation = pkgLite.installLocation;
8719            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8720            // reader
8721            synchronized (mPackages) {
8722                PackageParser.Package pkg = mPackages.get(packageName);
8723                if (pkg != null) {
8724                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8725                        // Check for downgrading.
8726                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8727                            try {
8728                                checkDowngrade(pkg, pkgLite);
8729                            } catch (PackageManagerException e) {
8730                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
8731                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8732                            }
8733                        }
8734                        // Check for updated system application.
8735                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8736                            if (onSd) {
8737                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8738                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8739                            }
8740                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8741                        } else {
8742                            if (onSd) {
8743                                // Install flag overrides everything.
8744                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8745                            }
8746                            // If current upgrade specifies particular preference
8747                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8748                                // Application explicitly specified internal.
8749                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8750                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8751                                // App explictly prefers external. Let policy decide
8752                            } else {
8753                                // Prefer previous location
8754                                if (isExternal(pkg)) {
8755                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8756                                }
8757                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8758                            }
8759                        }
8760                    } else {
8761                        // Invalid install. Return error code
8762                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8763                    }
8764                }
8765            }
8766            // All the special cases have been taken care of.
8767            // Return result based on recommended install location.
8768            if (onSd) {
8769                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8770            }
8771            return pkgLite.recommendedInstallLocation;
8772        }
8773
8774        /*
8775         * Invoke remote method to get package information and install
8776         * location values. Override install location based on default
8777         * policy if needed and then create install arguments based
8778         * on the install location.
8779         */
8780        public void handleStartCopy() throws RemoteException {
8781            int ret = PackageManager.INSTALL_SUCCEEDED;
8782
8783            // If we're already staged, we've firmly committed to an install location
8784            if (origin.staged) {
8785                if (origin.file != null) {
8786                    installFlags |= PackageManager.INSTALL_INTERNAL;
8787                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8788                } else if (origin.cid != null) {
8789                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8790                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8791                } else {
8792                    throw new IllegalStateException("Invalid stage location");
8793                }
8794            }
8795
8796            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8797            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8798
8799            PackageInfoLite pkgLite = null;
8800
8801            if (onInt && onSd) {
8802                // Check if both bits are set.
8803                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8804                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8805            } else {
8806                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8807                        packageAbiOverride);
8808
8809                /*
8810                 * If we have too little free space, try to free cache
8811                 * before giving up.
8812                 */
8813                if (!origin.staged && pkgLite.recommendedInstallLocation
8814                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8815                    // TODO: focus freeing disk space on the target device
8816                    final StorageManager storage = StorageManager.from(mContext);
8817                    final long lowThreshold = storage.getStorageLowBytes(
8818                            Environment.getDataDirectory());
8819
8820                    final long sizeBytes = mContainerService.calculateInstalledSize(
8821                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8822
8823                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8824                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8825                                installFlags, packageAbiOverride);
8826                    }
8827
8828                    /*
8829                     * The cache free must have deleted the file we
8830                     * downloaded to install.
8831                     *
8832                     * TODO: fix the "freeCache" call to not delete
8833                     *       the file we care about.
8834                     */
8835                    if (pkgLite.recommendedInstallLocation
8836                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8837                        pkgLite.recommendedInstallLocation
8838                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8839                    }
8840                }
8841            }
8842
8843            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8844                int loc = pkgLite.recommendedInstallLocation;
8845                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8846                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8847                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8848                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8849                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8850                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8851                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8852                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8853                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8854                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8855                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8856                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8857                } else {
8858                    // Override with defaults if needed.
8859                    loc = installLocationPolicy(pkgLite);
8860                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8861                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8862                    } else if (!onSd && !onInt) {
8863                        // Override install location with flags
8864                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8865                            // Set the flag to install on external media.
8866                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8867                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8868                        } else {
8869                            // Make sure the flag for installing on external
8870                            // media is unset
8871                            installFlags |= PackageManager.INSTALL_INTERNAL;
8872                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8873                        }
8874                    }
8875                }
8876            }
8877
8878            final InstallArgs args = createInstallArgs(this);
8879            mArgs = args;
8880
8881            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8882                 /*
8883                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8884                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8885                 */
8886                int userIdentifier = getUser().getIdentifier();
8887                if (userIdentifier == UserHandle.USER_ALL
8888                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8889                    userIdentifier = UserHandle.USER_OWNER;
8890                }
8891
8892                /*
8893                 * Determine if we have any installed package verifiers. If we
8894                 * do, then we'll defer to them to verify the packages.
8895                 */
8896                final int requiredUid = mRequiredVerifierPackage == null ? -1
8897                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8898                if (!origin.existing && requiredUid != -1
8899                        && isVerificationEnabled(userIdentifier, installFlags)) {
8900                    final Intent verification = new Intent(
8901                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8902                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
8903                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8904                            PACKAGE_MIME_TYPE);
8905                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8906
8907                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8908                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8909                            0 /* TODO: Which userId? */);
8910
8911                    if (DEBUG_VERIFY) {
8912                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8913                                + verification.toString() + " with " + pkgLite.verifiers.length
8914                                + " optional verifiers");
8915                    }
8916
8917                    final int verificationId = mPendingVerificationToken++;
8918
8919                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8920
8921                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8922                            installerPackageName);
8923
8924                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8925                            installFlags);
8926
8927                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8928                            pkgLite.packageName);
8929
8930                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8931                            pkgLite.versionCode);
8932
8933                    if (verificationParams != null) {
8934                        if (verificationParams.getVerificationURI() != null) {
8935                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8936                                 verificationParams.getVerificationURI());
8937                        }
8938                        if (verificationParams.getOriginatingURI() != null) {
8939                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8940                                  verificationParams.getOriginatingURI());
8941                        }
8942                        if (verificationParams.getReferrer() != null) {
8943                            verification.putExtra(Intent.EXTRA_REFERRER,
8944                                  verificationParams.getReferrer());
8945                        }
8946                        if (verificationParams.getOriginatingUid() >= 0) {
8947                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8948                                  verificationParams.getOriginatingUid());
8949                        }
8950                        if (verificationParams.getInstallerUid() >= 0) {
8951                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8952                                  verificationParams.getInstallerUid());
8953                        }
8954                    }
8955
8956                    final PackageVerificationState verificationState = new PackageVerificationState(
8957                            requiredUid, args);
8958
8959                    mPendingVerification.append(verificationId, verificationState);
8960
8961                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8962                            receivers, verificationState);
8963
8964                    /*
8965                     * If any sufficient verifiers were listed in the package
8966                     * manifest, attempt to ask them.
8967                     */
8968                    if (sufficientVerifiers != null) {
8969                        final int N = sufficientVerifiers.size();
8970                        if (N == 0) {
8971                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8972                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8973                        } else {
8974                            for (int i = 0; i < N; i++) {
8975                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8976
8977                                final Intent sufficientIntent = new Intent(verification);
8978                                sufficientIntent.setComponent(verifierComponent);
8979
8980                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8981                            }
8982                        }
8983                    }
8984
8985                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8986                            mRequiredVerifierPackage, receivers);
8987                    if (ret == PackageManager.INSTALL_SUCCEEDED
8988                            && mRequiredVerifierPackage != null) {
8989                        /*
8990                         * Send the intent to the required verification agent,
8991                         * but only start the verification timeout after the
8992                         * target BroadcastReceivers have run.
8993                         */
8994                        verification.setComponent(requiredVerifierComponent);
8995                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8996                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8997                                new BroadcastReceiver() {
8998                                    @Override
8999                                    public void onReceive(Context context, Intent intent) {
9000                                        final Message msg = mHandler
9001                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9002                                        msg.arg1 = verificationId;
9003                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9004                                    }
9005                                }, null, 0, null, null);
9006
9007                        /*
9008                         * We don't want the copy to proceed until verification
9009                         * succeeds, so null out this field.
9010                         */
9011                        mArgs = null;
9012                    }
9013                } else {
9014                    /*
9015                     * No package verification is enabled, so immediately start
9016                     * the remote call to initiate copy using temporary file.
9017                     */
9018                    ret = args.copyApk(mContainerService, true);
9019                }
9020            }
9021
9022            mRet = ret;
9023        }
9024
9025        @Override
9026        void handleReturnCode() {
9027            // If mArgs is null, then MCS couldn't be reached. When it
9028            // reconnects, it will try again to install. At that point, this
9029            // will succeed.
9030            if (mArgs != null) {
9031                processPendingInstall(mArgs, mRet);
9032            }
9033        }
9034
9035        @Override
9036        void handleServiceError() {
9037            mArgs = createInstallArgs(this);
9038            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9039        }
9040
9041        public boolean isForwardLocked() {
9042            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9043        }
9044    }
9045
9046    /**
9047     * Used during creation of InstallArgs
9048     *
9049     * @param installFlags package installation flags
9050     * @return true if should be installed on external storage
9051     */
9052    private static boolean installOnSd(int installFlags) {
9053        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9054            return false;
9055        }
9056        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9057            return true;
9058        }
9059        return false;
9060    }
9061
9062    /**
9063     * Used during creation of InstallArgs
9064     *
9065     * @param installFlags package installation flags
9066     * @return true if should be installed as forward locked
9067     */
9068    private static boolean installForwardLocked(int installFlags) {
9069        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9070    }
9071
9072    private InstallArgs createInstallArgs(InstallParams params) {
9073        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
9074            return new AsecInstallArgs(params);
9075        } else {
9076            return new FileInstallArgs(params);
9077        }
9078    }
9079
9080    /**
9081     * Create args that describe an existing installed package. Typically used
9082     * when cleaning up old installs, or used as a move source.
9083     */
9084    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9085            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9086        final boolean isInAsec;
9087        if (installOnSd(installFlags)) {
9088            /* Apps on SD card are always in ASEC containers. */
9089            isInAsec = true;
9090        } else if (installForwardLocked(installFlags)
9091                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9092            /*
9093             * Forward-locked apps are only in ASEC containers if they're the
9094             * new style
9095             */
9096            isInAsec = true;
9097        } else {
9098            isInAsec = false;
9099        }
9100
9101        if (isInAsec) {
9102            return new AsecInstallArgs(codePath, instructionSets,
9103                    installOnSd(installFlags), installForwardLocked(installFlags));
9104        } else {
9105            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9106                    instructionSets);
9107        }
9108    }
9109
9110    static abstract class InstallArgs {
9111        /** @see InstallParams#origin */
9112        final OriginInfo origin;
9113
9114        final IPackageInstallObserver2 observer;
9115        // Always refers to PackageManager flags only
9116        final int installFlags;
9117        final String installerPackageName;
9118        final ManifestDigest manifestDigest;
9119        final UserHandle user;
9120        final String abiOverride;
9121
9122        // The list of instruction sets supported by this app. This is currently
9123        // only used during the rmdex() phase to clean up resources. We can get rid of this
9124        // if we move dex files under the common app path.
9125        /* nullable */ String[] instructionSets;
9126
9127        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9128                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9129                String[] instructionSets, String abiOverride) {
9130            this.origin = origin;
9131            this.installFlags = installFlags;
9132            this.observer = observer;
9133            this.installerPackageName = installerPackageName;
9134            this.manifestDigest = manifestDigest;
9135            this.user = user;
9136            this.instructionSets = instructionSets;
9137            this.abiOverride = abiOverride;
9138        }
9139
9140        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9141        abstract int doPreInstall(int status);
9142
9143        /**
9144         * Rename package into final resting place. All paths on the given
9145         * scanned package should be updated to reflect the rename.
9146         */
9147        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9148        abstract int doPostInstall(int status, int uid);
9149
9150        /** @see PackageSettingBase#codePathString */
9151        abstract String getCodePath();
9152        /** @see PackageSettingBase#resourcePathString */
9153        abstract String getResourcePath();
9154        abstract String getLegacyNativeLibraryPath();
9155
9156        // Need installer lock especially for dex file removal.
9157        abstract void cleanUpResourcesLI();
9158        abstract boolean doPostDeleteLI(boolean delete);
9159        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9160
9161        /**
9162         * Called before the source arguments are copied. This is used mostly
9163         * for MoveParams when it needs to read the source file to put it in the
9164         * destination.
9165         */
9166        int doPreCopy() {
9167            return PackageManager.INSTALL_SUCCEEDED;
9168        }
9169
9170        /**
9171         * Called after the source arguments are copied. This is used mostly for
9172         * MoveParams when it needs to read the source file to put it in the
9173         * destination.
9174         *
9175         * @return
9176         */
9177        int doPostCopy(int uid) {
9178            return PackageManager.INSTALL_SUCCEEDED;
9179        }
9180
9181        protected boolean isFwdLocked() {
9182            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9183        }
9184
9185        protected boolean isExternal() {
9186            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9187        }
9188
9189        UserHandle getUser() {
9190            return user;
9191        }
9192    }
9193
9194    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
9195        if (!allCodePaths.isEmpty()) {
9196            if (instructionSets == null) {
9197                throw new IllegalStateException("instructionSet == null");
9198            }
9199            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9200            for (String codePath : allCodePaths) {
9201                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9202                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9203                    if (retCode < 0) {
9204                        Slog.w(TAG, "Couldn't remove dex file for package: "
9205                                + " at location " + codePath + ", retcode=" + retCode);
9206                        // we don't consider this to be a failure of the core package deletion
9207                    }
9208                }
9209            }
9210        }
9211    }
9212
9213    /**
9214     * Logic to handle installation of non-ASEC applications, including copying
9215     * and renaming logic.
9216     */
9217    class FileInstallArgs extends InstallArgs {
9218        private File codeFile;
9219        private File resourceFile;
9220        private File legacyNativeLibraryPath;
9221
9222        // Example topology:
9223        // /data/app/com.example/base.apk
9224        // /data/app/com.example/split_foo.apk
9225        // /data/app/com.example/lib/arm/libfoo.so
9226        // /data/app/com.example/lib/arm64/libfoo.so
9227        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9228
9229        /** New install */
9230        FileInstallArgs(InstallParams params) {
9231            super(params.origin, params.observer, params.installFlags,
9232                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9233                    null /* instruction sets */, params.packageAbiOverride);
9234            if (isFwdLocked()) {
9235                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9236            }
9237        }
9238
9239        /** Existing install */
9240        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9241                String[] instructionSets) {
9242            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9243            this.codeFile = (codePath != null) ? new File(codePath) : null;
9244            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9245            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9246                    new File(legacyNativeLibraryPath) : null;
9247        }
9248
9249        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9250            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9251                    isFwdLocked(), abiOverride);
9252
9253            final StorageManager storage = StorageManager.from(mContext);
9254            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9255        }
9256
9257        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9258            if (origin.staged) {
9259                Slog.d(TAG, origin.file + " already staged; skipping copy");
9260                codeFile = origin.file;
9261                resourceFile = origin.file;
9262                return PackageManager.INSTALL_SUCCEEDED;
9263            }
9264
9265            try {
9266                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9267                codeFile = tempDir;
9268                resourceFile = tempDir;
9269            } catch (IOException e) {
9270                Slog.w(TAG, "Failed to create copy file: " + e);
9271                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9272            }
9273
9274            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9275                @Override
9276                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9277                    if (!FileUtils.isValidExtFilename(name)) {
9278                        throw new IllegalArgumentException("Invalid filename: " + name);
9279                    }
9280                    try {
9281                        final File file = new File(codeFile, name);
9282                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9283                                O_RDWR | O_CREAT, 0644);
9284                        Os.chmod(file.getAbsolutePath(), 0644);
9285                        return new ParcelFileDescriptor(fd);
9286                    } catch (ErrnoException e) {
9287                        throw new RemoteException("Failed to open: " + e.getMessage());
9288                    }
9289                }
9290            };
9291
9292            int ret = PackageManager.INSTALL_SUCCEEDED;
9293            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9294            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9295                Slog.e(TAG, "Failed to copy package");
9296                return ret;
9297            }
9298
9299            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9300            NativeLibraryHelper.Handle handle = null;
9301            try {
9302                handle = NativeLibraryHelper.Handle.create(codeFile);
9303                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9304                        abiOverride);
9305            } catch (IOException e) {
9306                Slog.e(TAG, "Copying native libraries failed", e);
9307                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9308            } finally {
9309                IoUtils.closeQuietly(handle);
9310            }
9311
9312            return ret;
9313        }
9314
9315        int doPreInstall(int status) {
9316            if (status != PackageManager.INSTALL_SUCCEEDED) {
9317                cleanUp();
9318            }
9319            return status;
9320        }
9321
9322        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9323            if (status != PackageManager.INSTALL_SUCCEEDED) {
9324                cleanUp();
9325                return false;
9326            } else {
9327                final File beforeCodeFile = codeFile;
9328                final File afterCodeFile = getNextCodePath(pkg.packageName);
9329
9330                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9331                try {
9332                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9333                } catch (ErrnoException e) {
9334                    Slog.d(TAG, "Failed to rename", e);
9335                    return false;
9336                }
9337
9338                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9339                    Slog.d(TAG, "Failed to restorecon");
9340                    return false;
9341                }
9342
9343                // Reflect the rename internally
9344                codeFile = afterCodeFile;
9345                resourceFile = afterCodeFile;
9346
9347                // Reflect the rename in scanned details
9348                pkg.codePath = afterCodeFile.getAbsolutePath();
9349                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9350                        pkg.baseCodePath);
9351                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9352                        pkg.splitCodePaths);
9353
9354                // Reflect the rename in app info
9355                pkg.applicationInfo.setCodePath(pkg.codePath);
9356                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9357                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9358                pkg.applicationInfo.setResourcePath(pkg.codePath);
9359                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9360                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9361
9362                return true;
9363            }
9364        }
9365
9366        int doPostInstall(int status, int uid) {
9367            if (status != PackageManager.INSTALL_SUCCEEDED) {
9368                cleanUp();
9369            }
9370            return status;
9371        }
9372
9373        @Override
9374        String getCodePath() {
9375            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9376        }
9377
9378        @Override
9379        String getResourcePath() {
9380            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9381        }
9382
9383        @Override
9384        String getLegacyNativeLibraryPath() {
9385            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9386        }
9387
9388        private boolean cleanUp() {
9389            if (codeFile == null || !codeFile.exists()) {
9390                return false;
9391            }
9392
9393            if (codeFile.isDirectory()) {
9394                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
9395            } else {
9396                codeFile.delete();
9397            }
9398
9399            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9400                resourceFile.delete();
9401            }
9402
9403            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9404                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9405                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9406                }
9407                legacyNativeLibraryPath.delete();
9408            }
9409
9410            return true;
9411        }
9412
9413        void cleanUpResourcesLI() {
9414            // Try enumerating all code paths before deleting
9415            List<String> allCodePaths = Collections.EMPTY_LIST;
9416            if (codeFile != null && codeFile.exists()) {
9417                try {
9418                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9419                    allCodePaths = pkg.getAllCodePaths();
9420                } catch (PackageParserException e) {
9421                    // Ignored; we tried our best
9422                }
9423            }
9424
9425            cleanUp();
9426            removeDexFiles(allCodePaths, instructionSets);
9427        }
9428
9429        boolean doPostDeleteLI(boolean delete) {
9430            // XXX err, shouldn't we respect the delete flag?
9431            cleanUpResourcesLI();
9432            return true;
9433        }
9434    }
9435
9436    private boolean isAsecExternal(String cid) {
9437        final String asecPath = PackageHelper.getSdFilesystem(cid);
9438        return !asecPath.startsWith(mAsecInternalPath);
9439    }
9440
9441    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9442            PackageManagerException {
9443        if (copyRet < 0) {
9444            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9445                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9446                throw new PackageManagerException(copyRet, message);
9447            }
9448        }
9449    }
9450
9451    /**
9452     * Extract the MountService "container ID" from the full code path of an
9453     * .apk.
9454     */
9455    static String cidFromCodePath(String fullCodePath) {
9456        int eidx = fullCodePath.lastIndexOf("/");
9457        String subStr1 = fullCodePath.substring(0, eidx);
9458        int sidx = subStr1.lastIndexOf("/");
9459        return subStr1.substring(sidx+1, eidx);
9460    }
9461
9462    /**
9463     * Logic to handle installation of ASEC applications, including copying and
9464     * renaming logic.
9465     */
9466    class AsecInstallArgs extends InstallArgs {
9467        static final String RES_FILE_NAME = "pkg.apk";
9468        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9469
9470        String cid;
9471        String packagePath;
9472        String resourcePath;
9473        String legacyNativeLibraryDir;
9474
9475        /** New install */
9476        AsecInstallArgs(InstallParams params) {
9477            super(params.origin, params.observer, params.installFlags,
9478                    params.installerPackageName, params.getManifestDigest(),
9479                    params.getUser(), null /* instruction sets */,
9480                    params.packageAbiOverride);
9481        }
9482
9483        /** Existing install */
9484        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9485                        boolean isExternal, boolean isForwardLocked) {
9486            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9487                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9488                    instructionSets, null);
9489            // Hackily pretend we're still looking at a full code path
9490            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9491                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9492            }
9493
9494            // Extract cid from fullCodePath
9495            int eidx = fullCodePath.lastIndexOf("/");
9496            String subStr1 = fullCodePath.substring(0, eidx);
9497            int sidx = subStr1.lastIndexOf("/");
9498            cid = subStr1.substring(sidx+1, eidx);
9499            setMountPath(subStr1);
9500        }
9501
9502        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9503            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9504                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9505                    instructionSets, null);
9506            this.cid = cid;
9507            setMountPath(PackageHelper.getSdDir(cid));
9508        }
9509
9510        void createCopyFile() {
9511            cid = mInstallerService.allocateExternalStageCidLegacy();
9512        }
9513
9514        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9515            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9516                    abiOverride);
9517
9518            final File target;
9519            if (isExternal()) {
9520                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9521            } else {
9522                target = Environment.getDataDirectory();
9523            }
9524
9525            final StorageManager storage = StorageManager.from(mContext);
9526            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9527        }
9528
9529        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9530            if (origin.staged) {
9531                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9532                cid = origin.cid;
9533                setMountPath(PackageHelper.getSdDir(cid));
9534                return PackageManager.INSTALL_SUCCEEDED;
9535            }
9536
9537            if (temp) {
9538                createCopyFile();
9539            } else {
9540                /*
9541                 * Pre-emptively destroy the container since it's destroyed if
9542                 * copying fails due to it existing anyway.
9543                 */
9544                PackageHelper.destroySdDir(cid);
9545            }
9546
9547            final String newMountPath = imcs.copyPackageToContainer(
9548                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9549                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9550
9551            if (newMountPath != null) {
9552                setMountPath(newMountPath);
9553                return PackageManager.INSTALL_SUCCEEDED;
9554            } else {
9555                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9556            }
9557        }
9558
9559        @Override
9560        String getCodePath() {
9561            return packagePath;
9562        }
9563
9564        @Override
9565        String getResourcePath() {
9566            return resourcePath;
9567        }
9568
9569        @Override
9570        String getLegacyNativeLibraryPath() {
9571            return legacyNativeLibraryDir;
9572        }
9573
9574        int doPreInstall(int status) {
9575            if (status != PackageManager.INSTALL_SUCCEEDED) {
9576                // Destroy container
9577                PackageHelper.destroySdDir(cid);
9578            } else {
9579                boolean mounted = PackageHelper.isContainerMounted(cid);
9580                if (!mounted) {
9581                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9582                            Process.SYSTEM_UID);
9583                    if (newMountPath != null) {
9584                        setMountPath(newMountPath);
9585                    } else {
9586                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9587                    }
9588                }
9589            }
9590            return status;
9591        }
9592
9593        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9594            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9595            String newMountPath = null;
9596            if (PackageHelper.isContainerMounted(cid)) {
9597                // Unmount the container
9598                if (!PackageHelper.unMountSdDir(cid)) {
9599                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9600                    return false;
9601                }
9602            }
9603            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9604                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9605                        " which might be stale. Will try to clean up.");
9606                // Clean up the stale container and proceed to recreate.
9607                if (!PackageHelper.destroySdDir(newCacheId)) {
9608                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9609                    return false;
9610                }
9611                // Successfully cleaned up stale container. Try to rename again.
9612                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9613                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9614                            + " inspite of cleaning it up.");
9615                    return false;
9616                }
9617            }
9618            if (!PackageHelper.isContainerMounted(newCacheId)) {
9619                Slog.w(TAG, "Mounting container " + newCacheId);
9620                newMountPath = PackageHelper.mountSdDir(newCacheId,
9621                        getEncryptKey(), Process.SYSTEM_UID);
9622            } else {
9623                newMountPath = PackageHelper.getSdDir(newCacheId);
9624            }
9625            if (newMountPath == null) {
9626                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9627                return false;
9628            }
9629            Log.i(TAG, "Succesfully renamed " + cid +
9630                    " to " + newCacheId +
9631                    " at new path: " + newMountPath);
9632            cid = newCacheId;
9633
9634            final File beforeCodeFile = new File(packagePath);
9635            setMountPath(newMountPath);
9636            final File afterCodeFile = new File(packagePath);
9637
9638            // Reflect the rename in scanned details
9639            pkg.codePath = afterCodeFile.getAbsolutePath();
9640            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9641                    pkg.baseCodePath);
9642            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9643                    pkg.splitCodePaths);
9644
9645            // Reflect the rename in app info
9646            pkg.applicationInfo.setCodePath(pkg.codePath);
9647            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9648            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9649            pkg.applicationInfo.setResourcePath(pkg.codePath);
9650            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9651            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9652
9653            return true;
9654        }
9655
9656        private void setMountPath(String mountPath) {
9657            final File mountFile = new File(mountPath);
9658
9659            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9660            if (monolithicFile.exists()) {
9661                packagePath = monolithicFile.getAbsolutePath();
9662                if (isFwdLocked()) {
9663                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9664                } else {
9665                    resourcePath = packagePath;
9666                }
9667            } else {
9668                packagePath = mountFile.getAbsolutePath();
9669                resourcePath = packagePath;
9670            }
9671
9672            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9673        }
9674
9675        int doPostInstall(int status, int uid) {
9676            if (status != PackageManager.INSTALL_SUCCEEDED) {
9677                cleanUp();
9678            } else {
9679                final int groupOwner;
9680                final String protectedFile;
9681                if (isFwdLocked()) {
9682                    groupOwner = UserHandle.getSharedAppGid(uid);
9683                    protectedFile = RES_FILE_NAME;
9684                } else {
9685                    groupOwner = -1;
9686                    protectedFile = null;
9687                }
9688
9689                if (uid < Process.FIRST_APPLICATION_UID
9690                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9691                    Slog.e(TAG, "Failed to finalize " + cid);
9692                    PackageHelper.destroySdDir(cid);
9693                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9694                }
9695
9696                boolean mounted = PackageHelper.isContainerMounted(cid);
9697                if (!mounted) {
9698                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9699                }
9700            }
9701            return status;
9702        }
9703
9704        private void cleanUp() {
9705            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9706
9707            // Destroy secure container
9708            PackageHelper.destroySdDir(cid);
9709        }
9710
9711        private List<String> getAllCodePaths() {
9712            final File codeFile = new File(getCodePath());
9713            if (codeFile != null && codeFile.exists()) {
9714                try {
9715                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9716                    return pkg.getAllCodePaths();
9717                } catch (PackageParserException e) {
9718                    // Ignored; we tried our best
9719                }
9720            }
9721            return Collections.EMPTY_LIST;
9722        }
9723
9724        void cleanUpResourcesLI() {
9725            // Enumerate all code paths before deleting
9726            cleanUpResourcesLI(getAllCodePaths());
9727        }
9728
9729        private void cleanUpResourcesLI(List<String> allCodePaths) {
9730            cleanUp();
9731            removeDexFiles(allCodePaths, instructionSets);
9732        }
9733
9734
9735
9736        String getPackageName() {
9737            return getAsecPackageName(cid);
9738        }
9739
9740        boolean doPostDeleteLI(boolean delete) {
9741            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9742            final List<String> allCodePaths = getAllCodePaths();
9743            boolean mounted = PackageHelper.isContainerMounted(cid);
9744            if (mounted) {
9745                // Unmount first
9746                if (PackageHelper.unMountSdDir(cid)) {
9747                    mounted = false;
9748                }
9749            }
9750            if (!mounted && delete) {
9751                cleanUpResourcesLI(allCodePaths);
9752            }
9753            return !mounted;
9754        }
9755
9756        @Override
9757        int doPreCopy() {
9758            if (isFwdLocked()) {
9759                if (!PackageHelper.fixSdPermissions(cid,
9760                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9761                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9762                }
9763            }
9764
9765            return PackageManager.INSTALL_SUCCEEDED;
9766        }
9767
9768        @Override
9769        int doPostCopy(int uid) {
9770            if (isFwdLocked()) {
9771                if (uid < Process.FIRST_APPLICATION_UID
9772                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9773                                RES_FILE_NAME)) {
9774                    Slog.e(TAG, "Failed to finalize " + cid);
9775                    PackageHelper.destroySdDir(cid);
9776                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9777                }
9778            }
9779
9780            return PackageManager.INSTALL_SUCCEEDED;
9781        }
9782    }
9783
9784    static String getAsecPackageName(String packageCid) {
9785        int idx = packageCid.lastIndexOf("-");
9786        if (idx == -1) {
9787            return packageCid;
9788        }
9789        return packageCid.substring(0, idx);
9790    }
9791
9792    // Utility method used to create code paths based on package name and available index.
9793    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9794        String idxStr = "";
9795        int idx = 1;
9796        // Fall back to default value of idx=1 if prefix is not
9797        // part of oldCodePath
9798        if (oldCodePath != null) {
9799            String subStr = oldCodePath;
9800            // Drop the suffix right away
9801            if (suffix != null && subStr.endsWith(suffix)) {
9802                subStr = subStr.substring(0, subStr.length() - suffix.length());
9803            }
9804            // If oldCodePath already contains prefix find out the
9805            // ending index to either increment or decrement.
9806            int sidx = subStr.lastIndexOf(prefix);
9807            if (sidx != -1) {
9808                subStr = subStr.substring(sidx + prefix.length());
9809                if (subStr != null) {
9810                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9811                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9812                    }
9813                    try {
9814                        idx = Integer.parseInt(subStr);
9815                        if (idx <= 1) {
9816                            idx++;
9817                        } else {
9818                            idx--;
9819                        }
9820                    } catch(NumberFormatException e) {
9821                    }
9822                }
9823            }
9824        }
9825        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9826        return prefix + idxStr;
9827    }
9828
9829    private File getNextCodePath(String packageName) {
9830        int suffix = 1;
9831        File result;
9832        do {
9833            result = new File(mAppInstallDir, packageName + "-" + suffix);
9834            suffix++;
9835        } while (result.exists());
9836        return result;
9837    }
9838
9839    // Utility method that returns the relative package path with respect
9840    // to the installation directory. Like say for /data/data/com.test-1.apk
9841    // string com.test-1 is returned.
9842    static String deriveCodePathName(String codePath) {
9843        if (codePath == null) {
9844            return null;
9845        }
9846        final File codeFile = new File(codePath);
9847        final String name = codeFile.getName();
9848        if (codeFile.isDirectory()) {
9849            return name;
9850        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9851            final int lastDot = name.lastIndexOf('.');
9852            return name.substring(0, lastDot);
9853        } else {
9854            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9855            return null;
9856        }
9857    }
9858
9859    class PackageInstalledInfo {
9860        String name;
9861        int uid;
9862        // The set of users that originally had this package installed.
9863        int[] origUsers;
9864        // The set of users that now have this package installed.
9865        int[] newUsers;
9866        PackageParser.Package pkg;
9867        int returnCode;
9868        String returnMsg;
9869        PackageRemovedInfo removedInfo;
9870
9871        public void setError(int code, String msg) {
9872            returnCode = code;
9873            returnMsg = msg;
9874            Slog.w(TAG, msg);
9875        }
9876
9877        public void setError(String msg, PackageParserException e) {
9878            returnCode = e.error;
9879            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9880            Slog.w(TAG, msg, e);
9881        }
9882
9883        public void setError(String msg, PackageManagerException e) {
9884            returnCode = e.error;
9885            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9886            Slog.w(TAG, msg, e);
9887        }
9888
9889        // In some error cases we want to convey more info back to the observer
9890        String origPackage;
9891        String origPermission;
9892    }
9893
9894    /*
9895     * Install a non-existing package.
9896     */
9897    private void installNewPackageLI(PackageParser.Package pkg,
9898            int parseFlags, int scanFlags, UserHandle user,
9899            String installerPackageName, PackageInstalledInfo res) {
9900        // Remember this for later, in case we need to rollback this install
9901        String pkgName = pkg.packageName;
9902
9903        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9904        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9905        synchronized(mPackages) {
9906            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9907                // A package with the same name is already installed, though
9908                // it has been renamed to an older name.  The package we
9909                // are trying to install should be installed as an update to
9910                // the existing one, but that has not been requested, so bail.
9911                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9912                        + " without first uninstalling package running as "
9913                        + mSettings.mRenamedPackages.get(pkgName));
9914                return;
9915            }
9916            if (mPackages.containsKey(pkgName)) {
9917                // Don't allow installation over an existing package with the same name.
9918                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9919                        + " without first uninstalling.");
9920                return;
9921            }
9922        }
9923
9924        try {
9925            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9926                    System.currentTimeMillis(), user);
9927
9928            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9929            // delete the partially installed application. the data directory will have to be
9930            // restored if it was already existing
9931            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9932                // remove package from internal structures.  Note that we want deletePackageX to
9933                // delete the package data and cache directories that it created in
9934                // scanPackageLocked, unless those directories existed before we even tried to
9935                // install.
9936                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9937                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9938                                res.removedInfo, true);
9939            }
9940
9941        } catch (PackageManagerException e) {
9942            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9943        }
9944    }
9945
9946    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9947        // Upgrade keysets are being used.  Determine if new package has a superset of the
9948        // required keys.
9949        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9950        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9951        for (int i = 0; i < upgradeKeySets.length; i++) {
9952            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9953            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9954                return true;
9955            }
9956        }
9957        return false;
9958    }
9959
9960    private void replacePackageLI(PackageParser.Package pkg,
9961            int parseFlags, int scanFlags, UserHandle user,
9962            String installerPackageName, PackageInstalledInfo res) {
9963        PackageParser.Package oldPackage;
9964        String pkgName = pkg.packageName;
9965        int[] allUsers;
9966        boolean[] perUserInstalled;
9967
9968        // First find the old package info and check signatures
9969        synchronized(mPackages) {
9970            oldPackage = mPackages.get(pkgName);
9971            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9972            PackageSetting ps = mSettings.mPackages.get(pkgName);
9973            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9974                // default to original signature matching
9975                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9976                    != PackageManager.SIGNATURE_MATCH) {
9977                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9978                            "New package has a different signature: " + pkgName);
9979                    return;
9980                }
9981            } else {
9982                if(!checkUpgradeKeySetLP(ps, pkg)) {
9983                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
9984                            "New package not signed by keys specified by upgrade-keysets: "
9985                            + pkgName);
9986                    return;
9987                }
9988            }
9989
9990            // In case of rollback, remember per-user/profile install state
9991            allUsers = sUserManager.getUserIds();
9992            perUserInstalled = new boolean[allUsers.length];
9993            for (int i = 0; i < allUsers.length; i++) {
9994                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9995            }
9996        }
9997
9998        boolean sysPkg = (isSystemApp(oldPackage));
9999        if (sysPkg) {
10000            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10001                    user, allUsers, perUserInstalled, installerPackageName, res);
10002        } else {
10003            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10004                    user, allUsers, perUserInstalled, installerPackageName, res);
10005        }
10006    }
10007
10008    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10009            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10010            int[] allUsers, boolean[] perUserInstalled,
10011            String installerPackageName, PackageInstalledInfo res) {
10012        String pkgName = deletedPackage.packageName;
10013        boolean deletedPkg = true;
10014        boolean updatedSettings = false;
10015
10016        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10017                + deletedPackage);
10018        long origUpdateTime;
10019        if (pkg.mExtras != null) {
10020            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10021        } else {
10022            origUpdateTime = 0;
10023        }
10024
10025        // First delete the existing package while retaining the data directory
10026        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10027                res.removedInfo, true)) {
10028            // If the existing package wasn't successfully deleted
10029            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10030            deletedPkg = false;
10031        } else {
10032            // Successfully deleted the old package; proceed with replace.
10033
10034            // If deleted package lived in a container, give users a chance to
10035            // relinquish resources before killing.
10036            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
10037                if (DEBUG_INSTALL) {
10038                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10039                }
10040                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10041                final ArrayList<String> pkgList = new ArrayList<String>(1);
10042                pkgList.add(deletedPackage.applicationInfo.packageName);
10043                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10044            }
10045
10046            deleteCodeCacheDirsLI(pkgName);
10047            try {
10048                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10049                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10050                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10051                updatedSettings = true;
10052            } catch (PackageManagerException e) {
10053                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10054            }
10055        }
10056
10057        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10058            // remove package from internal structures.  Note that we want deletePackageX to
10059            // delete the package data and cache directories that it created in
10060            // scanPackageLocked, unless those directories existed before we even tried to
10061            // install.
10062            if(updatedSettings) {
10063                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10064                deletePackageLI(
10065                        pkgName, null, true, allUsers, perUserInstalled,
10066                        PackageManager.DELETE_KEEP_DATA,
10067                                res.removedInfo, true);
10068            }
10069            // Since we failed to install the new package we need to restore the old
10070            // package that we deleted.
10071            if (deletedPkg) {
10072                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10073                File restoreFile = new File(deletedPackage.codePath);
10074                // Parse old package
10075                boolean oldOnSd = isExternal(deletedPackage);
10076                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10077                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10078                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10079                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10080                try {
10081                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10082                } catch (PackageManagerException e) {
10083                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10084                            + e.getMessage());
10085                    return;
10086                }
10087                // Restore of old package succeeded. Update permissions.
10088                // writer
10089                synchronized (mPackages) {
10090                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10091                            UPDATE_PERMISSIONS_ALL);
10092                    // can downgrade to reader
10093                    mSettings.writeLPr();
10094                }
10095                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10096            }
10097        }
10098    }
10099
10100    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10101            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10102            int[] allUsers, boolean[] perUserInstalled,
10103            String installerPackageName, PackageInstalledInfo res) {
10104        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10105                + ", old=" + deletedPackage);
10106        boolean disabledSystem = false;
10107        boolean updatedSettings = false;
10108        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10109        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
10110                != 0) {
10111            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10112        }
10113        String packageName = deletedPackage.packageName;
10114        if (packageName == null) {
10115            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10116                    "Attempt to delete null packageName.");
10117            return;
10118        }
10119        PackageParser.Package oldPkg;
10120        PackageSetting oldPkgSetting;
10121        // reader
10122        synchronized (mPackages) {
10123            oldPkg = mPackages.get(packageName);
10124            oldPkgSetting = mSettings.mPackages.get(packageName);
10125            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10126                    (oldPkgSetting == null)) {
10127                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10128                        "Couldn't find package:" + packageName + " information");
10129                return;
10130            }
10131        }
10132
10133        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10134
10135        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10136        res.removedInfo.removedPackage = packageName;
10137        // Remove existing system package
10138        removePackageLI(oldPkgSetting, true);
10139        // writer
10140        synchronized (mPackages) {
10141            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10142            if (!disabledSystem && deletedPackage != null) {
10143                // We didn't need to disable the .apk as a current system package,
10144                // which means we are replacing another update that is already
10145                // installed.  We need to make sure to delete the older one's .apk.
10146                res.removedInfo.args = createInstallArgsForExisting(0,
10147                        deletedPackage.applicationInfo.getCodePath(),
10148                        deletedPackage.applicationInfo.getResourcePath(),
10149                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10150                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10151            } else {
10152                res.removedInfo.args = null;
10153            }
10154        }
10155
10156        // Successfully disabled the old package. Now proceed with re-installation
10157        deleteCodeCacheDirsLI(packageName);
10158
10159        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10160        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10161
10162        PackageParser.Package newPackage = null;
10163        try {
10164            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10165            if (newPackage.mExtras != null) {
10166                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10167                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10168                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10169
10170                // is the update attempting to change shared user? that isn't going to work...
10171                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10172                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10173                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10174                            + " to " + newPkgSetting.sharedUser);
10175                    updatedSettings = true;
10176                }
10177            }
10178
10179            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10180                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10181                updatedSettings = true;
10182            }
10183
10184        } catch (PackageManagerException e) {
10185            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10186        }
10187
10188        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10189            // Re installation failed. Restore old information
10190            // Remove new pkg information
10191            if (newPackage != null) {
10192                removeInstalledPackageLI(newPackage, true);
10193            }
10194            // Add back the old system package
10195            try {
10196                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10197            } catch (PackageManagerException e) {
10198                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10199            }
10200            // Restore the old system information in Settings
10201            synchronized (mPackages) {
10202                if (disabledSystem) {
10203                    mSettings.enableSystemPackageLPw(packageName);
10204                }
10205                if (updatedSettings) {
10206                    mSettings.setInstallerPackageName(packageName,
10207                            oldPkgSetting.installerPackageName);
10208                }
10209                mSettings.writeLPr();
10210            }
10211        }
10212    }
10213
10214    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10215            int[] allUsers, boolean[] perUserInstalled,
10216            PackageInstalledInfo res) {
10217        String pkgName = newPackage.packageName;
10218        synchronized (mPackages) {
10219            //write settings. the installStatus will be incomplete at this stage.
10220            //note that the new package setting would have already been
10221            //added to mPackages. It hasn't been persisted yet.
10222            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10223            mSettings.writeLPr();
10224        }
10225
10226        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10227
10228        synchronized (mPackages) {
10229            updatePermissionsLPw(newPackage.packageName, newPackage,
10230                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10231                            ? UPDATE_PERMISSIONS_ALL : 0));
10232            // For system-bundled packages, we assume that installing an upgraded version
10233            // of the package implies that the user actually wants to run that new code,
10234            // so we enable the package.
10235            if (isSystemApp(newPackage)) {
10236                // NB: implicit assumption that system package upgrades apply to all users
10237                if (DEBUG_INSTALL) {
10238                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10239                }
10240                PackageSetting ps = mSettings.mPackages.get(pkgName);
10241                if (ps != null) {
10242                    if (res.origUsers != null) {
10243                        for (int userHandle : res.origUsers) {
10244                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10245                                    userHandle, installerPackageName);
10246                        }
10247                    }
10248                    // Also convey the prior install/uninstall state
10249                    if (allUsers != null && perUserInstalled != null) {
10250                        for (int i = 0; i < allUsers.length; i++) {
10251                            if (DEBUG_INSTALL) {
10252                                Slog.d(TAG, "    user " + allUsers[i]
10253                                        + " => " + perUserInstalled[i]);
10254                            }
10255                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10256                        }
10257                        // these install state changes will be persisted in the
10258                        // upcoming call to mSettings.writeLPr().
10259                    }
10260                }
10261            }
10262            res.name = pkgName;
10263            res.uid = newPackage.applicationInfo.uid;
10264            res.pkg = newPackage;
10265            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10266            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10267            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10268            //to update install status
10269            mSettings.writeLPr();
10270        }
10271    }
10272
10273    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10274        final int installFlags = args.installFlags;
10275        String installerPackageName = args.installerPackageName;
10276        File tmpPackageFile = new File(args.getCodePath());
10277        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10278        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10279        boolean replace = false;
10280        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10281        // Result object to be returned
10282        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10283
10284        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10285        // Retrieve PackageSettings and parse package
10286        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10287                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10288                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10289        PackageParser pp = new PackageParser();
10290        pp.setSeparateProcesses(mSeparateProcesses);
10291        pp.setDisplayMetrics(mMetrics);
10292
10293        final PackageParser.Package pkg;
10294        try {
10295            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10296        } catch (PackageParserException e) {
10297            res.setError("Failed parse during installPackageLI", e);
10298            return;
10299        }
10300
10301        // Mark that we have an install time CPU ABI override.
10302        pkg.cpuAbiOverride = args.abiOverride;
10303
10304        String pkgName = res.name = pkg.packageName;
10305        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10306            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10307                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10308                return;
10309            }
10310        }
10311
10312        try {
10313            pp.collectCertificates(pkg, parseFlags);
10314            pp.collectManifestDigest(pkg);
10315        } catch (PackageParserException e) {
10316            res.setError("Failed collect during installPackageLI", e);
10317            return;
10318        }
10319
10320        /* If the installer passed in a manifest digest, compare it now. */
10321        if (args.manifestDigest != null) {
10322            if (DEBUG_INSTALL) {
10323                final String parsedManifest = pkg.manifestDigest == null ? "null"
10324                        : pkg.manifestDigest.toString();
10325                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10326                        + parsedManifest);
10327            }
10328
10329            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10330                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10331                return;
10332            }
10333        } else if (DEBUG_INSTALL) {
10334            final String parsedManifest = pkg.manifestDigest == null
10335                    ? "null" : pkg.manifestDigest.toString();
10336            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10337        }
10338
10339        // Get rid of all references to package scan path via parser.
10340        pp = null;
10341        String oldCodePath = null;
10342        boolean systemApp = false;
10343        synchronized (mPackages) {
10344            // Check if installing already existing package
10345            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10346                String oldName = mSettings.mRenamedPackages.get(pkgName);
10347                if (pkg.mOriginalPackages != null
10348                        && pkg.mOriginalPackages.contains(oldName)
10349                        && mPackages.containsKey(oldName)) {
10350                    // This package is derived from an original package,
10351                    // and this device has been updating from that original
10352                    // name.  We must continue using the original name, so
10353                    // rename the new package here.
10354                    pkg.setPackageName(oldName);
10355                    pkgName = pkg.packageName;
10356                    replace = true;
10357                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10358                            + oldName + " pkgName=" + pkgName);
10359                } else if (mPackages.containsKey(pkgName)) {
10360                    // This package, under its official name, already exists
10361                    // on the device; we should replace it.
10362                    replace = true;
10363                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10364                }
10365            }
10366
10367            PackageSetting ps = mSettings.mPackages.get(pkgName);
10368            if (ps != null) {
10369                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10370
10371                // Quick sanity check that we're signed correctly if updating;
10372                // we'll check this again later when scanning, but we want to
10373                // bail early here before tripping over redefined permissions.
10374                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10375                    try {
10376                        verifySignaturesLP(ps, pkg);
10377                    } catch (PackageManagerException e) {
10378                        res.setError(e.error, e.getMessage());
10379                        return;
10380                    }
10381                } else {
10382                    if (!checkUpgradeKeySetLP(ps, pkg)) {
10383                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
10384                                + pkg.packageName + " upgrade keys do not match the "
10385                                + "previously installed version");
10386                        return;
10387                    }
10388                }
10389
10390                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10391                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10392                    systemApp = (ps.pkg.applicationInfo.flags &
10393                            ApplicationInfo.FLAG_SYSTEM) != 0;
10394                }
10395                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10396            }
10397
10398            // Check whether the newly-scanned package wants to define an already-defined perm
10399            int N = pkg.permissions.size();
10400            for (int i = N-1; i >= 0; i--) {
10401                PackageParser.Permission perm = pkg.permissions.get(i);
10402                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10403                if (bp != null) {
10404                    // If the defining package is signed with our cert, it's okay.  This
10405                    // also includes the "updating the same package" case, of course.
10406                    // "updating same package" could also involve key-rotation.
10407                    final boolean sigsOk;
10408                    if (!bp.sourcePackage.equals(pkg.packageName)
10409                            || !(bp.packageSetting instanceof PackageSetting)
10410                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10411                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10412                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10413                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10414                    } else {
10415                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10416                    }
10417                    if (!sigsOk) {
10418                        // If the owning package is the system itself, we log but allow
10419                        // install to proceed; we fail the install on all other permission
10420                        // redefinitions.
10421                        if (!bp.sourcePackage.equals("android")) {
10422                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10423                                    + pkg.packageName + " attempting to redeclare permission "
10424                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10425                            res.origPermission = perm.info.name;
10426                            res.origPackage = bp.sourcePackage;
10427                            return;
10428                        } else {
10429                            Slog.w(TAG, "Package " + pkg.packageName
10430                                    + " attempting to redeclare system permission "
10431                                    + perm.info.name + "; ignoring new declaration");
10432                            pkg.permissions.remove(i);
10433                        }
10434                    }
10435                }
10436            }
10437
10438        }
10439
10440        if (systemApp && onSd) {
10441            // Disable updates to system apps on sdcard
10442            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10443                    "Cannot install updates to system apps on sdcard");
10444            return;
10445        }
10446
10447        // Run dexopt before old package gets removed, to minimize time when app is not available
10448        int result = mPackageDexOptimizer
10449                .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */,
10450                        false /* defer */, false /* inclDependencies */);
10451        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
10452            res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
10453            return;
10454        }
10455
10456        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10457            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10458            return;
10459        }
10460
10461        // Call with SCAN_NO_DEX, since dexopt has already been made
10462        if (replace) {
10463            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING | SCAN_NO_DEX, args.user,
10464                    installerPackageName, res);
10465        } else {
10466            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES
10467                            | SCAN_NO_DEX, args.user, installerPackageName, res);
10468        }
10469        synchronized (mPackages) {
10470            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10471            if (ps != null) {
10472                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10473            }
10474        }
10475    }
10476
10477    private static boolean isMultiArch(PackageSetting ps) {
10478        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10479    }
10480
10481    private static boolean isMultiArch(ApplicationInfo info) {
10482        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10483    }
10484
10485    private static boolean isExternal(PackageParser.Package pkg) {
10486        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10487    }
10488
10489    private static boolean isExternal(PackageSetting ps) {
10490        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10491    }
10492
10493    private static boolean isExternal(ApplicationInfo info) {
10494        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10495    }
10496
10497    private static boolean isSystemApp(PackageParser.Package pkg) {
10498        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10499    }
10500
10501    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10502        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
10503    }
10504
10505    private static boolean isSystemApp(PackageSetting ps) {
10506        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10507    }
10508
10509    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10510        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10511    }
10512
10513    private int packageFlagsToInstallFlags(PackageSetting ps) {
10514        int installFlags = 0;
10515        if (isExternal(ps)) {
10516            installFlags |= PackageManager.INSTALL_EXTERNAL;
10517        }
10518        if (ps.isForwardLocked()) {
10519            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10520        }
10521        return installFlags;
10522    }
10523
10524    private void deleteTempPackageFiles() {
10525        final FilenameFilter filter = new FilenameFilter() {
10526            public boolean accept(File dir, String name) {
10527                return name.startsWith("vmdl") && name.endsWith(".tmp");
10528            }
10529        };
10530        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10531            file.delete();
10532        }
10533    }
10534
10535    @Override
10536    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10537            int flags) {
10538        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10539                flags);
10540    }
10541
10542    @Override
10543    public void deletePackage(final String packageName,
10544            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10545        mContext.enforceCallingOrSelfPermission(
10546                android.Manifest.permission.DELETE_PACKAGES, null);
10547        final int uid = Binder.getCallingUid();
10548        if (UserHandle.getUserId(uid) != userId) {
10549            mContext.enforceCallingPermission(
10550                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10551                    "deletePackage for user " + userId);
10552        }
10553        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10554            try {
10555                observer.onPackageDeleted(packageName,
10556                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10557            } catch (RemoteException re) {
10558            }
10559            return;
10560        }
10561
10562        boolean uninstallBlocked = false;
10563        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10564            int[] users = sUserManager.getUserIds();
10565            for (int i = 0; i < users.length; ++i) {
10566                if (getBlockUninstallForUser(packageName, users[i])) {
10567                    uninstallBlocked = true;
10568                    break;
10569                }
10570            }
10571        } else {
10572            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10573        }
10574        if (uninstallBlocked) {
10575            try {
10576                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10577                        null);
10578            } catch (RemoteException re) {
10579            }
10580            return;
10581        }
10582
10583        if (DEBUG_REMOVE) {
10584            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10585        }
10586        // Queue up an async operation since the package deletion may take a little while.
10587        mHandler.post(new Runnable() {
10588            public void run() {
10589                mHandler.removeCallbacks(this);
10590                final int returnCode = deletePackageX(packageName, userId, flags);
10591                if (observer != null) {
10592                    try {
10593                        observer.onPackageDeleted(packageName, returnCode, null);
10594                    } catch (RemoteException e) {
10595                        Log.i(TAG, "Observer no longer exists.");
10596                    } //end catch
10597                } //end if
10598            } //end run
10599        });
10600    }
10601
10602    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10603        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10604                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10605        try {
10606            if (dpm != null) {
10607                if (dpm.isDeviceOwner(packageName)) {
10608                    return true;
10609                }
10610                int[] users;
10611                if (userId == UserHandle.USER_ALL) {
10612                    users = sUserManager.getUserIds();
10613                } else {
10614                    users = new int[]{userId};
10615                }
10616                for (int i = 0; i < users.length; ++i) {
10617                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10618                        return true;
10619                    }
10620                }
10621            }
10622        } catch (RemoteException e) {
10623        }
10624        return false;
10625    }
10626
10627    /**
10628     *  This method is an internal method that could be get invoked either
10629     *  to delete an installed package or to clean up a failed installation.
10630     *  After deleting an installed package, a broadcast is sent to notify any
10631     *  listeners that the package has been installed. For cleaning up a failed
10632     *  installation, the broadcast is not necessary since the package's
10633     *  installation wouldn't have sent the initial broadcast either
10634     *  The key steps in deleting a package are
10635     *  deleting the package information in internal structures like mPackages,
10636     *  deleting the packages base directories through installd
10637     *  updating mSettings to reflect current status
10638     *  persisting settings for later use
10639     *  sending a broadcast if necessary
10640     */
10641    private int deletePackageX(String packageName, int userId, int flags) {
10642        final PackageRemovedInfo info = new PackageRemovedInfo();
10643        final boolean res;
10644
10645        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10646                ? UserHandle.ALL : new UserHandle(userId);
10647
10648        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10649            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10650            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10651        }
10652
10653        boolean removedForAllUsers = false;
10654        boolean systemUpdate = false;
10655
10656        // for the uninstall-updates case and restricted profiles, remember the per-
10657        // userhandle installed state
10658        int[] allUsers;
10659        boolean[] perUserInstalled;
10660        synchronized (mPackages) {
10661            PackageSetting ps = mSettings.mPackages.get(packageName);
10662            allUsers = sUserManager.getUserIds();
10663            perUserInstalled = new boolean[allUsers.length];
10664            for (int i = 0; i < allUsers.length; i++) {
10665                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10666            }
10667        }
10668
10669        synchronized (mInstallLock) {
10670            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10671            res = deletePackageLI(packageName, removeForUser,
10672                    true, allUsers, perUserInstalled,
10673                    flags | REMOVE_CHATTY, info, true);
10674            systemUpdate = info.isRemovedPackageSystemUpdate;
10675            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10676                removedForAllUsers = true;
10677            }
10678            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10679                    + " removedForAllUsers=" + removedForAllUsers);
10680        }
10681
10682        if (res) {
10683            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10684
10685            // If the removed package was a system update, the old system package
10686            // was re-enabled; we need to broadcast this information
10687            if (systemUpdate) {
10688                Bundle extras = new Bundle(1);
10689                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10690                        ? info.removedAppId : info.uid);
10691                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10692
10693                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10694                        extras, null, null, null);
10695                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10696                        extras, null, null, null);
10697                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10698                        null, packageName, null, null);
10699            }
10700        }
10701        // Force a gc here.
10702        Runtime.getRuntime().gc();
10703        // Delete the resources here after sending the broadcast to let
10704        // other processes clean up before deleting resources.
10705        if (info.args != null) {
10706            synchronized (mInstallLock) {
10707                info.args.doPostDeleteLI(true);
10708            }
10709        }
10710
10711        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10712    }
10713
10714    static class PackageRemovedInfo {
10715        String removedPackage;
10716        int uid = -1;
10717        int removedAppId = -1;
10718        int[] removedUsers = null;
10719        boolean isRemovedPackageSystemUpdate = false;
10720        // Clean up resources deleted packages.
10721        InstallArgs args = null;
10722
10723        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10724            Bundle extras = new Bundle(1);
10725            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10726            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10727            if (replacing) {
10728                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10729            }
10730            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10731            if (removedPackage != null) {
10732                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10733                        extras, null, null, removedUsers);
10734                if (fullRemove && !replacing) {
10735                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10736                            extras, null, null, removedUsers);
10737                }
10738            }
10739            if (removedAppId >= 0) {
10740                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10741                        removedUsers);
10742            }
10743        }
10744    }
10745
10746    /*
10747     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10748     * flag is not set, the data directory is removed as well.
10749     * make sure this flag is set for partially installed apps. If not its meaningless to
10750     * delete a partially installed application.
10751     */
10752    private void removePackageDataLI(PackageSetting ps,
10753            int[] allUserHandles, boolean[] perUserInstalled,
10754            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10755        String packageName = ps.name;
10756        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10757        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10758        // Retrieve object to delete permissions for shared user later on
10759        final PackageSetting deletedPs;
10760        // reader
10761        synchronized (mPackages) {
10762            deletedPs = mSettings.mPackages.get(packageName);
10763            if (outInfo != null) {
10764                outInfo.removedPackage = packageName;
10765                outInfo.removedUsers = deletedPs != null
10766                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10767                        : null;
10768            }
10769        }
10770        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10771            removeDataDirsLI(packageName);
10772            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10773        }
10774        // writer
10775        synchronized (mPackages) {
10776            if (deletedPs != null) {
10777                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10778                    if (outInfo != null) {
10779                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10780                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10781                    }
10782                    if (deletedPs != null) {
10783                        updatePermissionsLPw(deletedPs.name, null, 0);
10784                        if (deletedPs.sharedUser != null) {
10785                            // remove permissions associated with package
10786                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10787                        }
10788                    }
10789                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10790                }
10791                // make sure to preserve per-user disabled state if this removal was just
10792                // a downgrade of a system app to the factory package
10793                if (allUserHandles != null && perUserInstalled != null) {
10794                    if (DEBUG_REMOVE) {
10795                        Slog.d(TAG, "Propagating install state across downgrade");
10796                    }
10797                    for (int i = 0; i < allUserHandles.length; i++) {
10798                        if (DEBUG_REMOVE) {
10799                            Slog.d(TAG, "    user " + allUserHandles[i]
10800                                    + " => " + perUserInstalled[i]);
10801                        }
10802                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10803                    }
10804                }
10805            }
10806            // can downgrade to reader
10807            if (writeSettings) {
10808                // Save settings now
10809                mSettings.writeLPr();
10810            }
10811        }
10812        if (outInfo != null) {
10813            // A user ID was deleted here. Go through all users and remove it
10814            // from KeyStore.
10815            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10816        }
10817    }
10818
10819    static boolean locationIsPrivileged(File path) {
10820        try {
10821            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10822                    .getCanonicalPath();
10823            return path.getCanonicalPath().startsWith(privilegedAppDir);
10824        } catch (IOException e) {
10825            Slog.e(TAG, "Unable to access code path " + path);
10826        }
10827        return false;
10828    }
10829
10830    /*
10831     * Tries to delete system package.
10832     */
10833    private boolean deleteSystemPackageLI(PackageSetting newPs,
10834            int[] allUserHandles, boolean[] perUserInstalled,
10835            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10836        final boolean applyUserRestrictions
10837                = (allUserHandles != null) && (perUserInstalled != null);
10838        PackageSetting disabledPs = null;
10839        // Confirm if the system package has been updated
10840        // An updated system app can be deleted. This will also have to restore
10841        // the system pkg from system partition
10842        // reader
10843        synchronized (mPackages) {
10844            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10845        }
10846        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10847                + " disabledPs=" + disabledPs);
10848        if (disabledPs == null) {
10849            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10850            return false;
10851        } else if (DEBUG_REMOVE) {
10852            Slog.d(TAG, "Deleting system pkg from data partition");
10853        }
10854        if (DEBUG_REMOVE) {
10855            if (applyUserRestrictions) {
10856                Slog.d(TAG, "Remembering install states:");
10857                for (int i = 0; i < allUserHandles.length; i++) {
10858                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10859                }
10860            }
10861        }
10862        // Delete the updated package
10863        outInfo.isRemovedPackageSystemUpdate = true;
10864        if (disabledPs.versionCode < newPs.versionCode) {
10865            // Delete data for downgrades
10866            flags &= ~PackageManager.DELETE_KEEP_DATA;
10867        } else {
10868            // Preserve data by setting flag
10869            flags |= PackageManager.DELETE_KEEP_DATA;
10870        }
10871        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10872                allUserHandles, perUserInstalled, outInfo, writeSettings);
10873        if (!ret) {
10874            return false;
10875        }
10876        // writer
10877        synchronized (mPackages) {
10878            // Reinstate the old system package
10879            mSettings.enableSystemPackageLPw(newPs.name);
10880            // Remove any native libraries from the upgraded package.
10881            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10882        }
10883        // Install the system package
10884        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10885        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10886        if (locationIsPrivileged(disabledPs.codePath)) {
10887            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10888        }
10889
10890        final PackageParser.Package newPkg;
10891        try {
10892            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10893        } catch (PackageManagerException e) {
10894            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10895            return false;
10896        }
10897
10898        // writer
10899        synchronized (mPackages) {
10900            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10901            updatePermissionsLPw(newPkg.packageName, newPkg,
10902                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10903            if (applyUserRestrictions) {
10904                if (DEBUG_REMOVE) {
10905                    Slog.d(TAG, "Propagating install state across reinstall");
10906                }
10907                for (int i = 0; i < allUserHandles.length; i++) {
10908                    if (DEBUG_REMOVE) {
10909                        Slog.d(TAG, "    user " + allUserHandles[i]
10910                                + " => " + perUserInstalled[i]);
10911                    }
10912                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10913                }
10914                // Regardless of writeSettings we need to ensure that this restriction
10915                // state propagation is persisted
10916                mSettings.writeAllUsersPackageRestrictionsLPr();
10917            }
10918            // can downgrade to reader here
10919            if (writeSettings) {
10920                mSettings.writeLPr();
10921            }
10922        }
10923        return true;
10924    }
10925
10926    private boolean deleteInstalledPackageLI(PackageSetting ps,
10927            boolean deleteCodeAndResources, int flags,
10928            int[] allUserHandles, boolean[] perUserInstalled,
10929            PackageRemovedInfo outInfo, boolean writeSettings) {
10930        if (outInfo != null) {
10931            outInfo.uid = ps.appId;
10932        }
10933
10934        // Delete package data from internal structures and also remove data if flag is set
10935        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10936
10937        // Delete application code and resources
10938        if (deleteCodeAndResources && (outInfo != null)) {
10939            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10940                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10941                    getAppDexInstructionSets(ps));
10942            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10943        }
10944        return true;
10945    }
10946
10947    @Override
10948    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10949            int userId) {
10950        mContext.enforceCallingOrSelfPermission(
10951                android.Manifest.permission.DELETE_PACKAGES, null);
10952        synchronized (mPackages) {
10953            PackageSetting ps = mSettings.mPackages.get(packageName);
10954            if (ps == null) {
10955                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10956                return false;
10957            }
10958            if (!ps.getInstalled(userId)) {
10959                // Can't block uninstall for an app that is not installed or enabled.
10960                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10961                return false;
10962            }
10963            ps.setBlockUninstall(blockUninstall, userId);
10964            mSettings.writePackageRestrictionsLPr(userId);
10965        }
10966        return true;
10967    }
10968
10969    @Override
10970    public boolean getBlockUninstallForUser(String packageName, int userId) {
10971        synchronized (mPackages) {
10972            PackageSetting ps = mSettings.mPackages.get(packageName);
10973            if (ps == null) {
10974                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10975                return false;
10976            }
10977            return ps.getBlockUninstall(userId);
10978        }
10979    }
10980
10981    /*
10982     * This method handles package deletion in general
10983     */
10984    private boolean deletePackageLI(String packageName, UserHandle user,
10985            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10986            int flags, PackageRemovedInfo outInfo,
10987            boolean writeSettings) {
10988        if (packageName == null) {
10989            Slog.w(TAG, "Attempt to delete null packageName.");
10990            return false;
10991        }
10992        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10993        PackageSetting ps;
10994        boolean dataOnly = false;
10995        int removeUser = -1;
10996        int appId = -1;
10997        synchronized (mPackages) {
10998            ps = mSettings.mPackages.get(packageName);
10999            if (ps == null) {
11000                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11001                return false;
11002            }
11003            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11004                    && user.getIdentifier() != UserHandle.USER_ALL) {
11005                // The caller is asking that the package only be deleted for a single
11006                // user.  To do this, we just mark its uninstalled state and delete
11007                // its data.  If this is a system app, we only allow this to happen if
11008                // they have set the special DELETE_SYSTEM_APP which requests different
11009                // semantics than normal for uninstalling system apps.
11010                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11011                ps.setUserState(user.getIdentifier(),
11012                        COMPONENT_ENABLED_STATE_DEFAULT,
11013                        false, //installed
11014                        true,  //stopped
11015                        true,  //notLaunched
11016                        false, //hidden
11017                        null, null, null,
11018                        false // blockUninstall
11019                        );
11020                if (!isSystemApp(ps)) {
11021                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11022                        // Other user still have this package installed, so all
11023                        // we need to do is clear this user's data and save that
11024                        // it is uninstalled.
11025                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11026                        removeUser = user.getIdentifier();
11027                        appId = ps.appId;
11028                        mSettings.writePackageRestrictionsLPr(removeUser);
11029                    } else {
11030                        // We need to set it back to 'installed' so the uninstall
11031                        // broadcasts will be sent correctly.
11032                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11033                        ps.setInstalled(true, user.getIdentifier());
11034                    }
11035                } else {
11036                    // This is a system app, so we assume that the
11037                    // other users still have this package installed, so all
11038                    // we need to do is clear this user's data and save that
11039                    // it is uninstalled.
11040                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11041                    removeUser = user.getIdentifier();
11042                    appId = ps.appId;
11043                    mSettings.writePackageRestrictionsLPr(removeUser);
11044                }
11045            }
11046        }
11047
11048        if (removeUser >= 0) {
11049            // From above, we determined that we are deleting this only
11050            // for a single user.  Continue the work here.
11051            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11052            if (outInfo != null) {
11053                outInfo.removedPackage = packageName;
11054                outInfo.removedAppId = appId;
11055                outInfo.removedUsers = new int[] {removeUser};
11056            }
11057            mInstaller.clearUserData(packageName, removeUser);
11058            removeKeystoreDataIfNeeded(removeUser, appId);
11059            schedulePackageCleaning(packageName, removeUser, false);
11060            return true;
11061        }
11062
11063        if (dataOnly) {
11064            // Delete application data first
11065            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11066            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11067            return true;
11068        }
11069
11070        boolean ret = false;
11071        if (isSystemApp(ps)) {
11072            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11073            // When an updated system application is deleted we delete the existing resources as well and
11074            // fall back to existing code in system partition
11075            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11076                    flags, outInfo, writeSettings);
11077        } else {
11078            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11079            // Kill application pre-emptively especially for apps on sd.
11080            killApplication(packageName, ps.appId, "uninstall pkg");
11081            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11082                    allUserHandles, perUserInstalled,
11083                    outInfo, writeSettings);
11084        }
11085
11086        return ret;
11087    }
11088
11089    private final class ClearStorageConnection implements ServiceConnection {
11090        IMediaContainerService mContainerService;
11091
11092        @Override
11093        public void onServiceConnected(ComponentName name, IBinder service) {
11094            synchronized (this) {
11095                mContainerService = IMediaContainerService.Stub.asInterface(service);
11096                notifyAll();
11097            }
11098        }
11099
11100        @Override
11101        public void onServiceDisconnected(ComponentName name) {
11102        }
11103    }
11104
11105    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11106        final boolean mounted;
11107        if (Environment.isExternalStorageEmulated()) {
11108            mounted = true;
11109        } else {
11110            final String status = Environment.getExternalStorageState();
11111
11112            mounted = status.equals(Environment.MEDIA_MOUNTED)
11113                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11114        }
11115
11116        if (!mounted) {
11117            return;
11118        }
11119
11120        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11121        int[] users;
11122        if (userId == UserHandle.USER_ALL) {
11123            users = sUserManager.getUserIds();
11124        } else {
11125            users = new int[] { userId };
11126        }
11127        final ClearStorageConnection conn = new ClearStorageConnection();
11128        if (mContext.bindServiceAsUser(
11129                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11130            try {
11131                for (int curUser : users) {
11132                    long timeout = SystemClock.uptimeMillis() + 5000;
11133                    synchronized (conn) {
11134                        long now = SystemClock.uptimeMillis();
11135                        while (conn.mContainerService == null && now < timeout) {
11136                            try {
11137                                conn.wait(timeout - now);
11138                            } catch (InterruptedException e) {
11139                            }
11140                        }
11141                    }
11142                    if (conn.mContainerService == null) {
11143                        return;
11144                    }
11145
11146                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11147                    clearDirectory(conn.mContainerService,
11148                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11149                    if (allData) {
11150                        clearDirectory(conn.mContainerService,
11151                                userEnv.buildExternalStorageAppDataDirs(packageName));
11152                        clearDirectory(conn.mContainerService,
11153                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11154                    }
11155                }
11156            } finally {
11157                mContext.unbindService(conn);
11158            }
11159        }
11160    }
11161
11162    @Override
11163    public void clearApplicationUserData(final String packageName,
11164            final IPackageDataObserver observer, final int userId) {
11165        mContext.enforceCallingOrSelfPermission(
11166                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11167        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11168        // Queue up an async operation since the package deletion may take a little while.
11169        mHandler.post(new Runnable() {
11170            public void run() {
11171                mHandler.removeCallbacks(this);
11172                final boolean succeeded;
11173                synchronized (mInstallLock) {
11174                    succeeded = clearApplicationUserDataLI(packageName, userId);
11175                }
11176                clearExternalStorageDataSync(packageName, userId, true);
11177                if (succeeded) {
11178                    // invoke DeviceStorageMonitor's update method to clear any notifications
11179                    DeviceStorageMonitorInternal
11180                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11181                    if (dsm != null) {
11182                        dsm.checkMemory();
11183                    }
11184                }
11185                if(observer != null) {
11186                    try {
11187                        observer.onRemoveCompleted(packageName, succeeded);
11188                    } catch (RemoteException e) {
11189                        Log.i(TAG, "Observer no longer exists.");
11190                    }
11191                } //end if observer
11192            } //end run
11193        });
11194    }
11195
11196    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11197        if (packageName == null) {
11198            Slog.w(TAG, "Attempt to delete null packageName.");
11199            return false;
11200        }
11201
11202        // Try finding details about the requested package
11203        PackageParser.Package pkg;
11204        synchronized (mPackages) {
11205            pkg = mPackages.get(packageName);
11206            if (pkg == null) {
11207                final PackageSetting ps = mSettings.mPackages.get(packageName);
11208                if (ps != null) {
11209                    pkg = ps.pkg;
11210                }
11211            }
11212        }
11213
11214        if (pkg == null) {
11215            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11216        }
11217
11218        // Always delete data directories for package, even if we found no other
11219        // record of app. This helps users recover from UID mismatches without
11220        // resorting to a full data wipe.
11221        int retCode = mInstaller.clearUserData(packageName, userId);
11222        if (retCode < 0) {
11223            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11224            return false;
11225        }
11226
11227        if (pkg == null) {
11228            return false;
11229        }
11230
11231        if (pkg != null && pkg.applicationInfo != null) {
11232            final int appId = pkg.applicationInfo.uid;
11233            removeKeystoreDataIfNeeded(userId, appId);
11234        }
11235
11236        // Create a native library symlink only if we have native libraries
11237        // and if the native libraries are 32 bit libraries. We do not provide
11238        // this symlink for 64 bit libraries.
11239        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11240                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11241            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11242            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11243                Slog.w(TAG, "Failed linking native library dir");
11244                return false;
11245            }
11246        }
11247
11248        return true;
11249    }
11250
11251    /**
11252     * Remove entries from the keystore daemon. Will only remove it if the
11253     * {@code appId} is valid.
11254     */
11255    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11256        if (appId < 0) {
11257            return;
11258        }
11259
11260        final KeyStore keyStore = KeyStore.getInstance();
11261        if (keyStore != null) {
11262            if (userId == UserHandle.USER_ALL) {
11263                for (final int individual : sUserManager.getUserIds()) {
11264                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11265                }
11266            } else {
11267                keyStore.clearUid(UserHandle.getUid(userId, appId));
11268            }
11269        } else {
11270            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11271        }
11272    }
11273
11274    @Override
11275    public void deleteApplicationCacheFiles(final String packageName,
11276            final IPackageDataObserver observer) {
11277        mContext.enforceCallingOrSelfPermission(
11278                android.Manifest.permission.DELETE_CACHE_FILES, null);
11279        // Queue up an async operation since the package deletion may take a little while.
11280        final int userId = UserHandle.getCallingUserId();
11281        mHandler.post(new Runnable() {
11282            public void run() {
11283                mHandler.removeCallbacks(this);
11284                final boolean succeded;
11285                synchronized (mInstallLock) {
11286                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11287                }
11288                clearExternalStorageDataSync(packageName, userId, false);
11289                if(observer != null) {
11290                    try {
11291                        observer.onRemoveCompleted(packageName, succeded);
11292                    } catch (RemoteException e) {
11293                        Log.i(TAG, "Observer no longer exists.");
11294                    }
11295                } //end if observer
11296            } //end run
11297        });
11298    }
11299
11300    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11301        if (packageName == null) {
11302            Slog.w(TAG, "Attempt to delete null packageName.");
11303            return false;
11304        }
11305        PackageParser.Package p;
11306        synchronized (mPackages) {
11307            p = mPackages.get(packageName);
11308        }
11309        if (p == null) {
11310            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11311            return false;
11312        }
11313        final ApplicationInfo applicationInfo = p.applicationInfo;
11314        if (applicationInfo == null) {
11315            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11316            return false;
11317        }
11318        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11319        if (retCode < 0) {
11320            Slog.w(TAG, "Couldn't remove cache files for package: "
11321                       + packageName + " u" + userId);
11322            return false;
11323        }
11324        return true;
11325    }
11326
11327    @Override
11328    public void getPackageSizeInfo(final String packageName, int userHandle,
11329            final IPackageStatsObserver observer) {
11330        mContext.enforceCallingOrSelfPermission(
11331                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11332        if (packageName == null) {
11333            throw new IllegalArgumentException("Attempt to get size of null packageName");
11334        }
11335
11336        PackageStats stats = new PackageStats(packageName, userHandle);
11337
11338        /*
11339         * Queue up an async operation since the package measurement may take a
11340         * little while.
11341         */
11342        Message msg = mHandler.obtainMessage(INIT_COPY);
11343        msg.obj = new MeasureParams(stats, observer);
11344        mHandler.sendMessage(msg);
11345    }
11346
11347    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11348            PackageStats pStats) {
11349        if (packageName == null) {
11350            Slog.w(TAG, "Attempt to get size of null packageName.");
11351            return false;
11352        }
11353        PackageParser.Package p;
11354        boolean dataOnly = false;
11355        String libDirRoot = null;
11356        String asecPath = null;
11357        PackageSetting ps = null;
11358        synchronized (mPackages) {
11359            p = mPackages.get(packageName);
11360            ps = mSettings.mPackages.get(packageName);
11361            if(p == null) {
11362                dataOnly = true;
11363                if((ps == null) || (ps.pkg == null)) {
11364                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11365                    return false;
11366                }
11367                p = ps.pkg;
11368            }
11369            if (ps != null) {
11370                libDirRoot = ps.legacyNativeLibraryPathString;
11371            }
11372            if (p != null && (isExternal(p) || p.isForwardLocked())) {
11373                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11374                if (secureContainerId != null) {
11375                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11376                }
11377            }
11378        }
11379        String publicSrcDir = null;
11380        if(!dataOnly) {
11381            final ApplicationInfo applicationInfo = p.applicationInfo;
11382            if (applicationInfo == null) {
11383                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11384                return false;
11385            }
11386            if (p.isForwardLocked()) {
11387                publicSrcDir = applicationInfo.getBaseResourcePath();
11388            }
11389        }
11390        // TODO: extend to measure size of split APKs
11391        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11392        // not just the first level.
11393        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11394        // just the primary.
11395        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11396        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11397                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11398        if (res < 0) {
11399            return false;
11400        }
11401
11402        // Fix-up for forward-locked applications in ASEC containers.
11403        if (!isExternal(p)) {
11404            pStats.codeSize += pStats.externalCodeSize;
11405            pStats.externalCodeSize = 0L;
11406        }
11407
11408        return true;
11409    }
11410
11411
11412    @Override
11413    public void addPackageToPreferred(String packageName) {
11414        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11415    }
11416
11417    @Override
11418    public void removePackageFromPreferred(String packageName) {
11419        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11420    }
11421
11422    @Override
11423    public List<PackageInfo> getPreferredPackages(int flags) {
11424        return new ArrayList<PackageInfo>();
11425    }
11426
11427    private int getUidTargetSdkVersionLockedLPr(int uid) {
11428        Object obj = mSettings.getUserIdLPr(uid);
11429        if (obj instanceof SharedUserSetting) {
11430            final SharedUserSetting sus = (SharedUserSetting) obj;
11431            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11432            final Iterator<PackageSetting> it = sus.packages.iterator();
11433            while (it.hasNext()) {
11434                final PackageSetting ps = it.next();
11435                if (ps.pkg != null) {
11436                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11437                    if (v < vers) vers = v;
11438                }
11439            }
11440            return vers;
11441        } else if (obj instanceof PackageSetting) {
11442            final PackageSetting ps = (PackageSetting) obj;
11443            if (ps.pkg != null) {
11444                return ps.pkg.applicationInfo.targetSdkVersion;
11445            }
11446        }
11447        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11448    }
11449
11450    @Override
11451    public void addPreferredActivity(IntentFilter filter, int match,
11452            ComponentName[] set, ComponentName activity, int userId) {
11453        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11454                "Adding preferred");
11455    }
11456
11457    private void addPreferredActivityInternal(IntentFilter filter, int match,
11458            ComponentName[] set, ComponentName activity, boolean always, int userId,
11459            String opname) {
11460        // writer
11461        int callingUid = Binder.getCallingUid();
11462        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11463        if (filter.countActions() == 0) {
11464            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11465            return;
11466        }
11467        synchronized (mPackages) {
11468            if (mContext.checkCallingOrSelfPermission(
11469                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11470                    != PackageManager.PERMISSION_GRANTED) {
11471                if (getUidTargetSdkVersionLockedLPr(callingUid)
11472                        < Build.VERSION_CODES.FROYO) {
11473                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11474                            + callingUid);
11475                    return;
11476                }
11477                mContext.enforceCallingOrSelfPermission(
11478                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11479            }
11480
11481            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11482            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11483                    + userId + ":");
11484            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11485            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11486            scheduleWritePackageRestrictionsLocked(userId);
11487        }
11488    }
11489
11490    @Override
11491    public void replacePreferredActivity(IntentFilter filter, int match,
11492            ComponentName[] set, ComponentName activity, int userId) {
11493        if (filter.countActions() != 1) {
11494            throw new IllegalArgumentException(
11495                    "replacePreferredActivity expects filter to have only 1 action.");
11496        }
11497        if (filter.countDataAuthorities() != 0
11498                || filter.countDataPaths() != 0
11499                || filter.countDataSchemes() > 1
11500                || filter.countDataTypes() != 0) {
11501            throw new IllegalArgumentException(
11502                    "replacePreferredActivity expects filter to have no data authorities, " +
11503                    "paths, or types; and at most one scheme.");
11504        }
11505
11506        final int callingUid = Binder.getCallingUid();
11507        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11508        synchronized (mPackages) {
11509            if (mContext.checkCallingOrSelfPermission(
11510                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11511                    != PackageManager.PERMISSION_GRANTED) {
11512                if (getUidTargetSdkVersionLockedLPr(callingUid)
11513                        < Build.VERSION_CODES.FROYO) {
11514                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11515                            + Binder.getCallingUid());
11516                    return;
11517                }
11518                mContext.enforceCallingOrSelfPermission(
11519                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11520            }
11521
11522            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11523            if (pir != null) {
11524                // Get all of the existing entries that exactly match this filter.
11525                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11526                if (existing != null && existing.size() == 1) {
11527                    PreferredActivity cur = existing.get(0);
11528                    if (DEBUG_PREFERRED) {
11529                        Slog.i(TAG, "Checking replace of preferred:");
11530                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11531                        if (!cur.mPref.mAlways) {
11532                            Slog.i(TAG, "  -- CUR; not mAlways!");
11533                        } else {
11534                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11535                            Slog.i(TAG, "  -- CUR: mSet="
11536                                    + Arrays.toString(cur.mPref.mSetComponents));
11537                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11538                            Slog.i(TAG, "  -- NEW: mMatch="
11539                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11540                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11541                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11542                        }
11543                    }
11544                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11545                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11546                            && cur.mPref.sameSet(set)) {
11547                        // Setting the preferred activity to what it happens to be already
11548                        if (DEBUG_PREFERRED) {
11549                            Slog.i(TAG, "Replacing with same preferred activity "
11550                                    + cur.mPref.mShortComponent + " for user "
11551                                    + userId + ":");
11552                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11553                        }
11554                        return;
11555                    }
11556                }
11557
11558                if (existing != null) {
11559                    if (DEBUG_PREFERRED) {
11560                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11561                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11562                    }
11563                    for (int i = 0; i < existing.size(); i++) {
11564                        PreferredActivity pa = existing.get(i);
11565                        if (DEBUG_PREFERRED) {
11566                            Slog.i(TAG, "Removing existing preferred activity "
11567                                    + pa.mPref.mComponent + ":");
11568                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11569                        }
11570                        pir.removeFilter(pa);
11571                    }
11572                }
11573            }
11574            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11575                    "Replacing preferred");
11576        }
11577    }
11578
11579    @Override
11580    public void clearPackagePreferredActivities(String packageName) {
11581        final int uid = Binder.getCallingUid();
11582        // writer
11583        synchronized (mPackages) {
11584            PackageParser.Package pkg = mPackages.get(packageName);
11585            if (pkg == null || pkg.applicationInfo.uid != uid) {
11586                if (mContext.checkCallingOrSelfPermission(
11587                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11588                        != PackageManager.PERMISSION_GRANTED) {
11589                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11590                            < Build.VERSION_CODES.FROYO) {
11591                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11592                                + Binder.getCallingUid());
11593                        return;
11594                    }
11595                    mContext.enforceCallingOrSelfPermission(
11596                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11597                }
11598            }
11599
11600            int user = UserHandle.getCallingUserId();
11601            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11602                scheduleWritePackageRestrictionsLocked(user);
11603            }
11604        }
11605    }
11606
11607    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11608    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11609        ArrayList<PreferredActivity> removed = null;
11610        boolean changed = false;
11611        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11612            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11613            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11614            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11615                continue;
11616            }
11617            Iterator<PreferredActivity> it = pir.filterIterator();
11618            while (it.hasNext()) {
11619                PreferredActivity pa = it.next();
11620                // Mark entry for removal only if it matches the package name
11621                // and the entry is of type "always".
11622                if (packageName == null ||
11623                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11624                                && pa.mPref.mAlways)) {
11625                    if (removed == null) {
11626                        removed = new ArrayList<PreferredActivity>();
11627                    }
11628                    removed.add(pa);
11629                }
11630            }
11631            if (removed != null) {
11632                for (int j=0; j<removed.size(); j++) {
11633                    PreferredActivity pa = removed.get(j);
11634                    pir.removeFilter(pa);
11635                }
11636                changed = true;
11637            }
11638        }
11639        return changed;
11640    }
11641
11642    @Override
11643    public void resetPreferredActivities(int userId) {
11644        /* TODO: Actually use userId. Why is it being passed in? */
11645        mContext.enforceCallingOrSelfPermission(
11646                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11647        // writer
11648        synchronized (mPackages) {
11649            int user = UserHandle.getCallingUserId();
11650            clearPackagePreferredActivitiesLPw(null, user);
11651            mSettings.readDefaultPreferredAppsLPw(this, user);
11652            scheduleWritePackageRestrictionsLocked(user);
11653        }
11654    }
11655
11656    @Override
11657    public int getPreferredActivities(List<IntentFilter> outFilters,
11658            List<ComponentName> outActivities, String packageName) {
11659
11660        int num = 0;
11661        final int userId = UserHandle.getCallingUserId();
11662        // reader
11663        synchronized (mPackages) {
11664            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11665            if (pir != null) {
11666                final Iterator<PreferredActivity> it = pir.filterIterator();
11667                while (it.hasNext()) {
11668                    final PreferredActivity pa = it.next();
11669                    if (packageName == null
11670                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11671                                    && pa.mPref.mAlways)) {
11672                        if (outFilters != null) {
11673                            outFilters.add(new IntentFilter(pa));
11674                        }
11675                        if (outActivities != null) {
11676                            outActivities.add(pa.mPref.mComponent);
11677                        }
11678                    }
11679                }
11680            }
11681        }
11682
11683        return num;
11684    }
11685
11686    @Override
11687    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11688            int userId) {
11689        int callingUid = Binder.getCallingUid();
11690        if (callingUid != Process.SYSTEM_UID) {
11691            throw new SecurityException(
11692                    "addPersistentPreferredActivity can only be run by the system");
11693        }
11694        if (filter.countActions() == 0) {
11695            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11696            return;
11697        }
11698        synchronized (mPackages) {
11699            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11700                    " :");
11701            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11702            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11703                    new PersistentPreferredActivity(filter, activity));
11704            scheduleWritePackageRestrictionsLocked(userId);
11705        }
11706    }
11707
11708    @Override
11709    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11710        int callingUid = Binder.getCallingUid();
11711        if (callingUid != Process.SYSTEM_UID) {
11712            throw new SecurityException(
11713                    "clearPackagePersistentPreferredActivities can only be run by the system");
11714        }
11715        ArrayList<PersistentPreferredActivity> removed = null;
11716        boolean changed = false;
11717        synchronized (mPackages) {
11718            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11719                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11720                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11721                        .valueAt(i);
11722                if (userId != thisUserId) {
11723                    continue;
11724                }
11725                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11726                while (it.hasNext()) {
11727                    PersistentPreferredActivity ppa = it.next();
11728                    // Mark entry for removal only if it matches the package name.
11729                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11730                        if (removed == null) {
11731                            removed = new ArrayList<PersistentPreferredActivity>();
11732                        }
11733                        removed.add(ppa);
11734                    }
11735                }
11736                if (removed != null) {
11737                    for (int j=0; j<removed.size(); j++) {
11738                        PersistentPreferredActivity ppa = removed.get(j);
11739                        ppir.removeFilter(ppa);
11740                    }
11741                    changed = true;
11742                }
11743            }
11744
11745            if (changed) {
11746                scheduleWritePackageRestrictionsLocked(userId);
11747            }
11748        }
11749    }
11750
11751    @Override
11752    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11753            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11754        mContext.enforceCallingOrSelfPermission(
11755                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11756        int callingUid = Binder.getCallingUid();
11757        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11758        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11759        if (intentFilter.countActions() == 0) {
11760            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11761            return;
11762        }
11763        synchronized (mPackages) {
11764            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
11765                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11766            CrossProfileIntentResolver resolver =
11767                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11768            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
11769            // We have all those whose filter is equal. Now checking if the rest is equal as well.
11770            if (existing != null) {
11771                int size = existing.size();
11772                for (int i = 0; i < size; i++) {
11773                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
11774                        return;
11775                    }
11776                }
11777            }
11778            resolver.addFilter(newFilter);
11779            scheduleWritePackageRestrictionsLocked(sourceUserId);
11780        }
11781    }
11782
11783    @Override
11784    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11785            int ownerUserId) {
11786        mContext.enforceCallingOrSelfPermission(
11787                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11788        int callingUid = Binder.getCallingUid();
11789        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11790        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11791        int callingUserId = UserHandle.getUserId(callingUid);
11792        synchronized (mPackages) {
11793            CrossProfileIntentResolver resolver =
11794                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11795            ArraySet<CrossProfileIntentFilter> set =
11796                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
11797            for (CrossProfileIntentFilter filter : set) {
11798                if (filter.getOwnerPackage().equals(ownerPackage)
11799                        && filter.getOwnerUserId() == callingUserId) {
11800                    resolver.removeFilter(filter);
11801                }
11802            }
11803            scheduleWritePackageRestrictionsLocked(sourceUserId);
11804        }
11805    }
11806
11807    // Enforcing that callingUid is owning pkg on userId
11808    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11809        // The system owns everything.
11810        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11811            return;
11812        }
11813        int callingUserId = UserHandle.getUserId(callingUid);
11814        if (callingUserId != userId) {
11815            throw new SecurityException("calling uid " + callingUid
11816                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11817                    + callingUserId);
11818        }
11819        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11820        if (pi == null) {
11821            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11822                    + callingUserId);
11823        }
11824        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11825            throw new SecurityException("Calling uid " + callingUid
11826                    + " does not own package " + pkg);
11827        }
11828    }
11829
11830    @Override
11831    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11832        Intent intent = new Intent(Intent.ACTION_MAIN);
11833        intent.addCategory(Intent.CATEGORY_HOME);
11834
11835        final int callingUserId = UserHandle.getCallingUserId();
11836        List<ResolveInfo> list = queryIntentActivities(intent, null,
11837                PackageManager.GET_META_DATA, callingUserId);
11838        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11839                true, false, false, callingUserId);
11840
11841        allHomeCandidates.clear();
11842        if (list != null) {
11843            for (ResolveInfo ri : list) {
11844                allHomeCandidates.add(ri);
11845            }
11846        }
11847        return (preferred == null || preferred.activityInfo == null)
11848                ? null
11849                : new ComponentName(preferred.activityInfo.packageName,
11850                        preferred.activityInfo.name);
11851    }
11852
11853    @Override
11854    public void setApplicationEnabledSetting(String appPackageName,
11855            int newState, int flags, int userId, String callingPackage) {
11856        if (!sUserManager.exists(userId)) return;
11857        if (callingPackage == null) {
11858            callingPackage = Integer.toString(Binder.getCallingUid());
11859        }
11860        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11861    }
11862
11863    @Override
11864    public void setComponentEnabledSetting(ComponentName componentName,
11865            int newState, int flags, int userId) {
11866        if (!sUserManager.exists(userId)) return;
11867        setEnabledSetting(componentName.getPackageName(),
11868                componentName.getClassName(), newState, flags, userId, null);
11869    }
11870
11871    private void setEnabledSetting(final String packageName, String className, int newState,
11872            final int flags, int userId, String callingPackage) {
11873        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11874              || newState == COMPONENT_ENABLED_STATE_ENABLED
11875              || newState == COMPONENT_ENABLED_STATE_DISABLED
11876              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11877              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11878            throw new IllegalArgumentException("Invalid new component state: "
11879                    + newState);
11880        }
11881        PackageSetting pkgSetting;
11882        final int uid = Binder.getCallingUid();
11883        final int permission = mContext.checkCallingOrSelfPermission(
11884                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11885        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
11886        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11887        boolean sendNow = false;
11888        boolean isApp = (className == null);
11889        String componentName = isApp ? packageName : className;
11890        int packageUid = -1;
11891        ArrayList<String> components;
11892
11893        // writer
11894        synchronized (mPackages) {
11895            pkgSetting = mSettings.mPackages.get(packageName);
11896            if (pkgSetting == null) {
11897                if (className == null) {
11898                    throw new IllegalArgumentException(
11899                            "Unknown package: " + packageName);
11900                }
11901                throw new IllegalArgumentException(
11902                        "Unknown component: " + packageName
11903                        + "/" + className);
11904            }
11905            // Allow root and verify that userId is not being specified by a different user
11906            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11907                throw new SecurityException(
11908                        "Permission Denial: attempt to change component state from pid="
11909                        + Binder.getCallingPid()
11910                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11911            }
11912            if (className == null) {
11913                // We're dealing with an application/package level state change
11914                if (pkgSetting.getEnabled(userId) == newState) {
11915                    // Nothing to do
11916                    return;
11917                }
11918                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11919                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11920                    // Don't care about who enables an app.
11921                    callingPackage = null;
11922                }
11923                pkgSetting.setEnabled(newState, userId, callingPackage);
11924                // pkgSetting.pkg.mSetEnabled = newState;
11925            } else {
11926                // We're dealing with a component level state change
11927                // First, verify that this is a valid class name.
11928                PackageParser.Package pkg = pkgSetting.pkg;
11929                if (pkg == null || !pkg.hasComponentClassName(className)) {
11930                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11931                        throw new IllegalArgumentException("Component class " + className
11932                                + " does not exist in " + packageName);
11933                    } else {
11934                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11935                                + className + " does not exist in " + packageName);
11936                    }
11937                }
11938                switch (newState) {
11939                case COMPONENT_ENABLED_STATE_ENABLED:
11940                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11941                        return;
11942                    }
11943                    break;
11944                case COMPONENT_ENABLED_STATE_DISABLED:
11945                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11946                        return;
11947                    }
11948                    break;
11949                case COMPONENT_ENABLED_STATE_DEFAULT:
11950                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11951                        return;
11952                    }
11953                    break;
11954                default:
11955                    Slog.e(TAG, "Invalid new component state: " + newState);
11956                    return;
11957                }
11958            }
11959            mSettings.writePackageRestrictionsLPr(userId);
11960            components = mPendingBroadcasts.get(userId, packageName);
11961            final boolean newPackage = components == null;
11962            if (newPackage) {
11963                components = new ArrayList<String>();
11964            }
11965            if (!components.contains(componentName)) {
11966                components.add(componentName);
11967            }
11968            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11969                sendNow = true;
11970                // Purge entry from pending broadcast list if another one exists already
11971                // since we are sending one right away.
11972                mPendingBroadcasts.remove(userId, packageName);
11973            } else {
11974                if (newPackage) {
11975                    mPendingBroadcasts.put(userId, packageName, components);
11976                }
11977                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11978                    // Schedule a message
11979                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11980                }
11981            }
11982        }
11983
11984        long callingId = Binder.clearCallingIdentity();
11985        try {
11986            if (sendNow) {
11987                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11988                sendPackageChangedBroadcast(packageName,
11989                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11990            }
11991        } finally {
11992            Binder.restoreCallingIdentity(callingId);
11993        }
11994    }
11995
11996    private void sendPackageChangedBroadcast(String packageName,
11997            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11998        if (DEBUG_INSTALL)
11999            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12000                    + componentNames);
12001        Bundle extras = new Bundle(4);
12002        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12003        String nameList[] = new String[componentNames.size()];
12004        componentNames.toArray(nameList);
12005        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12006        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12007        extras.putInt(Intent.EXTRA_UID, packageUid);
12008        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12009                new int[] {UserHandle.getUserId(packageUid)});
12010    }
12011
12012    @Override
12013    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12014        if (!sUserManager.exists(userId)) return;
12015        final int uid = Binder.getCallingUid();
12016        final int permission = mContext.checkCallingOrSelfPermission(
12017                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12018        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12019        enforceCrossUserPermission(uid, userId, true, true, "stop package");
12020        // writer
12021        synchronized (mPackages) {
12022            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12023                    uid, userId)) {
12024                scheduleWritePackageRestrictionsLocked(userId);
12025            }
12026        }
12027    }
12028
12029    @Override
12030    public String getInstallerPackageName(String packageName) {
12031        // reader
12032        synchronized (mPackages) {
12033            return mSettings.getInstallerPackageNameLPr(packageName);
12034        }
12035    }
12036
12037    @Override
12038    public int getApplicationEnabledSetting(String packageName, int userId) {
12039        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12040        int uid = Binder.getCallingUid();
12041        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
12042        // reader
12043        synchronized (mPackages) {
12044            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12045        }
12046    }
12047
12048    @Override
12049    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12050        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12051        int uid = Binder.getCallingUid();
12052        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
12053        // reader
12054        synchronized (mPackages) {
12055            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12056        }
12057    }
12058
12059    @Override
12060    public void enterSafeMode() {
12061        enforceSystemOrRoot("Only the system can request entering safe mode");
12062
12063        if (!mSystemReady) {
12064            mSafeMode = true;
12065        }
12066    }
12067
12068    @Override
12069    public void systemReady() {
12070        mSystemReady = true;
12071
12072        // Read the compatibilty setting when the system is ready.
12073        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12074                mContext.getContentResolver(),
12075                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12076        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12077        if (DEBUG_SETTINGS) {
12078            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12079        }
12080
12081        synchronized (mPackages) {
12082            // Verify that all of the preferred activity components actually
12083            // exist.  It is possible for applications to be updated and at
12084            // that point remove a previously declared activity component that
12085            // had been set as a preferred activity.  We try to clean this up
12086            // the next time we encounter that preferred activity, but it is
12087            // possible for the user flow to never be able to return to that
12088            // situation so here we do a sanity check to make sure we haven't
12089            // left any junk around.
12090            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12091            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12092                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12093                removed.clear();
12094                for (PreferredActivity pa : pir.filterSet()) {
12095                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12096                        removed.add(pa);
12097                    }
12098                }
12099                if (removed.size() > 0) {
12100                    for (int r=0; r<removed.size(); r++) {
12101                        PreferredActivity pa = removed.get(r);
12102                        Slog.w(TAG, "Removing dangling preferred activity: "
12103                                + pa.mPref.mComponent);
12104                        pir.removeFilter(pa);
12105                    }
12106                    mSettings.writePackageRestrictionsLPr(
12107                            mSettings.mPreferredActivities.keyAt(i));
12108                }
12109            }
12110        }
12111        sUserManager.systemReady();
12112
12113        // Kick off any messages waiting for system ready
12114        if (mPostSystemReadyMessages != null) {
12115            for (Message msg : mPostSystemReadyMessages) {
12116                msg.sendToTarget();
12117            }
12118            mPostSystemReadyMessages = null;
12119        }
12120    }
12121
12122    @Override
12123    public boolean isSafeMode() {
12124        return mSafeMode;
12125    }
12126
12127    @Override
12128    public boolean hasSystemUidErrors() {
12129        return mHasSystemUidErrors;
12130    }
12131
12132    static String arrayToString(int[] array) {
12133        StringBuffer buf = new StringBuffer(128);
12134        buf.append('[');
12135        if (array != null) {
12136            for (int i=0; i<array.length; i++) {
12137                if (i > 0) buf.append(", ");
12138                buf.append(array[i]);
12139            }
12140        }
12141        buf.append(']');
12142        return buf.toString();
12143    }
12144
12145    static class DumpState {
12146        public static final int DUMP_LIBS = 1 << 0;
12147        public static final int DUMP_FEATURES = 1 << 1;
12148        public static final int DUMP_RESOLVERS = 1 << 2;
12149        public static final int DUMP_PERMISSIONS = 1 << 3;
12150        public static final int DUMP_PACKAGES = 1 << 4;
12151        public static final int DUMP_SHARED_USERS = 1 << 5;
12152        public static final int DUMP_MESSAGES = 1 << 6;
12153        public static final int DUMP_PROVIDERS = 1 << 7;
12154        public static final int DUMP_VERIFIERS = 1 << 8;
12155        public static final int DUMP_PREFERRED = 1 << 9;
12156        public static final int DUMP_PREFERRED_XML = 1 << 10;
12157        public static final int DUMP_KEYSETS = 1 << 11;
12158        public static final int DUMP_VERSION = 1 << 12;
12159        public static final int DUMP_INSTALLS = 1 << 13;
12160
12161        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12162
12163        private int mTypes;
12164
12165        private int mOptions;
12166
12167        private boolean mTitlePrinted;
12168
12169        private SharedUserSetting mSharedUser;
12170
12171        public boolean isDumping(int type) {
12172            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12173                return true;
12174            }
12175
12176            return (mTypes & type) != 0;
12177        }
12178
12179        public void setDump(int type) {
12180            mTypes |= type;
12181        }
12182
12183        public boolean isOptionEnabled(int option) {
12184            return (mOptions & option) != 0;
12185        }
12186
12187        public void setOptionEnabled(int option) {
12188            mOptions |= option;
12189        }
12190
12191        public boolean onTitlePrinted() {
12192            final boolean printed = mTitlePrinted;
12193            mTitlePrinted = true;
12194            return printed;
12195        }
12196
12197        public boolean getTitlePrinted() {
12198            return mTitlePrinted;
12199        }
12200
12201        public void setTitlePrinted(boolean enabled) {
12202            mTitlePrinted = enabled;
12203        }
12204
12205        public SharedUserSetting getSharedUser() {
12206            return mSharedUser;
12207        }
12208
12209        public void setSharedUser(SharedUserSetting user) {
12210            mSharedUser = user;
12211        }
12212    }
12213
12214    @Override
12215    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12216        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12217                != PackageManager.PERMISSION_GRANTED) {
12218            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12219                    + Binder.getCallingPid()
12220                    + ", uid=" + Binder.getCallingUid()
12221                    + " without permission "
12222                    + android.Manifest.permission.DUMP);
12223            return;
12224        }
12225
12226        DumpState dumpState = new DumpState();
12227        boolean fullPreferred = false;
12228        boolean checkin = false;
12229
12230        String packageName = null;
12231
12232        int opti = 0;
12233        while (opti < args.length) {
12234            String opt = args[opti];
12235            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12236                break;
12237            }
12238            opti++;
12239
12240            if ("-a".equals(opt)) {
12241                // Right now we only know how to print all.
12242            } else if ("-h".equals(opt)) {
12243                pw.println("Package manager dump options:");
12244                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12245                pw.println("    --checkin: dump for a checkin");
12246                pw.println("    -f: print details of intent filters");
12247                pw.println("    -h: print this help");
12248                pw.println("  cmd may be one of:");
12249                pw.println("    l[ibraries]: list known shared libraries");
12250                pw.println("    f[ibraries]: list device features");
12251                pw.println("    k[eysets]: print known keysets");
12252                pw.println("    r[esolvers]: dump intent resolvers");
12253                pw.println("    perm[issions]: dump permissions");
12254                pw.println("    pref[erred]: print preferred package settings");
12255                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12256                pw.println("    prov[iders]: dump content providers");
12257                pw.println("    p[ackages]: dump installed packages");
12258                pw.println("    s[hared-users]: dump shared user IDs");
12259                pw.println("    m[essages]: print collected runtime messages");
12260                pw.println("    v[erifiers]: print package verifier info");
12261                pw.println("    version: print database version info");
12262                pw.println("    write: write current settings now");
12263                pw.println("    <package.name>: info about given package");
12264                pw.println("    installs: details about install sessions");
12265                return;
12266            } else if ("--checkin".equals(opt)) {
12267                checkin = true;
12268            } else if ("-f".equals(opt)) {
12269                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12270            } else {
12271                pw.println("Unknown argument: " + opt + "; use -h for help");
12272            }
12273        }
12274
12275        // Is the caller requesting to dump a particular piece of data?
12276        if (opti < args.length) {
12277            String cmd = args[opti];
12278            opti++;
12279            // Is this a package name?
12280            if ("android".equals(cmd) || cmd.contains(".")) {
12281                packageName = cmd;
12282                // When dumping a single package, we always dump all of its
12283                // filter information since the amount of data will be reasonable.
12284                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12285            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12286                dumpState.setDump(DumpState.DUMP_LIBS);
12287            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12288                dumpState.setDump(DumpState.DUMP_FEATURES);
12289            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12290                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12291            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12292                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12293            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12294                dumpState.setDump(DumpState.DUMP_PREFERRED);
12295            } else if ("preferred-xml".equals(cmd)) {
12296                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12297                if (opti < args.length && "--full".equals(args[opti])) {
12298                    fullPreferred = true;
12299                    opti++;
12300                }
12301            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12302                dumpState.setDump(DumpState.DUMP_PACKAGES);
12303            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12304                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12305            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12306                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12307            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12308                dumpState.setDump(DumpState.DUMP_MESSAGES);
12309            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12310                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12311            } else if ("version".equals(cmd)) {
12312                dumpState.setDump(DumpState.DUMP_VERSION);
12313            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12314                dumpState.setDump(DumpState.DUMP_KEYSETS);
12315            } else if ("installs".equals(cmd)) {
12316                dumpState.setDump(DumpState.DUMP_INSTALLS);
12317            } else if ("write".equals(cmd)) {
12318                synchronized (mPackages) {
12319                    mSettings.writeLPr();
12320                    pw.println("Settings written.");
12321                    return;
12322                }
12323            }
12324        }
12325
12326        if (checkin) {
12327            pw.println("vers,1");
12328        }
12329
12330        // reader
12331        synchronized (mPackages) {
12332            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12333                if (!checkin) {
12334                    if (dumpState.onTitlePrinted())
12335                        pw.println();
12336                    pw.println("Database versions:");
12337                    pw.print("  SDK Version:");
12338                    pw.print(" internal=");
12339                    pw.print(mSettings.mInternalSdkPlatform);
12340                    pw.print(" external=");
12341                    pw.println(mSettings.mExternalSdkPlatform);
12342                    pw.print("  DB Version:");
12343                    pw.print(" internal=");
12344                    pw.print(mSettings.mInternalDatabaseVersion);
12345                    pw.print(" external=");
12346                    pw.println(mSettings.mExternalDatabaseVersion);
12347                }
12348            }
12349
12350            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12351                if (!checkin) {
12352                    if (dumpState.onTitlePrinted())
12353                        pw.println();
12354                    pw.println("Verifiers:");
12355                    pw.print("  Required: ");
12356                    pw.print(mRequiredVerifierPackage);
12357                    pw.print(" (uid=");
12358                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12359                    pw.println(")");
12360                } else if (mRequiredVerifierPackage != null) {
12361                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12362                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12363                }
12364            }
12365
12366            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12367                boolean printedHeader = false;
12368                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12369                while (it.hasNext()) {
12370                    String name = it.next();
12371                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12372                    if (!checkin) {
12373                        if (!printedHeader) {
12374                            if (dumpState.onTitlePrinted())
12375                                pw.println();
12376                            pw.println("Libraries:");
12377                            printedHeader = true;
12378                        }
12379                        pw.print("  ");
12380                    } else {
12381                        pw.print("lib,");
12382                    }
12383                    pw.print(name);
12384                    if (!checkin) {
12385                        pw.print(" -> ");
12386                    }
12387                    if (ent.path != null) {
12388                        if (!checkin) {
12389                            pw.print("(jar) ");
12390                            pw.print(ent.path);
12391                        } else {
12392                            pw.print(",jar,");
12393                            pw.print(ent.path);
12394                        }
12395                    } else {
12396                        if (!checkin) {
12397                            pw.print("(apk) ");
12398                            pw.print(ent.apk);
12399                        } else {
12400                            pw.print(",apk,");
12401                            pw.print(ent.apk);
12402                        }
12403                    }
12404                    pw.println();
12405                }
12406            }
12407
12408            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12409                if (dumpState.onTitlePrinted())
12410                    pw.println();
12411                if (!checkin) {
12412                    pw.println("Features:");
12413                }
12414                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12415                while (it.hasNext()) {
12416                    String name = it.next();
12417                    if (!checkin) {
12418                        pw.print("  ");
12419                    } else {
12420                        pw.print("feat,");
12421                    }
12422                    pw.println(name);
12423                }
12424            }
12425
12426            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12427                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12428                        : "Activity Resolver Table:", "  ", packageName,
12429                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12430                    dumpState.setTitlePrinted(true);
12431                }
12432                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12433                        : "Receiver Resolver Table:", "  ", packageName,
12434                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12435                    dumpState.setTitlePrinted(true);
12436                }
12437                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12438                        : "Service Resolver Table:", "  ", packageName,
12439                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12440                    dumpState.setTitlePrinted(true);
12441                }
12442                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12443                        : "Provider Resolver Table:", "  ", packageName,
12444                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
12445                    dumpState.setTitlePrinted(true);
12446                }
12447            }
12448
12449            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12450                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12451                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12452                    int user = mSettings.mPreferredActivities.keyAt(i);
12453                    if (pir.dump(pw,
12454                            dumpState.getTitlePrinted()
12455                                ? "\nPreferred Activities User " + user + ":"
12456                                : "Preferred Activities User " + user + ":", "  ",
12457                            packageName, true, false)) {
12458                        dumpState.setTitlePrinted(true);
12459                    }
12460                }
12461            }
12462
12463            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12464                pw.flush();
12465                FileOutputStream fout = new FileOutputStream(fd);
12466                BufferedOutputStream str = new BufferedOutputStream(fout);
12467                XmlSerializer serializer = new FastXmlSerializer();
12468                try {
12469                    serializer.setOutput(str, "utf-8");
12470                    serializer.startDocument(null, true);
12471                    serializer.setFeature(
12472                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12473                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12474                    serializer.endDocument();
12475                    serializer.flush();
12476                } catch (IllegalArgumentException e) {
12477                    pw.println("Failed writing: " + e);
12478                } catch (IllegalStateException e) {
12479                    pw.println("Failed writing: " + e);
12480                } catch (IOException e) {
12481                    pw.println("Failed writing: " + e);
12482                }
12483            }
12484
12485            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12486                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12487                if (packageName == null) {
12488                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12489                        if (iperm == 0) {
12490                            if (dumpState.onTitlePrinted())
12491                                pw.println();
12492                            pw.println("AppOp Permissions:");
12493                        }
12494                        pw.print("  AppOp Permission ");
12495                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12496                        pw.println(":");
12497                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12498                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12499                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12500                        }
12501                    }
12502                }
12503            }
12504
12505            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12506                boolean printedSomething = false;
12507                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12508                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12509                        continue;
12510                    }
12511                    if (!printedSomething) {
12512                        if (dumpState.onTitlePrinted())
12513                            pw.println();
12514                        pw.println("Registered ContentProviders:");
12515                        printedSomething = true;
12516                    }
12517                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12518                    pw.print("    "); pw.println(p.toString());
12519                }
12520                printedSomething = false;
12521                for (Map.Entry<String, PackageParser.Provider> entry :
12522                        mProvidersByAuthority.entrySet()) {
12523                    PackageParser.Provider p = entry.getValue();
12524                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12525                        continue;
12526                    }
12527                    if (!printedSomething) {
12528                        if (dumpState.onTitlePrinted())
12529                            pw.println();
12530                        pw.println("ContentProvider Authorities:");
12531                        printedSomething = true;
12532                    }
12533                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12534                    pw.print("    "); pw.println(p.toString());
12535                    if (p.info != null && p.info.applicationInfo != null) {
12536                        final String appInfo = p.info.applicationInfo.toString();
12537                        pw.print("      applicationInfo="); pw.println(appInfo);
12538                    }
12539                }
12540            }
12541
12542            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12543                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12544            }
12545
12546            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12547                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12548            }
12549
12550            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12551                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
12552            }
12553
12554            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12555                // XXX should handle packageName != null by dumping only install data that
12556                // the given package is involved with.
12557                if (dumpState.onTitlePrinted()) pw.println();
12558                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12559            }
12560
12561            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12562                if (dumpState.onTitlePrinted()) pw.println();
12563                mSettings.dumpReadMessagesLPr(pw, dumpState);
12564
12565                pw.println();
12566                pw.println("Package warning messages:");
12567                BufferedReader in = null;
12568                String line = null;
12569                try {
12570                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12571                    while ((line = in.readLine()) != null) {
12572                        if (line.contains("ignored: updated version")) continue;
12573                        pw.println(line);
12574                    }
12575                } catch (IOException ignored) {
12576                } finally {
12577                    IoUtils.closeQuietly(in);
12578                }
12579            }
12580
12581            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
12582                BufferedReader in = null;
12583                String line = null;
12584                try {
12585                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12586                    while ((line = in.readLine()) != null) {
12587                        if (line.contains("ignored: updated version")) continue;
12588                        pw.print("msg,");
12589                        pw.println(line);
12590                    }
12591                } catch (IOException ignored) {
12592                } finally {
12593                    IoUtils.closeQuietly(in);
12594                }
12595            }
12596        }
12597    }
12598
12599    // ------- apps on sdcard specific code -------
12600    static final boolean DEBUG_SD_INSTALL = false;
12601
12602    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12603
12604    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12605
12606    private boolean mMediaMounted = false;
12607
12608    static String getEncryptKey() {
12609        try {
12610            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12611                    SD_ENCRYPTION_KEYSTORE_NAME);
12612            if (sdEncKey == null) {
12613                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12614                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12615                if (sdEncKey == null) {
12616                    Slog.e(TAG, "Failed to create encryption keys");
12617                    return null;
12618                }
12619            }
12620            return sdEncKey;
12621        } catch (NoSuchAlgorithmException nsae) {
12622            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12623            return null;
12624        } catch (IOException ioe) {
12625            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12626            return null;
12627        }
12628    }
12629
12630    /*
12631     * Update media status on PackageManager.
12632     */
12633    @Override
12634    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12635        int callingUid = Binder.getCallingUid();
12636        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12637            throw new SecurityException("Media status can only be updated by the system");
12638        }
12639        // reader; this apparently protects mMediaMounted, but should probably
12640        // be a different lock in that case.
12641        synchronized (mPackages) {
12642            Log.i(TAG, "Updating external media status from "
12643                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12644                    + (mediaStatus ? "mounted" : "unmounted"));
12645            if (DEBUG_SD_INSTALL)
12646                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12647                        + ", mMediaMounted=" + mMediaMounted);
12648            if (mediaStatus == mMediaMounted) {
12649                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12650                        : 0, -1);
12651                mHandler.sendMessage(msg);
12652                return;
12653            }
12654            mMediaMounted = mediaStatus;
12655        }
12656        // Queue up an async operation since the package installation may take a
12657        // little while.
12658        mHandler.post(new Runnable() {
12659            public void run() {
12660                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12661            }
12662        });
12663    }
12664
12665    /**
12666     * Called by MountService when the initial ASECs to scan are available.
12667     * Should block until all the ASEC containers are finished being scanned.
12668     */
12669    public void scanAvailableAsecs() {
12670        updateExternalMediaStatusInner(true, false, false);
12671        if (mShouldRestoreconData) {
12672            SELinuxMMAC.setRestoreconDone();
12673            mShouldRestoreconData = false;
12674        }
12675    }
12676
12677    /*
12678     * Collect information of applications on external media, map them against
12679     * existing containers and update information based on current mount status.
12680     * Please note that we always have to report status if reportStatus has been
12681     * set to true especially when unloading packages.
12682     */
12683    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12684            boolean externalStorage) {
12685        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12686        int[] uidArr = EmptyArray.INT;
12687
12688        final String[] list = PackageHelper.getSecureContainerList();
12689        if (ArrayUtils.isEmpty(list)) {
12690            Log.i(TAG, "No secure containers found");
12691        } else {
12692            // Process list of secure containers and categorize them
12693            // as active or stale based on their package internal state.
12694
12695            // reader
12696            synchronized (mPackages) {
12697                for (String cid : list) {
12698                    // Leave stages untouched for now; installer service owns them
12699                    if (PackageInstallerService.isStageName(cid)) continue;
12700
12701                    if (DEBUG_SD_INSTALL)
12702                        Log.i(TAG, "Processing container " + cid);
12703                    String pkgName = getAsecPackageName(cid);
12704                    if (pkgName == null) {
12705                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12706                        continue;
12707                    }
12708                    if (DEBUG_SD_INSTALL)
12709                        Log.i(TAG, "Looking for pkg : " + pkgName);
12710
12711                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12712                    if (ps == null) {
12713                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12714                        continue;
12715                    }
12716
12717                    /*
12718                     * Skip packages that are not external if we're unmounting
12719                     * external storage.
12720                     */
12721                    if (externalStorage && !isMounted && !isExternal(ps)) {
12722                        continue;
12723                    }
12724
12725                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12726                            getAppDexInstructionSets(ps), ps.isForwardLocked());
12727                    // The package status is changed only if the code path
12728                    // matches between settings and the container id.
12729                    if (ps.codePathString != null
12730                            && ps.codePathString.startsWith(args.getCodePath())) {
12731                        if (DEBUG_SD_INSTALL) {
12732                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12733                                    + " at code path: " + ps.codePathString);
12734                        }
12735
12736                        // We do have a valid package installed on sdcard
12737                        processCids.put(args, ps.codePathString);
12738                        final int uid = ps.appId;
12739                        if (uid != -1) {
12740                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12741                        }
12742                    } else {
12743                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12744                                + ps.codePathString);
12745                    }
12746                }
12747            }
12748
12749            Arrays.sort(uidArr);
12750        }
12751
12752        // Process packages with valid entries.
12753        if (isMounted) {
12754            if (DEBUG_SD_INSTALL)
12755                Log.i(TAG, "Loading packages");
12756            loadMediaPackages(processCids, uidArr);
12757            startCleaningPackages();
12758            mInstallerService.onSecureContainersAvailable();
12759        } else {
12760            if (DEBUG_SD_INSTALL)
12761                Log.i(TAG, "Unloading packages");
12762            unloadMediaPackages(processCids, uidArr, reportStatus);
12763        }
12764    }
12765
12766    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12767            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12768        int size = pkgList.size();
12769        if (size > 0) {
12770            // Send broadcasts here
12771            Bundle extras = new Bundle();
12772            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12773                    .toArray(new String[size]));
12774            if (uidArr != null) {
12775                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12776            }
12777            if (replacing) {
12778                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12779            }
12780            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12781                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12782            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12783        }
12784    }
12785
12786   /*
12787     * Look at potentially valid container ids from processCids If package
12788     * information doesn't match the one on record or package scanning fails,
12789     * the cid is added to list of removeCids. We currently don't delete stale
12790     * containers.
12791     */
12792    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12793        ArrayList<String> pkgList = new ArrayList<String>();
12794        Set<AsecInstallArgs> keys = processCids.keySet();
12795
12796        for (AsecInstallArgs args : keys) {
12797            String codePath = processCids.get(args);
12798            if (DEBUG_SD_INSTALL)
12799                Log.i(TAG, "Loading container : " + args.cid);
12800            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12801            try {
12802                // Make sure there are no container errors first.
12803                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12804                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12805                            + " when installing from sdcard");
12806                    continue;
12807                }
12808                // Check code path here.
12809                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12810                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12811                            + " does not match one in settings " + codePath);
12812                    continue;
12813                }
12814                // Parse package
12815                int parseFlags = mDefParseFlags;
12816                if (args.isExternal()) {
12817                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12818                }
12819                if (args.isFwdLocked()) {
12820                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12821                }
12822
12823                synchronized (mInstallLock) {
12824                    PackageParser.Package pkg = null;
12825                    try {
12826                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12827                    } catch (PackageManagerException e) {
12828                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12829                    }
12830                    // Scan the package
12831                    if (pkg != null) {
12832                        /*
12833                         * TODO why is the lock being held? doPostInstall is
12834                         * called in other places without the lock. This needs
12835                         * to be straightened out.
12836                         */
12837                        // writer
12838                        synchronized (mPackages) {
12839                            retCode = PackageManager.INSTALL_SUCCEEDED;
12840                            pkgList.add(pkg.packageName);
12841                            // Post process args
12842                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12843                                    pkg.applicationInfo.uid);
12844                        }
12845                    } else {
12846                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12847                    }
12848                }
12849
12850            } finally {
12851                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12852                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12853                }
12854            }
12855        }
12856        // writer
12857        synchronized (mPackages) {
12858            // If the platform SDK has changed since the last time we booted,
12859            // we need to re-grant app permission to catch any new ones that
12860            // appear. This is really a hack, and means that apps can in some
12861            // cases get permissions that the user didn't initially explicitly
12862            // allow... it would be nice to have some better way to handle
12863            // this situation.
12864            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12865            if (regrantPermissions)
12866                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12867                        + mSdkVersion + "; regranting permissions for external storage");
12868            mSettings.mExternalSdkPlatform = mSdkVersion;
12869
12870            // Make sure group IDs have been assigned, and any permission
12871            // changes in other apps are accounted for
12872            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12873                    | (regrantPermissions
12874                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12875                            : 0));
12876
12877            mSettings.updateExternalDatabaseVersion();
12878
12879            // can downgrade to reader
12880            // Persist settings
12881            mSettings.writeLPr();
12882        }
12883        // Send a broadcast to let everyone know we are done processing
12884        if (pkgList.size() > 0) {
12885            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12886        }
12887    }
12888
12889   /*
12890     * Utility method to unload a list of specified containers
12891     */
12892    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12893        // Just unmount all valid containers.
12894        for (AsecInstallArgs arg : cidArgs) {
12895            synchronized (mInstallLock) {
12896                arg.doPostDeleteLI(false);
12897           }
12898       }
12899   }
12900
12901    /*
12902     * Unload packages mounted on external media. This involves deleting package
12903     * data from internal structures, sending broadcasts about diabled packages,
12904     * gc'ing to free up references, unmounting all secure containers
12905     * corresponding to packages on external media, and posting a
12906     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12907     * that we always have to post this message if status has been requested no
12908     * matter what.
12909     */
12910    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12911            final boolean reportStatus) {
12912        if (DEBUG_SD_INSTALL)
12913            Log.i(TAG, "unloading media packages");
12914        ArrayList<String> pkgList = new ArrayList<String>();
12915        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12916        final Set<AsecInstallArgs> keys = processCids.keySet();
12917        for (AsecInstallArgs args : keys) {
12918            String pkgName = args.getPackageName();
12919            if (DEBUG_SD_INSTALL)
12920                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12921            // Delete package internally
12922            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12923            synchronized (mInstallLock) {
12924                boolean res = deletePackageLI(pkgName, null, false, null, null,
12925                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12926                if (res) {
12927                    pkgList.add(pkgName);
12928                } else {
12929                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12930                    failedList.add(args);
12931                }
12932            }
12933        }
12934
12935        // reader
12936        synchronized (mPackages) {
12937            // We didn't update the settings after removing each package;
12938            // write them now for all packages.
12939            mSettings.writeLPr();
12940        }
12941
12942        // We have to absolutely send UPDATED_MEDIA_STATUS only
12943        // after confirming that all the receivers processed the ordered
12944        // broadcast when packages get disabled, force a gc to clean things up.
12945        // and unload all the containers.
12946        if (pkgList.size() > 0) {
12947            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12948                    new IIntentReceiver.Stub() {
12949                public void performReceive(Intent intent, int resultCode, String data,
12950                        Bundle extras, boolean ordered, boolean sticky,
12951                        int sendingUser) throws RemoteException {
12952                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12953                            reportStatus ? 1 : 0, 1, keys);
12954                    mHandler.sendMessage(msg);
12955                }
12956            });
12957        } else {
12958            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12959                    keys);
12960            mHandler.sendMessage(msg);
12961        }
12962    }
12963
12964    /** Binder call */
12965    @Override
12966    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12967            final int flags) {
12968        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12969        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12970        int returnCode = PackageManager.MOVE_SUCCEEDED;
12971        int currInstallFlags = 0;
12972        int newInstallFlags = 0;
12973
12974        File codeFile = null;
12975        String installerPackageName = null;
12976        String packageAbiOverride = null;
12977
12978        // reader
12979        synchronized (mPackages) {
12980            final PackageParser.Package pkg = mPackages.get(packageName);
12981            final PackageSetting ps = mSettings.mPackages.get(packageName);
12982            if (pkg == null || ps == null) {
12983                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12984            } else {
12985                // Disable moving fwd locked apps and system packages
12986                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12987                    Slog.w(TAG, "Cannot move system application");
12988                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12989                } else if (pkg.mOperationPending) {
12990                    Slog.w(TAG, "Attempt to move package which has pending operations");
12991                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12992                } else {
12993                    // Find install location first
12994                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12995                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12996                        Slog.w(TAG, "Ambigous flags specified for move location.");
12997                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12998                    } else {
12999                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13000                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13001                        currInstallFlags = isExternal(pkg)
13002                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13003
13004                        if (newInstallFlags == currInstallFlags) {
13005                            Slog.w(TAG, "No move required. Trying to move to same location");
13006                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13007                        } else {
13008                            if (pkg.isForwardLocked()) {
13009                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13010                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13011                            }
13012                        }
13013                    }
13014                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13015                        pkg.mOperationPending = true;
13016                    }
13017                }
13018
13019                codeFile = new File(pkg.codePath);
13020                installerPackageName = ps.installerPackageName;
13021                packageAbiOverride = ps.cpuAbiOverrideString;
13022            }
13023        }
13024
13025        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13026            try {
13027                observer.packageMoved(packageName, returnCode);
13028            } catch (RemoteException ignored) {
13029            }
13030            return;
13031        }
13032
13033        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
13034            @Override
13035            public void onUserActionRequired(Intent intent) throws RemoteException {
13036                throw new IllegalStateException();
13037            }
13038
13039            @Override
13040            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
13041                    Bundle extras) throws RemoteException {
13042                Slog.d(TAG, "Install result for move: "
13043                        + PackageManager.installStatusToString(returnCode, msg));
13044
13045                // We usually have a new package now after the install, but if
13046                // we failed we need to clear the pending flag on the original
13047                // package object.
13048                synchronized (mPackages) {
13049                    final PackageParser.Package pkg = mPackages.get(packageName);
13050                    if (pkg != null) {
13051                        pkg.mOperationPending = false;
13052                    }
13053                }
13054
13055                final int status = PackageManager.installStatusToPublicStatus(returnCode);
13056                switch (status) {
13057                    case PackageInstaller.STATUS_SUCCESS:
13058                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
13059                        break;
13060                    case PackageInstaller.STATUS_FAILURE_STORAGE:
13061                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
13062                        break;
13063                    default:
13064                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
13065                        break;
13066                }
13067            }
13068        };
13069
13070        // Treat a move like reinstalling an existing app, which ensures that we
13071        // process everythign uniformly, like unpacking native libraries.
13072        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
13073
13074        final Message msg = mHandler.obtainMessage(INIT_COPY);
13075        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
13076        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
13077                installerPackageName, null, user, packageAbiOverride);
13078        mHandler.sendMessage(msg);
13079    }
13080
13081    @Override
13082    public boolean setInstallLocation(int loc) {
13083        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13084                null);
13085        if (getInstallLocation() == loc) {
13086            return true;
13087        }
13088        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13089                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13090            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13091                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13092            return true;
13093        }
13094        return false;
13095   }
13096
13097    @Override
13098    public int getInstallLocation() {
13099        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13100                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13101                PackageHelper.APP_INSTALL_AUTO);
13102    }
13103
13104    /** Called by UserManagerService */
13105    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13106        mDirtyUsers.remove(userHandle);
13107        mSettings.removeUserLPw(userHandle);
13108        mPendingBroadcasts.remove(userHandle);
13109        if (mInstaller != null) {
13110            // Technically, we shouldn't be doing this with the package lock
13111            // held.  However, this is very rare, and there is already so much
13112            // other disk I/O going on, that we'll let it slide for now.
13113            mInstaller.removeUserDataDirs(userHandle);
13114        }
13115        mUserNeedsBadging.delete(userHandle);
13116        removeUnusedPackagesLILPw(userManager, userHandle);
13117    }
13118
13119    /**
13120     * We're removing userHandle and would like to remove any downloaded packages
13121     * that are no longer in use by any other user.
13122     * @param userHandle the user being removed
13123     */
13124    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13125        final boolean DEBUG_CLEAN_APKS = false;
13126        int [] users = userManager.getUserIdsLPr();
13127        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13128        while (psit.hasNext()) {
13129            PackageSetting ps = psit.next();
13130            if (ps.pkg == null) {
13131                continue;
13132            }
13133            final String packageName = ps.pkg.packageName;
13134            // Skip over if system app
13135            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13136                continue;
13137            }
13138            if (DEBUG_CLEAN_APKS) {
13139                Slog.i(TAG, "Checking package " + packageName);
13140            }
13141            boolean keep = false;
13142            for (int i = 0; i < users.length; i++) {
13143                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13144                    keep = true;
13145                    if (DEBUG_CLEAN_APKS) {
13146                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13147                                + users[i]);
13148                    }
13149                    break;
13150                }
13151            }
13152            if (!keep) {
13153                if (DEBUG_CLEAN_APKS) {
13154                    Slog.i(TAG, "  Removing package " + packageName);
13155                }
13156                mHandler.post(new Runnable() {
13157                    public void run() {
13158                        deletePackageX(packageName, userHandle, 0);
13159                    } //end run
13160                });
13161            }
13162        }
13163    }
13164
13165    /** Called by UserManagerService */
13166    void createNewUserLILPw(int userHandle, File path) {
13167        if (mInstaller != null) {
13168            mInstaller.createUserConfig(userHandle);
13169            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13170        }
13171    }
13172
13173    @Override
13174    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13175        mContext.enforceCallingOrSelfPermission(
13176                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13177                "Only package verification agents can read the verifier device identity");
13178
13179        synchronized (mPackages) {
13180            return mSettings.getVerifierDeviceIdentityLPw();
13181        }
13182    }
13183
13184    @Override
13185    public void setPermissionEnforced(String permission, boolean enforced) {
13186        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13187        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13188            synchronized (mPackages) {
13189                if (mSettings.mReadExternalStorageEnforced == null
13190                        || mSettings.mReadExternalStorageEnforced != enforced) {
13191                    mSettings.mReadExternalStorageEnforced = enforced;
13192                    mSettings.writeLPr();
13193                }
13194            }
13195            // kill any non-foreground processes so we restart them and
13196            // grant/revoke the GID.
13197            final IActivityManager am = ActivityManagerNative.getDefault();
13198            if (am != null) {
13199                final long token = Binder.clearCallingIdentity();
13200                try {
13201                    am.killProcessesBelowForeground("setPermissionEnforcement");
13202                } catch (RemoteException e) {
13203                } finally {
13204                    Binder.restoreCallingIdentity(token);
13205                }
13206            }
13207        } else {
13208            throw new IllegalArgumentException("No selective enforcement for " + permission);
13209        }
13210    }
13211
13212    @Override
13213    @Deprecated
13214    public boolean isPermissionEnforced(String permission) {
13215        return true;
13216    }
13217
13218    @Override
13219    public boolean isStorageLow() {
13220        final long token = Binder.clearCallingIdentity();
13221        try {
13222            final DeviceStorageMonitorInternal
13223                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13224            if (dsm != null) {
13225                return dsm.isMemoryLow();
13226            } else {
13227                return false;
13228            }
13229        } finally {
13230            Binder.restoreCallingIdentity(token);
13231        }
13232    }
13233
13234    @Override
13235    public IPackageInstaller getPackageInstaller() {
13236        return mInstallerService;
13237    }
13238
13239    private boolean userNeedsBadging(int userId) {
13240        int index = mUserNeedsBadging.indexOfKey(userId);
13241        if (index < 0) {
13242            final UserInfo userInfo;
13243            final long token = Binder.clearCallingIdentity();
13244            try {
13245                userInfo = sUserManager.getUserInfo(userId);
13246            } finally {
13247                Binder.restoreCallingIdentity(token);
13248            }
13249            final boolean b;
13250            if (userInfo != null && userInfo.isManagedProfile()) {
13251                b = true;
13252            } else {
13253                b = false;
13254            }
13255            mUserNeedsBadging.put(userId, b);
13256            return b;
13257        }
13258        return mUserNeedsBadging.valueAt(index);
13259    }
13260
13261    @Override
13262    public KeySet getKeySetByAlias(String packageName, String alias) {
13263        if (packageName == null || alias == null) {
13264            return null;
13265        }
13266        synchronized(mPackages) {
13267            final PackageParser.Package pkg = mPackages.get(packageName);
13268            if (pkg == null) {
13269                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13270                throw new IllegalArgumentException("Unknown package: " + packageName);
13271            }
13272            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13273            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13274        }
13275    }
13276
13277    @Override
13278    public KeySet getSigningKeySet(String packageName) {
13279        if (packageName == null) {
13280            return null;
13281        }
13282        synchronized(mPackages) {
13283            final PackageParser.Package pkg = mPackages.get(packageName);
13284            if (pkg == null) {
13285                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13286                throw new IllegalArgumentException("Unknown package: " + packageName);
13287            }
13288            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13289                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13290                throw new SecurityException("May not access signing KeySet of other apps.");
13291            }
13292            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13293            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13294        }
13295    }
13296
13297    @Override
13298    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13299        if (packageName == null || ks == null) {
13300            return false;
13301        }
13302        synchronized(mPackages) {
13303            final PackageParser.Package pkg = mPackages.get(packageName);
13304            if (pkg == null) {
13305                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13306                throw new IllegalArgumentException("Unknown package: " + packageName);
13307            }
13308            IBinder ksh = ks.getToken();
13309            if (ksh instanceof KeySetHandle) {
13310                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13311                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13312            }
13313            return false;
13314        }
13315    }
13316
13317    @Override
13318    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13319        if (packageName == null || ks == null) {
13320            return false;
13321        }
13322        synchronized(mPackages) {
13323            final PackageParser.Package pkg = mPackages.get(packageName);
13324            if (pkg == null) {
13325                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13326                throw new IllegalArgumentException("Unknown package: " + packageName);
13327            }
13328            IBinder ksh = ks.getToken();
13329            if (ksh instanceof KeySetHandle) {
13330                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13331                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13332            }
13333            return false;
13334        }
13335    }
13336
13337    public void getUsageStatsIfNoPackageUsageInfo() {
13338        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
13339            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
13340            if (usm == null) {
13341                throw new IllegalStateException("UsageStatsManager must be initialized");
13342            }
13343            long now = System.currentTimeMillis();
13344            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
13345            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
13346                String packageName = entry.getKey();
13347                PackageParser.Package pkg = mPackages.get(packageName);
13348                if (pkg == null) {
13349                    continue;
13350                }
13351                UsageStats usage = entry.getValue();
13352                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
13353                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
13354            }
13355        }
13356    }
13357
13358    /**
13359     * Check and throw if the given before/after packages would be considered a
13360     * downgrade.
13361     */
13362    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
13363            throws PackageManagerException {
13364        if (after.versionCode < before.mVersionCode) {
13365            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13366                    "Update version code " + after.versionCode + " is older than current "
13367                    + before.mVersionCode);
13368        } else if (after.versionCode == before.mVersionCode) {
13369            if (after.baseRevisionCode < before.baseRevisionCode) {
13370                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13371                        "Update base revision code " + after.baseRevisionCode
13372                        + " is older than current " + before.baseRevisionCode);
13373            }
13374
13375            if (!ArrayUtils.isEmpty(after.splitNames)) {
13376                for (int i = 0; i < after.splitNames.length; i++) {
13377                    final String splitName = after.splitNames[i];
13378                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
13379                    if (j != -1) {
13380                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
13381                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
13382                                    "Update split " + splitName + " revision code "
13383                                    + after.splitRevisionCodes[i] + " is older than current "
13384                                    + before.splitRevisionCodes[j]);
13385                        }
13386                    }
13387                }
13388            }
13389        }
13390    }
13391}
13392