PackageManagerService.java revision 9f8602644418ecfb1a5c9555792ceed285fa72bd
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.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
33import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
34import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
35import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
36import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
43import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
44import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
45import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
46import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
48import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
53import static android.content.pm.PackageManager.INSTALL_INTERNAL;
54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
65import static android.content.pm.PackageManager.PERMISSION_DENIED;
66import static android.content.pm.PackageManager.PERMISSION_GRANTED;
67import static android.content.pm.PackageParser.isApkFile;
68import static android.os.Process.PACKAGE_INFO_GID;
69import static android.os.Process.SYSTEM_UID;
70import static android.system.OsConstants.O_CREAT;
71import static android.system.OsConstants.O_RDWR;
72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
74import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
75import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
76import static com.android.internal.util.ArrayUtils.appendInt;
77import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
78import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
79import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
81import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
82import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
86
87import android.Manifest;
88import android.app.ActivityManager;
89import android.app.ActivityManagerNative;
90import android.app.AppGlobals;
91import android.app.IActivityManager;
92import android.app.admin.IDevicePolicyManager;
93import android.app.backup.IBackupManager;
94import android.app.usage.UsageStats;
95import android.app.usage.UsageStatsManager;
96import android.content.BroadcastReceiver;
97import android.content.ComponentName;
98import android.content.Context;
99import android.content.IIntentReceiver;
100import android.content.Intent;
101import android.content.IntentFilter;
102import android.content.IntentSender;
103import android.content.IntentSender.SendIntentException;
104import android.content.ServiceConnection;
105import android.content.pm.ActivityInfo;
106import android.content.pm.ApplicationInfo;
107import android.content.pm.FeatureInfo;
108import android.content.pm.IOnPermissionsChangeListener;
109import android.content.pm.IPackageDataObserver;
110import android.content.pm.IPackageDeleteObserver;
111import android.content.pm.IPackageDeleteObserver2;
112import android.content.pm.IPackageInstallObserver2;
113import android.content.pm.IPackageInstaller;
114import android.content.pm.IPackageManager;
115import android.content.pm.IPackageMoveObserver;
116import android.content.pm.IPackageStatsObserver;
117import android.content.pm.InstrumentationInfo;
118import android.content.pm.IntentFilterVerificationInfo;
119import android.content.pm.KeySet;
120import android.content.pm.ManifestDigest;
121import android.content.pm.PackageCleanItem;
122import android.content.pm.PackageInfo;
123import android.content.pm.PackageInfoLite;
124import android.content.pm.PackageInstaller;
125import android.content.pm.PackageManager;
126import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
127import android.content.pm.PackageManagerInternal;
128import android.content.pm.PackageParser;
129import android.content.pm.PackageParser.ActivityIntentInfo;
130import android.content.pm.PackageParser.PackageLite;
131import android.content.pm.PackageParser.PackageParserException;
132import android.content.pm.PackageStats;
133import android.content.pm.PackageUserState;
134import android.content.pm.ParceledListSlice;
135import android.content.pm.PermissionGroupInfo;
136import android.content.pm.PermissionInfo;
137import android.content.pm.ProviderInfo;
138import android.content.pm.ResolveInfo;
139import android.content.pm.ServiceInfo;
140import android.content.pm.Signature;
141import android.content.pm.UserInfo;
142import android.content.pm.VerificationParams;
143import android.content.pm.VerifierDeviceIdentity;
144import android.content.pm.VerifierInfo;
145import android.content.res.Resources;
146import android.hardware.display.DisplayManager;
147import android.net.Uri;
148import android.os.Debug;
149import android.os.Binder;
150import android.os.Build;
151import android.os.Bundle;
152import android.os.Environment;
153import android.os.Environment.UserEnvironment;
154import android.os.FileUtils;
155import android.os.Handler;
156import android.os.IBinder;
157import android.os.Looper;
158import android.os.Message;
159import android.os.Parcel;
160import android.os.ParcelFileDescriptor;
161import android.os.Process;
162import android.os.RemoteCallbackList;
163import android.os.RemoteException;
164import android.os.SELinux;
165import android.os.ServiceManager;
166import android.os.SystemClock;
167import android.os.SystemProperties;
168import android.os.UserHandle;
169import android.os.UserManager;
170import android.os.storage.IMountService;
171import android.os.storage.MountServiceInternal;
172import android.os.storage.StorageEventListener;
173import android.os.storage.StorageManager;
174import android.os.storage.VolumeInfo;
175import android.os.storage.VolumeRecord;
176import android.security.KeyStore;
177import android.security.SystemKeyStore;
178import android.system.ErrnoException;
179import android.system.Os;
180import android.system.StructStat;
181import android.text.TextUtils;
182import android.text.format.DateUtils;
183import android.util.ArrayMap;
184import android.util.ArraySet;
185import android.util.AtomicFile;
186import android.util.DisplayMetrics;
187import android.util.EventLog;
188import android.util.ExceptionUtils;
189import android.util.Log;
190import android.util.LogPrinter;
191import android.util.MathUtils;
192import android.util.PrintStreamPrinter;
193import android.util.Slog;
194import android.util.SparseArray;
195import android.util.SparseBooleanArray;
196import android.util.SparseIntArray;
197import android.util.Xml;
198import android.view.Display;
199
200import dalvik.system.DexFile;
201import dalvik.system.VMRuntime;
202
203import libcore.io.IoUtils;
204import libcore.util.EmptyArray;
205
206import com.android.internal.R;
207import com.android.internal.annotations.GuardedBy;
208import com.android.internal.app.IMediaContainerService;
209import com.android.internal.app.ResolverActivity;
210import com.android.internal.content.NativeLibraryHelper;
211import com.android.internal.content.PackageHelper;
212import com.android.internal.os.IParcelFileDescriptorFactory;
213import com.android.internal.os.SomeArgs;
214import com.android.internal.os.Zygote;
215import com.android.internal.util.ArrayUtils;
216import com.android.internal.util.FastPrintWriter;
217import com.android.internal.util.FastXmlSerializer;
218import com.android.internal.util.IndentingPrintWriter;
219import com.android.internal.util.Preconditions;
220import com.android.server.EventLogTags;
221import com.android.server.FgThread;
222import com.android.server.IntentResolver;
223import com.android.server.LocalServices;
224import com.android.server.ServiceThread;
225import com.android.server.SystemConfig;
226import com.android.server.Watchdog;
227import com.android.server.pm.PermissionsState.PermissionState;
228import com.android.server.pm.Settings.DatabaseVersion;
229import com.android.server.pm.Settings.VersionInfo;
230import com.android.server.storage.DeviceStorageMonitorInternal;
231
232import org.xmlpull.v1.XmlPullParser;
233import org.xmlpull.v1.XmlPullParserException;
234import org.xmlpull.v1.XmlSerializer;
235
236import java.io.BufferedInputStream;
237import java.io.BufferedOutputStream;
238import java.io.BufferedReader;
239import java.io.ByteArrayInputStream;
240import java.io.ByteArrayOutputStream;
241import java.io.File;
242import java.io.FileDescriptor;
243import java.io.FileNotFoundException;
244import java.io.FileOutputStream;
245import java.io.FileReader;
246import java.io.FilenameFilter;
247import java.io.IOException;
248import java.io.InputStream;
249import java.io.PrintWriter;
250import java.nio.charset.StandardCharsets;
251import java.security.NoSuchAlgorithmException;
252import java.security.PublicKey;
253import java.security.cert.CertificateEncodingException;
254import java.security.cert.CertificateException;
255import java.text.SimpleDateFormat;
256import java.util.ArrayList;
257import java.util.Arrays;
258import java.util.Collection;
259import java.util.Collections;
260import java.util.Comparator;
261import java.util.Date;
262import java.util.Iterator;
263import java.util.List;
264import java.util.Map;
265import java.util.Objects;
266import java.util.Set;
267import java.util.concurrent.CountDownLatch;
268import java.util.concurrent.TimeUnit;
269import java.util.concurrent.atomic.AtomicBoolean;
270import java.util.concurrent.atomic.AtomicInteger;
271import java.util.concurrent.atomic.AtomicLong;
272
273/**
274 * Keep track of all those .apks everywhere.
275 *
276 * This is very central to the platform's security; please run the unit
277 * tests whenever making modifications here:
278 *
279mmm frameworks/base/tests/AndroidTests
280adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
281adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
282 *
283 * {@hide}
284 */
285public class PackageManagerService extends IPackageManager.Stub {
286    static final String TAG = "PackageManager";
287    static final boolean DEBUG_SETTINGS = false;
288    static final boolean DEBUG_PREFERRED = false;
289    static final boolean DEBUG_UPGRADE = false;
290    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
291    private static final boolean DEBUG_BACKUP = false;
292    private static final boolean DEBUG_INSTALL = false;
293    private static final boolean DEBUG_REMOVE = false;
294    private static final boolean DEBUG_BROADCASTS = false;
295    private static final boolean DEBUG_SHOW_INFO = false;
296    private static final boolean DEBUG_PACKAGE_INFO = false;
297    private static final boolean DEBUG_INTENT_MATCHING = false;
298    private static final boolean DEBUG_PACKAGE_SCANNING = false;
299    private static final boolean DEBUG_VERIFY = false;
300    private static final boolean DEBUG_DEXOPT = false;
301    private static final boolean DEBUG_ABI_SELECTION = false;
302
303    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
304
305    private static final int RADIO_UID = Process.PHONE_UID;
306    private static final int LOG_UID = Process.LOG_UID;
307    private static final int NFC_UID = Process.NFC_UID;
308    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
309    private static final int SHELL_UID = Process.SHELL_UID;
310
311    // Cap the size of permission trees that 3rd party apps can define
312    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
313
314    // Suffix used during package installation when copying/moving
315    // package apks to install directory.
316    private static final String INSTALL_PACKAGE_SUFFIX = "-";
317
318    static final int SCAN_NO_DEX = 1<<1;
319    static final int SCAN_FORCE_DEX = 1<<2;
320    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
321    static final int SCAN_NEW_INSTALL = 1<<4;
322    static final int SCAN_NO_PATHS = 1<<5;
323    static final int SCAN_UPDATE_TIME = 1<<6;
324    static final int SCAN_DEFER_DEX = 1<<7;
325    static final int SCAN_BOOTING = 1<<8;
326    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
327    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
328    static final int SCAN_REPLACING = 1<<11;
329    static final int SCAN_REQUIRE_KNOWN = 1<<12;
330    static final int SCAN_MOVE = 1<<13;
331    static final int SCAN_INITIAL = 1<<14;
332
333    static final int REMOVE_CHATTY = 1<<16;
334
335    private static final int[] EMPTY_INT_ARRAY = new int[0];
336
337    /**
338     * Timeout (in milliseconds) after which the watchdog should declare that
339     * our handler thread is wedged.  The usual default for such things is one
340     * minute but we sometimes do very lengthy I/O operations on this thread,
341     * such as installing multi-gigabyte applications, so ours needs to be longer.
342     */
343    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
344
345    /**
346     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
347     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
348     * settings entry if available, otherwise we use the hardcoded default.  If it's been
349     * more than this long since the last fstrim, we force one during the boot sequence.
350     *
351     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
352     * one gets run at the next available charging+idle time.  This final mandatory
353     * no-fstrim check kicks in only of the other scheduling criteria is never met.
354     */
355    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
356
357    /**
358     * Whether verification is enabled by default.
359     */
360    private static final boolean DEFAULT_VERIFY_ENABLE = true;
361
362    /**
363     * The default maximum time to wait for the verification agent to return in
364     * milliseconds.
365     */
366    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
367
368    /**
369     * The default response for package verification timeout.
370     *
371     * This can be either PackageManager.VERIFICATION_ALLOW or
372     * PackageManager.VERIFICATION_REJECT.
373     */
374    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
375
376    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
377
378    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
379            DEFAULT_CONTAINER_PACKAGE,
380            "com.android.defcontainer.DefaultContainerService");
381
382    private static final String KILL_APP_REASON_GIDS_CHANGED =
383            "permission grant or revoke changed gids";
384
385    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
386            "permissions revoked";
387
388    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
389
390    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
391
392    /** Permission grant: not grant the permission. */
393    private static final int GRANT_DENIED = 1;
394
395    /** Permission grant: grant the permission as an install permission. */
396    private static final int GRANT_INSTALL = 2;
397
398    /** Permission grant: grant the permission as an install permission for a legacy app. */
399    private static final int GRANT_INSTALL_LEGACY = 3;
400
401    /** Permission grant: grant the permission as a runtime one. */
402    private static final int GRANT_RUNTIME = 4;
403
404    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
405    private static final int GRANT_UPGRADE = 5;
406
407    /** Canonical intent used to identify what counts as a "web browser" app */
408    private static final Intent sBrowserIntent;
409    static {
410        sBrowserIntent = new Intent();
411        sBrowserIntent.setAction(Intent.ACTION_VIEW);
412        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
413        sBrowserIntent.setData(Uri.parse("http:"));
414    }
415
416    final ServiceThread mHandlerThread;
417
418    final PackageHandler mHandler;
419
420    /**
421     * Messages for {@link #mHandler} that need to wait for system ready before
422     * being dispatched.
423     */
424    private ArrayList<Message> mPostSystemReadyMessages;
425
426    final int mSdkVersion = Build.VERSION.SDK_INT;
427
428    final Context mContext;
429    final boolean mFactoryTest;
430    final boolean mOnlyCore;
431    final boolean mLazyDexOpt;
432    final long mDexOptLRUThresholdInMills;
433    final DisplayMetrics mMetrics;
434    final int mDefParseFlags;
435    final String[] mSeparateProcesses;
436    final boolean mIsUpgrade;
437
438    // This is where all application persistent data goes.
439    final File mAppDataDir;
440
441    // This is where all application persistent data goes for secondary users.
442    final File mUserAppDataDir;
443
444    /** The location for ASEC container files on internal storage. */
445    final String mAsecInternalPath;
446
447    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
448    // LOCK HELD.  Can be called with mInstallLock held.
449    @GuardedBy("mInstallLock")
450    final Installer mInstaller;
451
452    /** Directory where installed third-party apps stored */
453    final File mAppInstallDir;
454
455    /**
456     * Directory to which applications installed internally have their
457     * 32 bit native libraries copied.
458     */
459    private File mAppLib32InstallDir;
460
461    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
462    // apps.
463    final File mDrmAppPrivateInstallDir;
464
465    // ----------------------------------------------------------------
466
467    // Lock for state used when installing and doing other long running
468    // operations.  Methods that must be called with this lock held have
469    // the suffix "LI".
470    final Object mInstallLock = new Object();
471
472    // ----------------------------------------------------------------
473
474    // Keys are String (package name), values are Package.  This also serves
475    // as the lock for the global state.  Methods that must be called with
476    // this lock held have the prefix "LP".
477    @GuardedBy("mPackages")
478    final ArrayMap<String, PackageParser.Package> mPackages =
479            new ArrayMap<String, PackageParser.Package>();
480
481    // Tracks available target package names -> overlay package paths.
482    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
483        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
484
485    /**
486     * Tracks new system packages [received in an OTA] that we expect to
487     * find updated user-installed versions. Keys are package name, values
488     * are package location.
489     */
490    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
491
492    /**
493     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
494     */
495    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
496    /**
497     * Whether or not system app permissions should be promoted from install to runtime.
498     */
499    boolean mPromoteSystemApps;
500
501    final Settings mSettings;
502    boolean mRestoredSettings;
503
504    // System configuration read by SystemConfig.
505    final int[] mGlobalGids;
506    final SparseArray<ArraySet<String>> mSystemPermissions;
507    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
508
509    // If mac_permissions.xml was found for seinfo labeling.
510    boolean mFoundPolicyFile;
511
512    // If a recursive restorecon of /data/data/<pkg> is needed.
513    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
514
515    public static final class SharedLibraryEntry {
516        public final String path;
517        public final String apk;
518
519        SharedLibraryEntry(String _path, String _apk) {
520            path = _path;
521            apk = _apk;
522        }
523    }
524
525    // Currently known shared libraries.
526    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
527            new ArrayMap<String, SharedLibraryEntry>();
528
529    // All available activities, for your resolving pleasure.
530    final ActivityIntentResolver mActivities =
531            new ActivityIntentResolver();
532
533    // All available receivers, for your resolving pleasure.
534    final ActivityIntentResolver mReceivers =
535            new ActivityIntentResolver();
536
537    // All available services, for your resolving pleasure.
538    final ServiceIntentResolver mServices = new ServiceIntentResolver();
539
540    // All available providers, for your resolving pleasure.
541    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
542
543    // Mapping from provider base names (first directory in content URI codePath)
544    // to the provider information.
545    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
546            new ArrayMap<String, PackageParser.Provider>();
547
548    // Mapping from instrumentation class names to info about them.
549    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
550            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
551
552    // Mapping from permission names to info about them.
553    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
554            new ArrayMap<String, PackageParser.PermissionGroup>();
555
556    // Packages whose data we have transfered into another package, thus
557    // should no longer exist.
558    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
559
560    // Broadcast actions that are only available to the system.
561    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
562
563    /** List of packages waiting for verification. */
564    final SparseArray<PackageVerificationState> mPendingVerification
565            = new SparseArray<PackageVerificationState>();
566
567    /** Set of packages associated with each app op permission. */
568    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
569
570    final PackageInstallerService mInstallerService;
571
572    private final PackageDexOptimizer mPackageDexOptimizer;
573
574    private AtomicInteger mNextMoveId = new AtomicInteger();
575    private final MoveCallbacks mMoveCallbacks;
576
577    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
578
579    // Cache of users who need badging.
580    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
581
582    /** Token for keys in mPendingVerification. */
583    private int mPendingVerificationToken = 0;
584
585    volatile boolean mSystemReady;
586    volatile boolean mSafeMode;
587    volatile boolean mHasSystemUidErrors;
588
589    ApplicationInfo mAndroidApplication;
590    final ActivityInfo mResolveActivity = new ActivityInfo();
591    final ResolveInfo mResolveInfo = new ResolveInfo();
592    ComponentName mResolveComponentName;
593    PackageParser.Package mPlatformPackage;
594    ComponentName mCustomResolverComponentName;
595
596    boolean mResolverReplaced = false;
597
598    private final ComponentName mIntentFilterVerifierComponent;
599    private int mIntentFilterVerificationToken = 0;
600
601    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
602            = new SparseArray<IntentFilterVerificationState>();
603
604    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
605            new DefaultPermissionGrantPolicy(this);
606
607    private static class IFVerificationParams {
608        PackageParser.Package pkg;
609        boolean replacing;
610        int userId;
611        int verifierUid;
612
613        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
614                int _userId, int _verifierUid) {
615            pkg = _pkg;
616            replacing = _replacing;
617            userId = _userId;
618            replacing = _replacing;
619            verifierUid = _verifierUid;
620        }
621    }
622
623    private interface IntentFilterVerifier<T extends IntentFilter> {
624        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
625                                               T filter, String packageName);
626        void startVerifications(int userId);
627        void receiveVerificationResponse(int verificationId);
628    }
629
630    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
631        private Context mContext;
632        private ComponentName mIntentFilterVerifierComponent;
633        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
634
635        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
636            mContext = context;
637            mIntentFilterVerifierComponent = verifierComponent;
638        }
639
640        private String getDefaultScheme() {
641            return IntentFilter.SCHEME_HTTPS;
642        }
643
644        @Override
645        public void startVerifications(int userId) {
646            // Launch verifications requests
647            int count = mCurrentIntentFilterVerifications.size();
648            for (int n=0; n<count; n++) {
649                int verificationId = mCurrentIntentFilterVerifications.get(n);
650                final IntentFilterVerificationState ivs =
651                        mIntentFilterVerificationStates.get(verificationId);
652
653                String packageName = ivs.getPackageName();
654
655                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
656                final int filterCount = filters.size();
657                ArraySet<String> domainsSet = new ArraySet<>();
658                for (int m=0; m<filterCount; m++) {
659                    PackageParser.ActivityIntentInfo filter = filters.get(m);
660                    domainsSet.addAll(filter.getHostsList());
661                }
662                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
663                synchronized (mPackages) {
664                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
665                            packageName, domainsList) != null) {
666                        scheduleWriteSettingsLocked();
667                    }
668                }
669                sendVerificationRequest(userId, verificationId, ivs);
670            }
671            mCurrentIntentFilterVerifications.clear();
672        }
673
674        private void sendVerificationRequest(int userId, int verificationId,
675                IntentFilterVerificationState ivs) {
676
677            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
678            verificationIntent.putExtra(
679                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
680                    verificationId);
681            verificationIntent.putExtra(
682                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
683                    getDefaultScheme());
684            verificationIntent.putExtra(
685                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
686                    ivs.getHostsString());
687            verificationIntent.putExtra(
688                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
689                    ivs.getPackageName());
690            verificationIntent.setComponent(mIntentFilterVerifierComponent);
691            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
692
693            UserHandle user = new UserHandle(userId);
694            mContext.sendBroadcastAsUser(verificationIntent, user);
695            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
696                    "Sending IntentFilter verification broadcast");
697        }
698
699        public void receiveVerificationResponse(int verificationId) {
700            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
701
702            final boolean verified = ivs.isVerified();
703
704            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
705            final int count = filters.size();
706            if (DEBUG_DOMAIN_VERIFICATION) {
707                Slog.i(TAG, "Received verification response " + verificationId
708                        + " for " + count + " filters, verified=" + verified);
709            }
710            for (int n=0; n<count; n++) {
711                PackageParser.ActivityIntentInfo filter = filters.get(n);
712                filter.setVerified(verified);
713
714                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
715                        + " verified with result:" + verified + " and hosts:"
716                        + ivs.getHostsString());
717            }
718
719            mIntentFilterVerificationStates.remove(verificationId);
720
721            final String packageName = ivs.getPackageName();
722            IntentFilterVerificationInfo ivi = null;
723
724            synchronized (mPackages) {
725                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
726            }
727            if (ivi == null) {
728                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
729                        + verificationId + " packageName:" + packageName);
730                return;
731            }
732            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
733                    "Updating IntentFilterVerificationInfo for package " + packageName
734                            +" verificationId:" + verificationId);
735
736            synchronized (mPackages) {
737                if (verified) {
738                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
739                } else {
740                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
741                }
742                scheduleWriteSettingsLocked();
743
744                final int userId = ivs.getUserId();
745                if (userId != UserHandle.USER_ALL) {
746                    final int userStatus =
747                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
748
749                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
750                    boolean needUpdate = false;
751
752                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
753                    // already been set by the User thru the Disambiguation dialog
754                    switch (userStatus) {
755                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
756                            if (verified) {
757                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
758                            } else {
759                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
760                            }
761                            needUpdate = true;
762                            break;
763
764                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
765                            if (verified) {
766                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
767                                needUpdate = true;
768                            }
769                            break;
770
771                        default:
772                            // Nothing to do
773                    }
774
775                    if (needUpdate) {
776                        mSettings.updateIntentFilterVerificationStatusLPw(
777                                packageName, updatedStatus, userId);
778                        scheduleWritePackageRestrictionsLocked(userId);
779                    }
780                }
781            }
782        }
783
784        @Override
785        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
786                    ActivityIntentInfo filter, String packageName) {
787            if (!hasValidDomains(filter)) {
788                return false;
789            }
790            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
791            if (ivs == null) {
792                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
793                        packageName);
794            }
795            if (DEBUG_DOMAIN_VERIFICATION) {
796                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
797            }
798            ivs.addFilter(filter);
799            return true;
800        }
801
802        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
803                int userId, int verificationId, String packageName) {
804            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
805                    verifierUid, userId, packageName);
806            ivs.setPendingState();
807            synchronized (mPackages) {
808                mIntentFilterVerificationStates.append(verificationId, ivs);
809                mCurrentIntentFilterVerifications.add(verificationId);
810            }
811            return ivs;
812        }
813    }
814
815    private static boolean hasValidDomains(ActivityIntentInfo filter) {
816        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
817                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
818                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
819    }
820
821    private IntentFilterVerifier mIntentFilterVerifier;
822
823    // Set of pending broadcasts for aggregating enable/disable of components.
824    static class PendingPackageBroadcasts {
825        // for each user id, a map of <package name -> components within that package>
826        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
827
828        public PendingPackageBroadcasts() {
829            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
830        }
831
832        public ArrayList<String> get(int userId, String packageName) {
833            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
834            return packages.get(packageName);
835        }
836
837        public void put(int userId, String packageName, ArrayList<String> components) {
838            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
839            packages.put(packageName, components);
840        }
841
842        public void remove(int userId, String packageName) {
843            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
844            if (packages != null) {
845                packages.remove(packageName);
846            }
847        }
848
849        public void remove(int userId) {
850            mUidMap.remove(userId);
851        }
852
853        public int userIdCount() {
854            return mUidMap.size();
855        }
856
857        public int userIdAt(int n) {
858            return mUidMap.keyAt(n);
859        }
860
861        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
862            return mUidMap.get(userId);
863        }
864
865        public int size() {
866            // total number of pending broadcast entries across all userIds
867            int num = 0;
868            for (int i = 0; i< mUidMap.size(); i++) {
869                num += mUidMap.valueAt(i).size();
870            }
871            return num;
872        }
873
874        public void clear() {
875            mUidMap.clear();
876        }
877
878        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
879            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
880            if (map == null) {
881                map = new ArrayMap<String, ArrayList<String>>();
882                mUidMap.put(userId, map);
883            }
884            return map;
885        }
886    }
887    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
888
889    // Service Connection to remote media container service to copy
890    // package uri's from external media onto secure containers
891    // or internal storage.
892    private IMediaContainerService mContainerService = null;
893
894    static final int SEND_PENDING_BROADCAST = 1;
895    static final int MCS_BOUND = 3;
896    static final int END_COPY = 4;
897    static final int INIT_COPY = 5;
898    static final int MCS_UNBIND = 6;
899    static final int START_CLEANING_PACKAGE = 7;
900    static final int FIND_INSTALL_LOC = 8;
901    static final int POST_INSTALL = 9;
902    static final int MCS_RECONNECT = 10;
903    static final int MCS_GIVE_UP = 11;
904    static final int UPDATED_MEDIA_STATUS = 12;
905    static final int WRITE_SETTINGS = 13;
906    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
907    static final int PACKAGE_VERIFIED = 15;
908    static final int CHECK_PENDING_VERIFICATION = 16;
909    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
910    static final int INTENT_FILTER_VERIFIED = 18;
911
912    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
913
914    // Delay time in millisecs
915    static final int BROADCAST_DELAY = 10 * 1000;
916
917    static UserManagerService sUserManager;
918
919    // Stores a list of users whose package restrictions file needs to be updated
920    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
921
922    final private DefaultContainerConnection mDefContainerConn =
923            new DefaultContainerConnection();
924    class DefaultContainerConnection implements ServiceConnection {
925        public void onServiceConnected(ComponentName name, IBinder service) {
926            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
927            IMediaContainerService imcs =
928                IMediaContainerService.Stub.asInterface(service);
929            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
930        }
931
932        public void onServiceDisconnected(ComponentName name) {
933            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
934        }
935    }
936
937    // Recordkeeping of restore-after-install operations that are currently in flight
938    // between the Package Manager and the Backup Manager
939    class PostInstallData {
940        public InstallArgs args;
941        public PackageInstalledInfo res;
942
943        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
944            args = _a;
945            res = _r;
946        }
947    }
948
949    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
950    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
951
952    // XML tags for backup/restore of various bits of state
953    private static final String TAG_PREFERRED_BACKUP = "pa";
954    private static final String TAG_DEFAULT_APPS = "da";
955    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
956
957    final String mRequiredVerifierPackage;
958    final String mRequiredInstallerPackage;
959
960    private final PackageUsage mPackageUsage = new PackageUsage();
961
962    private class PackageUsage {
963        private static final int WRITE_INTERVAL
964            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
965
966        private final Object mFileLock = new Object();
967        private final AtomicLong mLastWritten = new AtomicLong(0);
968        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
969
970        private boolean mIsHistoricalPackageUsageAvailable = true;
971
972        boolean isHistoricalPackageUsageAvailable() {
973            return mIsHistoricalPackageUsageAvailable;
974        }
975
976        void write(boolean force) {
977            if (force) {
978                writeInternal();
979                return;
980            }
981            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
982                && !DEBUG_DEXOPT) {
983                return;
984            }
985            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
986                new Thread("PackageUsage_DiskWriter") {
987                    @Override
988                    public void run() {
989                        try {
990                            writeInternal();
991                        } finally {
992                            mBackgroundWriteRunning.set(false);
993                        }
994                    }
995                }.start();
996            }
997        }
998
999        private void writeInternal() {
1000            synchronized (mPackages) {
1001                synchronized (mFileLock) {
1002                    AtomicFile file = getFile();
1003                    FileOutputStream f = null;
1004                    try {
1005                        f = file.startWrite();
1006                        BufferedOutputStream out = new BufferedOutputStream(f);
1007                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1008                        StringBuilder sb = new StringBuilder();
1009                        for (PackageParser.Package pkg : mPackages.values()) {
1010                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1011                                continue;
1012                            }
1013                            sb.setLength(0);
1014                            sb.append(pkg.packageName);
1015                            sb.append(' ');
1016                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1017                            sb.append('\n');
1018                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1019                        }
1020                        out.flush();
1021                        file.finishWrite(f);
1022                    } catch (IOException e) {
1023                        if (f != null) {
1024                            file.failWrite(f);
1025                        }
1026                        Log.e(TAG, "Failed to write package usage times", e);
1027                    }
1028                }
1029            }
1030            mLastWritten.set(SystemClock.elapsedRealtime());
1031        }
1032
1033        void readLP() {
1034            synchronized (mFileLock) {
1035                AtomicFile file = getFile();
1036                BufferedInputStream in = null;
1037                try {
1038                    in = new BufferedInputStream(file.openRead());
1039                    StringBuffer sb = new StringBuffer();
1040                    while (true) {
1041                        String packageName = readToken(in, sb, ' ');
1042                        if (packageName == null) {
1043                            break;
1044                        }
1045                        String timeInMillisString = readToken(in, sb, '\n');
1046                        if (timeInMillisString == null) {
1047                            throw new IOException("Failed to find last usage time for package "
1048                                                  + packageName);
1049                        }
1050                        PackageParser.Package pkg = mPackages.get(packageName);
1051                        if (pkg == null) {
1052                            continue;
1053                        }
1054                        long timeInMillis;
1055                        try {
1056                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1057                        } catch (NumberFormatException e) {
1058                            throw new IOException("Failed to parse " + timeInMillisString
1059                                                  + " as a long.", e);
1060                        }
1061                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1062                    }
1063                } catch (FileNotFoundException expected) {
1064                    mIsHistoricalPackageUsageAvailable = false;
1065                } catch (IOException e) {
1066                    Log.w(TAG, "Failed to read package usage times", e);
1067                } finally {
1068                    IoUtils.closeQuietly(in);
1069                }
1070            }
1071            mLastWritten.set(SystemClock.elapsedRealtime());
1072        }
1073
1074        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1075                throws IOException {
1076            sb.setLength(0);
1077            while (true) {
1078                int ch = in.read();
1079                if (ch == -1) {
1080                    if (sb.length() == 0) {
1081                        return null;
1082                    }
1083                    throw new IOException("Unexpected EOF");
1084                }
1085                if (ch == endOfToken) {
1086                    return sb.toString();
1087                }
1088                sb.append((char)ch);
1089            }
1090        }
1091
1092        private AtomicFile getFile() {
1093            File dataDir = Environment.getDataDirectory();
1094            File systemDir = new File(dataDir, "system");
1095            File fname = new File(systemDir, "package-usage.list");
1096            return new AtomicFile(fname);
1097        }
1098    }
1099
1100    class PackageHandler extends Handler {
1101        private boolean mBound = false;
1102        final ArrayList<HandlerParams> mPendingInstalls =
1103            new ArrayList<HandlerParams>();
1104
1105        private boolean connectToService() {
1106            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1107                    " DefaultContainerService");
1108            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1109            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1110            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1111                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1112                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1113                mBound = true;
1114                return true;
1115            }
1116            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1117            return false;
1118        }
1119
1120        private void disconnectService() {
1121            mContainerService = null;
1122            mBound = false;
1123            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1124            mContext.unbindService(mDefContainerConn);
1125            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1126        }
1127
1128        PackageHandler(Looper looper) {
1129            super(looper);
1130        }
1131
1132        public void handleMessage(Message msg) {
1133            try {
1134                doHandleMessage(msg);
1135            } finally {
1136                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1137            }
1138        }
1139
1140        void doHandleMessage(Message msg) {
1141            switch (msg.what) {
1142                case INIT_COPY: {
1143                    HandlerParams params = (HandlerParams) msg.obj;
1144                    int idx = mPendingInstalls.size();
1145                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1146                    // If a bind was already initiated we dont really
1147                    // need to do anything. The pending install
1148                    // will be processed later on.
1149                    if (!mBound) {
1150                        // If this is the only one pending we might
1151                        // have to bind to the service again.
1152                        if (!connectToService()) {
1153                            Slog.e(TAG, "Failed to bind to media container service");
1154                            params.serviceError();
1155                            return;
1156                        } else {
1157                            // Once we bind to the service, the first
1158                            // pending request will be processed.
1159                            mPendingInstalls.add(idx, params);
1160                        }
1161                    } else {
1162                        mPendingInstalls.add(idx, params);
1163                        // Already bound to the service. Just make
1164                        // sure we trigger off processing the first request.
1165                        if (idx == 0) {
1166                            mHandler.sendEmptyMessage(MCS_BOUND);
1167                        }
1168                    }
1169                    break;
1170                }
1171                case MCS_BOUND: {
1172                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1173                    if (msg.obj != null) {
1174                        mContainerService = (IMediaContainerService) msg.obj;
1175                    }
1176                    if (mContainerService == null) {
1177                        if (!mBound) {
1178                            // Something seriously wrong since we are not bound and we are not
1179                            // waiting for connection. Bail out.
1180                            Slog.e(TAG, "Cannot bind to media container service");
1181                            for (HandlerParams params : mPendingInstalls) {
1182                                // Indicate service bind error
1183                                params.serviceError();
1184                            }
1185                            mPendingInstalls.clear();
1186                        } else {
1187                            Slog.w(TAG, "Waiting to connect to media container service");
1188                        }
1189                    } else if (mPendingInstalls.size() > 0) {
1190                        HandlerParams params = mPendingInstalls.get(0);
1191                        if (params != null) {
1192                            if (params.startCopy()) {
1193                                // We are done...  look for more work or to
1194                                // go idle.
1195                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1196                                        "Checking for more work or unbind...");
1197                                // Delete pending install
1198                                if (mPendingInstalls.size() > 0) {
1199                                    mPendingInstalls.remove(0);
1200                                }
1201                                if (mPendingInstalls.size() == 0) {
1202                                    if (mBound) {
1203                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1204                                                "Posting delayed MCS_UNBIND");
1205                                        removeMessages(MCS_UNBIND);
1206                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1207                                        // Unbind after a little delay, to avoid
1208                                        // continual thrashing.
1209                                        sendMessageDelayed(ubmsg, 10000);
1210                                    }
1211                                } else {
1212                                    // There are more pending requests in queue.
1213                                    // Just post MCS_BOUND message to trigger processing
1214                                    // of next pending install.
1215                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1216                                            "Posting MCS_BOUND for next work");
1217                                    mHandler.sendEmptyMessage(MCS_BOUND);
1218                                }
1219                            }
1220                        }
1221                    } else {
1222                        // Should never happen ideally.
1223                        Slog.w(TAG, "Empty queue");
1224                    }
1225                    break;
1226                }
1227                case MCS_RECONNECT: {
1228                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1229                    if (mPendingInstalls.size() > 0) {
1230                        if (mBound) {
1231                            disconnectService();
1232                        }
1233                        if (!connectToService()) {
1234                            Slog.e(TAG, "Failed to bind to media container service");
1235                            for (HandlerParams params : mPendingInstalls) {
1236                                // Indicate service bind error
1237                                params.serviceError();
1238                            }
1239                            mPendingInstalls.clear();
1240                        }
1241                    }
1242                    break;
1243                }
1244                case MCS_UNBIND: {
1245                    // If there is no actual work left, then time to unbind.
1246                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1247
1248                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1249                        if (mBound) {
1250                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1251
1252                            disconnectService();
1253                        }
1254                    } else if (mPendingInstalls.size() > 0) {
1255                        // There are more pending requests in queue.
1256                        // Just post MCS_BOUND message to trigger processing
1257                        // of next pending install.
1258                        mHandler.sendEmptyMessage(MCS_BOUND);
1259                    }
1260
1261                    break;
1262                }
1263                case MCS_GIVE_UP: {
1264                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1265                    mPendingInstalls.remove(0);
1266                    break;
1267                }
1268                case SEND_PENDING_BROADCAST: {
1269                    String packages[];
1270                    ArrayList<String> components[];
1271                    int size = 0;
1272                    int uids[];
1273                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1274                    synchronized (mPackages) {
1275                        if (mPendingBroadcasts == null) {
1276                            return;
1277                        }
1278                        size = mPendingBroadcasts.size();
1279                        if (size <= 0) {
1280                            // Nothing to be done. Just return
1281                            return;
1282                        }
1283                        packages = new String[size];
1284                        components = new ArrayList[size];
1285                        uids = new int[size];
1286                        int i = 0;  // filling out the above arrays
1287
1288                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1289                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1290                            Iterator<Map.Entry<String, ArrayList<String>>> it
1291                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1292                                            .entrySet().iterator();
1293                            while (it.hasNext() && i < size) {
1294                                Map.Entry<String, ArrayList<String>> ent = it.next();
1295                                packages[i] = ent.getKey();
1296                                components[i] = ent.getValue();
1297                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1298                                uids[i] = (ps != null)
1299                                        ? UserHandle.getUid(packageUserId, ps.appId)
1300                                        : -1;
1301                                i++;
1302                            }
1303                        }
1304                        size = i;
1305                        mPendingBroadcasts.clear();
1306                    }
1307                    // Send broadcasts
1308                    for (int i = 0; i < size; i++) {
1309                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1310                    }
1311                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1312                    break;
1313                }
1314                case START_CLEANING_PACKAGE: {
1315                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1316                    final String packageName = (String)msg.obj;
1317                    final int userId = msg.arg1;
1318                    final boolean andCode = msg.arg2 != 0;
1319                    synchronized (mPackages) {
1320                        if (userId == UserHandle.USER_ALL) {
1321                            int[] users = sUserManager.getUserIds();
1322                            for (int user : users) {
1323                                mSettings.addPackageToCleanLPw(
1324                                        new PackageCleanItem(user, packageName, andCode));
1325                            }
1326                        } else {
1327                            mSettings.addPackageToCleanLPw(
1328                                    new PackageCleanItem(userId, packageName, andCode));
1329                        }
1330                    }
1331                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1332                    startCleaningPackages();
1333                } break;
1334                case POST_INSTALL: {
1335                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1336                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1337                    mRunningInstalls.delete(msg.arg1);
1338                    boolean deleteOld = false;
1339
1340                    if (data != null) {
1341                        InstallArgs args = data.args;
1342                        PackageInstalledInfo res = data.res;
1343
1344                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1345                            final String packageName = res.pkg.applicationInfo.packageName;
1346                            res.removedInfo.sendBroadcast(false, true, false);
1347                            Bundle extras = new Bundle(1);
1348                            extras.putInt(Intent.EXTRA_UID, res.uid);
1349
1350                            // Now that we successfully installed the package, grant runtime
1351                            // permissions if requested before broadcasting the install.
1352                            if ((args.installFlags
1353                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1354                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1355                                        args.installGrantPermissions);
1356                            }
1357
1358                            // Determine the set of users who are adding this
1359                            // package for the first time vs. those who are seeing
1360                            // an update.
1361                            int[] firstUsers;
1362                            int[] updateUsers = new int[0];
1363                            if (res.origUsers == null || res.origUsers.length == 0) {
1364                                firstUsers = res.newUsers;
1365                            } else {
1366                                firstUsers = new int[0];
1367                                for (int i=0; i<res.newUsers.length; i++) {
1368                                    int user = res.newUsers[i];
1369                                    boolean isNew = true;
1370                                    for (int j=0; j<res.origUsers.length; j++) {
1371                                        if (res.origUsers[j] == user) {
1372                                            isNew = false;
1373                                            break;
1374                                        }
1375                                    }
1376                                    if (isNew) {
1377                                        int[] newFirst = new int[firstUsers.length+1];
1378                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1379                                                firstUsers.length);
1380                                        newFirst[firstUsers.length] = user;
1381                                        firstUsers = newFirst;
1382                                    } else {
1383                                        int[] newUpdate = new int[updateUsers.length+1];
1384                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1385                                                updateUsers.length);
1386                                        newUpdate[updateUsers.length] = user;
1387                                        updateUsers = newUpdate;
1388                                    }
1389                                }
1390                            }
1391                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1392                                    packageName, extras, null, null, firstUsers);
1393                            final boolean update = res.removedInfo.removedPackage != null;
1394                            if (update) {
1395                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1396                            }
1397                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1398                                    packageName, extras, null, null, updateUsers);
1399                            if (update) {
1400                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1401                                        packageName, extras, null, null, updateUsers);
1402                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1403                                        null, null, packageName, null, updateUsers);
1404
1405                                // treat asec-hosted packages like removable media on upgrade
1406                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1407                                    if (DEBUG_INSTALL) {
1408                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1409                                                + " is ASEC-hosted -> AVAILABLE");
1410                                    }
1411                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1412                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1413                                    pkgList.add(packageName);
1414                                    sendResourcesChangedBroadcast(true, true,
1415                                            pkgList,uidArray, null);
1416                                }
1417                            }
1418                            if (res.removedInfo.args != null) {
1419                                // Remove the replaced package's older resources safely now
1420                                deleteOld = true;
1421                            }
1422
1423                            // If this app is a browser and it's newly-installed for some
1424                            // users, clear any default-browser state in those users
1425                            if (firstUsers.length > 0) {
1426                                // the app's nature doesn't depend on the user, so we can just
1427                                // check its browser nature in any user and generalize.
1428                                if (packageIsBrowser(packageName, firstUsers[0])) {
1429                                    synchronized (mPackages) {
1430                                        for (int userId : firstUsers) {
1431                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1432                                        }
1433                                    }
1434                                }
1435                            }
1436                            // Log current value of "unknown sources" setting
1437                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1438                                getUnknownSourcesSettings());
1439                        }
1440                        // Force a gc to clear up things
1441                        Runtime.getRuntime().gc();
1442                        // We delete after a gc for applications  on sdcard.
1443                        if (deleteOld) {
1444                            synchronized (mInstallLock) {
1445                                res.removedInfo.args.doPostDeleteLI(true);
1446                            }
1447                        }
1448                        if (args.observer != null) {
1449                            try {
1450                                Bundle extras = extrasForInstallResult(res);
1451                                args.observer.onPackageInstalled(res.name, res.returnCode,
1452                                        res.returnMsg, extras);
1453                            } catch (RemoteException e) {
1454                                Slog.i(TAG, "Observer no longer exists.");
1455                            }
1456                        }
1457                    } else {
1458                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1459                    }
1460                } break;
1461                case UPDATED_MEDIA_STATUS: {
1462                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1463                    boolean reportStatus = msg.arg1 == 1;
1464                    boolean doGc = msg.arg2 == 1;
1465                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1466                    if (doGc) {
1467                        // Force a gc to clear up stale containers.
1468                        Runtime.getRuntime().gc();
1469                    }
1470                    if (msg.obj != null) {
1471                        @SuppressWarnings("unchecked")
1472                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1473                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1474                        // Unload containers
1475                        unloadAllContainers(args);
1476                    }
1477                    if (reportStatus) {
1478                        try {
1479                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1480                            PackageHelper.getMountService().finishMediaUpdate();
1481                        } catch (RemoteException e) {
1482                            Log.e(TAG, "MountService not running?");
1483                        }
1484                    }
1485                } break;
1486                case WRITE_SETTINGS: {
1487                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1488                    synchronized (mPackages) {
1489                        removeMessages(WRITE_SETTINGS);
1490                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1491                        mSettings.writeLPr();
1492                        mDirtyUsers.clear();
1493                    }
1494                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1495                } break;
1496                case WRITE_PACKAGE_RESTRICTIONS: {
1497                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1498                    synchronized (mPackages) {
1499                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1500                        for (int userId : mDirtyUsers) {
1501                            mSettings.writePackageRestrictionsLPr(userId);
1502                        }
1503                        mDirtyUsers.clear();
1504                    }
1505                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1506                } break;
1507                case CHECK_PENDING_VERIFICATION: {
1508                    final int verificationId = msg.arg1;
1509                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1510
1511                    if ((state != null) && !state.timeoutExtended()) {
1512                        final InstallArgs args = state.getInstallArgs();
1513                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1514
1515                        Slog.i(TAG, "Verification timed out for " + originUri);
1516                        mPendingVerification.remove(verificationId);
1517
1518                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1519
1520                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1521                            Slog.i(TAG, "Continuing with installation of " + originUri);
1522                            state.setVerifierResponse(Binder.getCallingUid(),
1523                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1524                            broadcastPackageVerified(verificationId, originUri,
1525                                    PackageManager.VERIFICATION_ALLOW,
1526                                    state.getInstallArgs().getUser());
1527                            try {
1528                                ret = args.copyApk(mContainerService, true);
1529                            } catch (RemoteException e) {
1530                                Slog.e(TAG, "Could not contact the ContainerService");
1531                            }
1532                        } else {
1533                            broadcastPackageVerified(verificationId, originUri,
1534                                    PackageManager.VERIFICATION_REJECT,
1535                                    state.getInstallArgs().getUser());
1536                        }
1537
1538                        processPendingInstall(args, ret);
1539                        mHandler.sendEmptyMessage(MCS_UNBIND);
1540                    }
1541                    break;
1542                }
1543                case PACKAGE_VERIFIED: {
1544                    final int verificationId = msg.arg1;
1545
1546                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1547                    if (state == null) {
1548                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1549                        break;
1550                    }
1551
1552                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1553
1554                    state.setVerifierResponse(response.callerUid, response.code);
1555
1556                    if (state.isVerificationComplete()) {
1557                        mPendingVerification.remove(verificationId);
1558
1559                        final InstallArgs args = state.getInstallArgs();
1560                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1561
1562                        int ret;
1563                        if (state.isInstallAllowed()) {
1564                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1565                            broadcastPackageVerified(verificationId, originUri,
1566                                    response.code, state.getInstallArgs().getUser());
1567                            try {
1568                                ret = args.copyApk(mContainerService, true);
1569                            } catch (RemoteException e) {
1570                                Slog.e(TAG, "Could not contact the ContainerService");
1571                            }
1572                        } else {
1573                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1574                        }
1575
1576                        processPendingInstall(args, ret);
1577
1578                        mHandler.sendEmptyMessage(MCS_UNBIND);
1579                    }
1580
1581                    break;
1582                }
1583                case START_INTENT_FILTER_VERIFICATIONS: {
1584                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1585                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1586                            params.replacing, params.pkg);
1587                    break;
1588                }
1589                case INTENT_FILTER_VERIFIED: {
1590                    final int verificationId = msg.arg1;
1591
1592                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1593                            verificationId);
1594                    if (state == null) {
1595                        Slog.w(TAG, "Invalid IntentFilter verification token "
1596                                + verificationId + " received");
1597                        break;
1598                    }
1599
1600                    final int userId = state.getUserId();
1601
1602                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1603                            "Processing IntentFilter verification with token:"
1604                            + verificationId + " and userId:" + userId);
1605
1606                    final IntentFilterVerificationResponse response =
1607                            (IntentFilterVerificationResponse) msg.obj;
1608
1609                    state.setVerifierResponse(response.callerUid, response.code);
1610
1611                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1612                            "IntentFilter verification with token:" + verificationId
1613                            + " and userId:" + userId
1614                            + " is settings verifier response with response code:"
1615                            + response.code);
1616
1617                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1618                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1619                                + response.getFailedDomainsString());
1620                    }
1621
1622                    if (state.isVerificationComplete()) {
1623                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1624                    } else {
1625                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1626                                "IntentFilter verification with token:" + verificationId
1627                                + " was not said to be complete");
1628                    }
1629
1630                    break;
1631                }
1632            }
1633        }
1634    }
1635
1636    private StorageEventListener mStorageListener = new StorageEventListener() {
1637        @Override
1638        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1639            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1640                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1641                    final String volumeUuid = vol.getFsUuid();
1642
1643                    // Clean up any users or apps that were removed or recreated
1644                    // while this volume was missing
1645                    reconcileUsers(volumeUuid);
1646                    reconcileApps(volumeUuid);
1647
1648                    // Clean up any install sessions that expired or were
1649                    // cancelled while this volume was missing
1650                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1651
1652                    loadPrivatePackages(vol);
1653
1654                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1655                    unloadPrivatePackages(vol);
1656                }
1657            }
1658
1659            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1660                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1661                    updateExternalMediaStatus(true, false);
1662                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1663                    updateExternalMediaStatus(false, false);
1664                }
1665            }
1666        }
1667
1668        @Override
1669        public void onVolumeForgotten(String fsUuid) {
1670            if (TextUtils.isEmpty(fsUuid)) {
1671                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1672                return;
1673            }
1674
1675            // Remove any apps installed on the forgotten volume
1676            synchronized (mPackages) {
1677                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1678                for (PackageSetting ps : packages) {
1679                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1680                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1681                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1682                }
1683
1684                mSettings.onVolumeForgotten(fsUuid);
1685                mSettings.writeLPr();
1686            }
1687        }
1688    };
1689
1690    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1691            String[] grantedPermissions) {
1692        if (userId >= UserHandle.USER_OWNER) {
1693            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1694        } else if (userId == UserHandle.USER_ALL) {
1695            final int[] userIds;
1696            synchronized (mPackages) {
1697                userIds = UserManagerService.getInstance().getUserIds();
1698            }
1699            for (int someUserId : userIds) {
1700                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1701            }
1702        }
1703
1704        // We could have touched GID membership, so flush out packages.list
1705        synchronized (mPackages) {
1706            mSettings.writePackageListLPr();
1707        }
1708    }
1709
1710    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1711            String[] grantedPermissions) {
1712        SettingBase sb = (SettingBase) pkg.mExtras;
1713        if (sb == null) {
1714            return;
1715        }
1716
1717        PermissionsState permissionsState = sb.getPermissionsState();
1718
1719        for (String permission : pkg.requestedPermissions) {
1720            BasePermission bp = mSettings.mPermissions.get(permission);
1721            if (bp != null && bp.isRuntime() && (grantedPermissions == null
1722                    || ArrayUtils.contains(grantedPermissions, permission))) {
1723                permissionsState.grantRuntimePermission(bp, userId);
1724            }
1725        }
1726    }
1727
1728    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1729        Bundle extras = null;
1730        switch (res.returnCode) {
1731            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1732                extras = new Bundle();
1733                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1734                        res.origPermission);
1735                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1736                        res.origPackage);
1737                break;
1738            }
1739            case PackageManager.INSTALL_SUCCEEDED: {
1740                extras = new Bundle();
1741                extras.putBoolean(Intent.EXTRA_REPLACING,
1742                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1743                break;
1744            }
1745        }
1746        return extras;
1747    }
1748
1749    void scheduleWriteSettingsLocked() {
1750        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1751            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1752        }
1753    }
1754
1755    void scheduleWritePackageRestrictionsLocked(int userId) {
1756        if (!sUserManager.exists(userId)) return;
1757        mDirtyUsers.add(userId);
1758        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1759            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1760        }
1761    }
1762
1763    public static PackageManagerService main(Context context, Installer installer,
1764            boolean factoryTest, boolean onlyCore) {
1765        PackageManagerService m = new PackageManagerService(context, installer,
1766                factoryTest, onlyCore);
1767        ServiceManager.addService("package", m);
1768        return m;
1769    }
1770
1771    static String[] splitString(String str, char sep) {
1772        int count = 1;
1773        int i = 0;
1774        while ((i=str.indexOf(sep, i)) >= 0) {
1775            count++;
1776            i++;
1777        }
1778
1779        String[] res = new String[count];
1780        i=0;
1781        count = 0;
1782        int lastI=0;
1783        while ((i=str.indexOf(sep, i)) >= 0) {
1784            res[count] = str.substring(lastI, i);
1785            count++;
1786            i++;
1787            lastI = i;
1788        }
1789        res[count] = str.substring(lastI, str.length());
1790        return res;
1791    }
1792
1793    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1794        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1795                Context.DISPLAY_SERVICE);
1796        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1797    }
1798
1799    public PackageManagerService(Context context, Installer installer,
1800            boolean factoryTest, boolean onlyCore) {
1801        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1802                SystemClock.uptimeMillis());
1803
1804        if (mSdkVersion <= 0) {
1805            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1806        }
1807
1808        mContext = context;
1809        mFactoryTest = factoryTest;
1810        mOnlyCore = onlyCore;
1811        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1812        mMetrics = new DisplayMetrics();
1813        mSettings = new Settings(mPackages);
1814        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1815                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1816        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1817                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1818        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1819                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1820        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1821                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1822        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1823                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1824        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1825                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1826
1827        // TODO: add a property to control this?
1828        long dexOptLRUThresholdInMinutes;
1829        if (mLazyDexOpt) {
1830            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1831        } else {
1832            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1833        }
1834        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1835
1836        String separateProcesses = SystemProperties.get("debug.separate_processes");
1837        if (separateProcesses != null && separateProcesses.length() > 0) {
1838            if ("*".equals(separateProcesses)) {
1839                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1840                mSeparateProcesses = null;
1841                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1842            } else {
1843                mDefParseFlags = 0;
1844                mSeparateProcesses = separateProcesses.split(",");
1845                Slog.w(TAG, "Running with debug.separate_processes: "
1846                        + separateProcesses);
1847            }
1848        } else {
1849            mDefParseFlags = 0;
1850            mSeparateProcesses = null;
1851        }
1852
1853        mInstaller = installer;
1854        mPackageDexOptimizer = new PackageDexOptimizer(this);
1855        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1856
1857        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1858                FgThread.get().getLooper());
1859
1860        getDefaultDisplayMetrics(context, mMetrics);
1861
1862        SystemConfig systemConfig = SystemConfig.getInstance();
1863        mGlobalGids = systemConfig.getGlobalGids();
1864        mSystemPermissions = systemConfig.getSystemPermissions();
1865        mAvailableFeatures = systemConfig.getAvailableFeatures();
1866
1867        synchronized (mInstallLock) {
1868        // writer
1869        synchronized (mPackages) {
1870            mHandlerThread = new ServiceThread(TAG,
1871                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1872            mHandlerThread.start();
1873            mHandler = new PackageHandler(mHandlerThread.getLooper());
1874            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1875
1876            File dataDir = Environment.getDataDirectory();
1877            mAppDataDir = new File(dataDir, "data");
1878            mAppInstallDir = new File(dataDir, "app");
1879            mAppLib32InstallDir = new File(dataDir, "app-lib");
1880            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1881            mUserAppDataDir = new File(dataDir, "user");
1882            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1883
1884            sUserManager = new UserManagerService(context, this,
1885                    mInstallLock, mPackages);
1886
1887            // Propagate permission configuration in to package manager.
1888            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1889                    = systemConfig.getPermissions();
1890            for (int i=0; i<permConfig.size(); i++) {
1891                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1892                BasePermission bp = mSettings.mPermissions.get(perm.name);
1893                if (bp == null) {
1894                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1895                    mSettings.mPermissions.put(perm.name, bp);
1896                }
1897                if (perm.gids != null) {
1898                    bp.setGids(perm.gids, perm.perUser);
1899                }
1900            }
1901
1902            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1903            for (int i=0; i<libConfig.size(); i++) {
1904                mSharedLibraries.put(libConfig.keyAt(i),
1905                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1906            }
1907
1908            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1909
1910            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1911                    mSdkVersion, mOnlyCore);
1912
1913            String customResolverActivity = Resources.getSystem().getString(
1914                    R.string.config_customResolverActivity);
1915            if (TextUtils.isEmpty(customResolverActivity)) {
1916                customResolverActivity = null;
1917            } else {
1918                mCustomResolverComponentName = ComponentName.unflattenFromString(
1919                        customResolverActivity);
1920            }
1921
1922            long startTime = SystemClock.uptimeMillis();
1923
1924            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1925                    startTime);
1926
1927            // Set flag to monitor and not change apk file paths when
1928            // scanning install directories.
1929            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1930
1931            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1932
1933            /**
1934             * Add everything in the in the boot class path to the
1935             * list of process files because dexopt will have been run
1936             * if necessary during zygote startup.
1937             */
1938            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1939            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1940
1941            if (bootClassPath != null) {
1942                String[] bootClassPathElements = splitString(bootClassPath, ':');
1943                for (String element : bootClassPathElements) {
1944                    alreadyDexOpted.add(element);
1945                }
1946            } else {
1947                Slog.w(TAG, "No BOOTCLASSPATH found!");
1948            }
1949
1950            if (systemServerClassPath != null) {
1951                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1952                for (String element : systemServerClassPathElements) {
1953                    alreadyDexOpted.add(element);
1954                }
1955            } else {
1956                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1957            }
1958
1959            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1960            final String[] dexCodeInstructionSets =
1961                    getDexCodeInstructionSets(
1962                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1963
1964            /**
1965             * Ensure all external libraries have had dexopt run on them.
1966             */
1967            if (mSharedLibraries.size() > 0) {
1968                // NOTE: For now, we're compiling these system "shared libraries"
1969                // (and framework jars) into all available architectures. It's possible
1970                // to compile them only when we come across an app that uses them (there's
1971                // already logic for that in scanPackageLI) but that adds some complexity.
1972                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1973                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1974                        final String lib = libEntry.path;
1975                        if (lib == null) {
1976                            continue;
1977                        }
1978
1979                        try {
1980                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1981                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1982                                alreadyDexOpted.add(lib);
1983                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
1984                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
1985                            }
1986                        } catch (FileNotFoundException e) {
1987                            Slog.w(TAG, "Library not found: " + lib);
1988                        } catch (IOException e) {
1989                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1990                                    + e.getMessage());
1991                        }
1992                    }
1993                }
1994            }
1995
1996            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1997
1998            // Gross hack for now: we know this file doesn't contain any
1999            // code, so don't dexopt it to avoid the resulting log spew.
2000            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
2001
2002            // Gross hack for now: we know this file is only part of
2003            // the boot class path for art, so don't dexopt it to
2004            // avoid the resulting log spew.
2005            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
2006
2007            /**
2008             * There are a number of commands implemented in Java, which
2009             * we currently need to do the dexopt on so that they can be
2010             * run from a non-root shell.
2011             */
2012            String[] frameworkFiles = frameworkDir.list();
2013            if (frameworkFiles != null) {
2014                // TODO: We could compile these only for the most preferred ABI. We should
2015                // first double check that the dex files for these commands are not referenced
2016                // by other system apps.
2017                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2018                    for (int i=0; i<frameworkFiles.length; i++) {
2019                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2020                        String path = libPath.getPath();
2021                        // Skip the file if we already did it.
2022                        if (alreadyDexOpted.contains(path)) {
2023                            continue;
2024                        }
2025                        // Skip the file if it is not a type we want to dexopt.
2026                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2027                            continue;
2028                        }
2029                        try {
2030                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2031                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2032                                mInstaller.dexopt(path, Process.SYSTEM_UID, dexCodeInstructionSet,
2033                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2034                            }
2035                        } catch (FileNotFoundException e) {
2036                            Slog.w(TAG, "Jar not found: " + path);
2037                        } catch (IOException e) {
2038                            Slog.w(TAG, "Exception reading jar: " + path, e);
2039                        }
2040                    }
2041                }
2042            }
2043
2044            final VersionInfo ver = mSettings.getInternalVersion();
2045            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2046            // when upgrading from pre-M, promote system app permissions from install to runtime
2047            mPromoteSystemApps =
2048                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2049
2050            // save off the names of pre-existing system packages prior to scanning; we don't
2051            // want to automatically grant runtime permissions for new system apps
2052            if (mPromoteSystemApps) {
2053                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2054                while (pkgSettingIter.hasNext()) {
2055                    PackageSetting ps = pkgSettingIter.next();
2056                    if (isSystemApp(ps)) {
2057                        mExistingSystemPackages.add(ps.name);
2058                    }
2059                }
2060            }
2061
2062            // Collect vendor overlay packages.
2063            // (Do this before scanning any apps.)
2064            // For security and version matching reason, only consider
2065            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2066            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2067            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2068                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2069
2070            // Find base frameworks (resource packages without code).
2071            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2072                    | PackageParser.PARSE_IS_SYSTEM_DIR
2073                    | PackageParser.PARSE_IS_PRIVILEGED,
2074                    scanFlags | SCAN_NO_DEX, 0);
2075
2076            // Collected privileged system packages.
2077            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2078            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2079                    | PackageParser.PARSE_IS_SYSTEM_DIR
2080                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2081
2082            // Collect ordinary system packages.
2083            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2084            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2085                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2086
2087            // Collect all vendor packages.
2088            File vendorAppDir = new File("/vendor/app");
2089            try {
2090                vendorAppDir = vendorAppDir.getCanonicalFile();
2091            } catch (IOException e) {
2092                // failed to look up canonical path, continue with original one
2093            }
2094            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2095                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2096
2097            // Collect all OEM packages.
2098            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2099            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2100                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2101
2102            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2103            mInstaller.moveFiles();
2104
2105            // Prune any system packages that no longer exist.
2106            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2107            if (!mOnlyCore) {
2108                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2109                while (psit.hasNext()) {
2110                    PackageSetting ps = psit.next();
2111
2112                    /*
2113                     * If this is not a system app, it can't be a
2114                     * disable system app.
2115                     */
2116                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2117                        continue;
2118                    }
2119
2120                    /*
2121                     * If the package is scanned, it's not erased.
2122                     */
2123                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2124                    if (scannedPkg != null) {
2125                        /*
2126                         * If the system app is both scanned and in the
2127                         * disabled packages list, then it must have been
2128                         * added via OTA. Remove it from the currently
2129                         * scanned package so the previously user-installed
2130                         * application can be scanned.
2131                         */
2132                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2133                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2134                                    + ps.name + "; removing system app.  Last known codePath="
2135                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2136                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2137                                    + scannedPkg.mVersionCode);
2138                            removePackageLI(ps, true);
2139                            mExpectingBetter.put(ps.name, ps.codePath);
2140                        }
2141
2142                        continue;
2143                    }
2144
2145                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2146                        psit.remove();
2147                        logCriticalInfo(Log.WARN, "System package " + ps.name
2148                                + " no longer exists; wiping its data");
2149                        removeDataDirsLI(null, ps.name);
2150                    } else {
2151                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2152                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2153                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2154                        }
2155                    }
2156                }
2157            }
2158
2159            //look for any incomplete package installations
2160            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2161            //clean up list
2162            for(int i = 0; i < deletePkgsList.size(); i++) {
2163                //clean up here
2164                cleanupInstallFailedPackage(deletePkgsList.get(i));
2165            }
2166            //delete tmp files
2167            deleteTempPackageFiles();
2168
2169            // Remove any shared userIDs that have no associated packages
2170            mSettings.pruneSharedUsersLPw();
2171
2172            if (!mOnlyCore) {
2173                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2174                        SystemClock.uptimeMillis());
2175                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2176
2177                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2178                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2179
2180                /**
2181                 * Remove disable package settings for any updated system
2182                 * apps that were removed via an OTA. If they're not a
2183                 * previously-updated app, remove them completely.
2184                 * Otherwise, just revoke their system-level permissions.
2185                 */
2186                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2187                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2188                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2189
2190                    String msg;
2191                    if (deletedPkg == null) {
2192                        msg = "Updated system package " + deletedAppName
2193                                + " no longer exists; wiping its data";
2194                        removeDataDirsLI(null, deletedAppName);
2195                    } else {
2196                        msg = "Updated system app + " + deletedAppName
2197                                + " no longer present; removing system privileges for "
2198                                + deletedAppName;
2199
2200                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2201
2202                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2203                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2204                    }
2205                    logCriticalInfo(Log.WARN, msg);
2206                }
2207
2208                /**
2209                 * Make sure all system apps that we expected to appear on
2210                 * the userdata partition actually showed up. If they never
2211                 * appeared, crawl back and revive the system version.
2212                 */
2213                for (int i = 0; i < mExpectingBetter.size(); i++) {
2214                    final String packageName = mExpectingBetter.keyAt(i);
2215                    if (!mPackages.containsKey(packageName)) {
2216                        final File scanFile = mExpectingBetter.valueAt(i);
2217
2218                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2219                                + " but never showed up; reverting to system");
2220
2221                        final int reparseFlags;
2222                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2223                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2224                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2225                                    | PackageParser.PARSE_IS_PRIVILEGED;
2226                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2227                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2228                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2229                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2230                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2231                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2232                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2233                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2234                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2235                        } else {
2236                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2237                            continue;
2238                        }
2239
2240                        mSettings.enableSystemPackageLPw(packageName);
2241
2242                        try {
2243                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2244                        } catch (PackageManagerException e) {
2245                            Slog.e(TAG, "Failed to parse original system package: "
2246                                    + e.getMessage());
2247                        }
2248                    }
2249                }
2250            }
2251            mExpectingBetter.clear();
2252
2253            // Now that we know all of the shared libraries, update all clients to have
2254            // the correct library paths.
2255            updateAllSharedLibrariesLPw();
2256
2257            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2258                // NOTE: We ignore potential failures here during a system scan (like
2259                // the rest of the commands above) because there's precious little we
2260                // can do about it. A settings error is reported, though.
2261                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2262                        false /* force dexopt */, false /* defer dexopt */,
2263                        false /* boot complete */);
2264            }
2265
2266            // Now that we know all the packages we are keeping,
2267            // read and update their last usage times.
2268            mPackageUsage.readLP();
2269
2270            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2271                    SystemClock.uptimeMillis());
2272            Slog.i(TAG, "Time to scan packages: "
2273                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2274                    + " seconds");
2275
2276            // If the platform SDK has changed since the last time we booted,
2277            // we need to re-grant app permission to catch any new ones that
2278            // appear.  This is really a hack, and means that apps can in some
2279            // cases get permissions that the user didn't initially explicitly
2280            // allow...  it would be nice to have some better way to handle
2281            // this situation.
2282            int updateFlags = UPDATE_PERMISSIONS_ALL;
2283            if (ver.sdkVersion != mSdkVersion) {
2284                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2285                        + mSdkVersion + "; regranting permissions for internal storage");
2286                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2287            }
2288            updatePermissionsLPw(null, null, updateFlags);
2289            ver.sdkVersion = mSdkVersion;
2290            // clear only after permissions have been updated
2291            mExistingSystemPackages.clear();
2292            mPromoteSystemApps = false;
2293
2294            // If this is the first boot, and it is a normal boot, then
2295            // we need to initialize the default preferred apps.
2296            if (!mRestoredSettings && !onlyCore) {
2297                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2298                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2299                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2300            }
2301
2302            // If this is first boot after an OTA, and a normal boot, then
2303            // we need to clear code cache directories.
2304            if (mIsUpgrade && !onlyCore) {
2305                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2306                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2307                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2308                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2309                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2310                    }
2311                }
2312                ver.fingerprint = Build.FINGERPRINT;
2313            }
2314
2315            checkDefaultBrowser();
2316
2317            // All the changes are done during package scanning.
2318            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2319
2320            // can downgrade to reader
2321            mSettings.writeLPr();
2322
2323            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2324                    SystemClock.uptimeMillis());
2325
2326            mRequiredVerifierPackage = getRequiredVerifierLPr();
2327            mRequiredInstallerPackage = getRequiredInstallerLPr();
2328
2329            mInstallerService = new PackageInstallerService(context, this);
2330
2331            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2332            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2333                    mIntentFilterVerifierComponent);
2334
2335        } // synchronized (mPackages)
2336        } // synchronized (mInstallLock)
2337
2338        // Now after opening every single application zip, make sure they
2339        // are all flushed.  Not really needed, but keeps things nice and
2340        // tidy.
2341        Runtime.getRuntime().gc();
2342
2343        // Expose private service for system components to use.
2344        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2345    }
2346
2347    @Override
2348    public boolean isFirstBoot() {
2349        return !mRestoredSettings;
2350    }
2351
2352    @Override
2353    public boolean isOnlyCoreApps() {
2354        return mOnlyCore;
2355    }
2356
2357    @Override
2358    public boolean isUpgrade() {
2359        return mIsUpgrade;
2360    }
2361
2362    private String getRequiredVerifierLPr() {
2363        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2364        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2365                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2366
2367        String requiredVerifier = null;
2368
2369        final int N = receivers.size();
2370        for (int i = 0; i < N; i++) {
2371            final ResolveInfo info = receivers.get(i);
2372
2373            if (info.activityInfo == null) {
2374                continue;
2375            }
2376
2377            final String packageName = info.activityInfo.packageName;
2378
2379            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2380                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2381                continue;
2382            }
2383
2384            if (requiredVerifier != null) {
2385                throw new RuntimeException("There can be only one required verifier");
2386            }
2387
2388            requiredVerifier = packageName;
2389        }
2390
2391        return requiredVerifier;
2392    }
2393
2394    private String getRequiredInstallerLPr() {
2395        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2396        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2397        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2398
2399        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2400                PACKAGE_MIME_TYPE, 0, 0);
2401
2402        String requiredInstaller = null;
2403
2404        final int N = installers.size();
2405        for (int i = 0; i < N; i++) {
2406            final ResolveInfo info = installers.get(i);
2407            final String packageName = info.activityInfo.packageName;
2408
2409            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2410                continue;
2411            }
2412
2413            if (requiredInstaller != null) {
2414                throw new RuntimeException("There must be one required installer");
2415            }
2416
2417            requiredInstaller = packageName;
2418        }
2419
2420        if (requiredInstaller == null) {
2421            throw new RuntimeException("There must be one required installer");
2422        }
2423
2424        return requiredInstaller;
2425    }
2426
2427    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2428        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2429        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2430                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2431
2432        ComponentName verifierComponentName = null;
2433
2434        int priority = -1000;
2435        final int N = receivers.size();
2436        for (int i = 0; i < N; i++) {
2437            final ResolveInfo info = receivers.get(i);
2438
2439            if (info.activityInfo == null) {
2440                continue;
2441            }
2442
2443            final String packageName = info.activityInfo.packageName;
2444
2445            final PackageSetting ps = mSettings.mPackages.get(packageName);
2446            if (ps == null) {
2447                continue;
2448            }
2449
2450            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2451                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2452                continue;
2453            }
2454
2455            // Select the IntentFilterVerifier with the highest priority
2456            if (priority < info.priority) {
2457                priority = info.priority;
2458                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2459                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2460                        + verifierComponentName + " with priority: " + info.priority);
2461            }
2462        }
2463
2464        return verifierComponentName;
2465    }
2466
2467    private void primeDomainVerificationsLPw(int userId) {
2468        if (DEBUG_DOMAIN_VERIFICATION) {
2469            Slog.d(TAG, "Priming domain verifications in user " + userId);
2470        }
2471
2472        SystemConfig systemConfig = SystemConfig.getInstance();
2473        ArraySet<String> packages = systemConfig.getLinkedApps();
2474        ArraySet<String> domains = new ArraySet<String>();
2475
2476        for (String packageName : packages) {
2477            PackageParser.Package pkg = mPackages.get(packageName);
2478            if (pkg != null) {
2479                if (!pkg.isSystemApp()) {
2480                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2481                    continue;
2482                }
2483
2484                domains.clear();
2485                for (PackageParser.Activity a : pkg.activities) {
2486                    for (ActivityIntentInfo filter : a.intents) {
2487                        if (hasValidDomains(filter)) {
2488                            domains.addAll(filter.getHostsList());
2489                        }
2490                    }
2491                }
2492
2493                if (domains.size() > 0) {
2494                    if (DEBUG_DOMAIN_VERIFICATION) {
2495                        Slog.v(TAG, "      + " + packageName);
2496                    }
2497                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2498                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2499                    // and then 'always' in the per-user state actually used for intent resolution.
2500                    final IntentFilterVerificationInfo ivi;
2501                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2502                            new ArrayList<String>(domains));
2503                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2504                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2505                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2506                } else {
2507                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2508                            + "' does not handle web links");
2509                }
2510            } else {
2511                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2512            }
2513        }
2514
2515        scheduleWritePackageRestrictionsLocked(userId);
2516        scheduleWriteSettingsLocked();
2517    }
2518
2519    private void applyFactoryDefaultBrowserLPw(int userId) {
2520        // The default browser app's package name is stored in a string resource,
2521        // with a product-specific overlay used for vendor customization.
2522        String browserPkg = mContext.getResources().getString(
2523                com.android.internal.R.string.default_browser);
2524        if (!TextUtils.isEmpty(browserPkg)) {
2525            // non-empty string => required to be a known package
2526            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2527            if (ps == null) {
2528                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2529                browserPkg = null;
2530            } else {
2531                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2532            }
2533        }
2534
2535        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2536        // default.  If there's more than one, just leave everything alone.
2537        if (browserPkg == null) {
2538            calculateDefaultBrowserLPw(userId);
2539        }
2540    }
2541
2542    private void calculateDefaultBrowserLPw(int userId) {
2543        List<String> allBrowsers = resolveAllBrowserApps(userId);
2544        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2545        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2546    }
2547
2548    private List<String> resolveAllBrowserApps(int userId) {
2549        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2550        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2551                PackageManager.MATCH_ALL, userId);
2552
2553        final int count = list.size();
2554        List<String> result = new ArrayList<String>(count);
2555        for (int i=0; i<count; i++) {
2556            ResolveInfo info = list.get(i);
2557            if (info.activityInfo == null
2558                    || !info.handleAllWebDataURI
2559                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2560                    || result.contains(info.activityInfo.packageName)) {
2561                continue;
2562            }
2563            result.add(info.activityInfo.packageName);
2564        }
2565
2566        return result;
2567    }
2568
2569    private boolean packageIsBrowser(String packageName, int userId) {
2570        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2571                PackageManager.MATCH_ALL, userId);
2572        final int N = list.size();
2573        for (int i = 0; i < N; i++) {
2574            ResolveInfo info = list.get(i);
2575            if (packageName.equals(info.activityInfo.packageName)) {
2576                return true;
2577            }
2578        }
2579        return false;
2580    }
2581
2582    private void checkDefaultBrowser() {
2583        final int myUserId = UserHandle.myUserId();
2584        final String packageName = getDefaultBrowserPackageName(myUserId);
2585        if (packageName != null) {
2586            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2587            if (info == null) {
2588                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2589                synchronized (mPackages) {
2590                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2591                }
2592            }
2593        }
2594    }
2595
2596    @Override
2597    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2598            throws RemoteException {
2599        try {
2600            return super.onTransact(code, data, reply, flags);
2601        } catch (RuntimeException e) {
2602            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2603                Slog.wtf(TAG, "Package Manager Crash", e);
2604            }
2605            throw e;
2606        }
2607    }
2608
2609    void cleanupInstallFailedPackage(PackageSetting ps) {
2610        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2611
2612        removeDataDirsLI(ps.volumeUuid, ps.name);
2613        if (ps.codePath != null) {
2614            if (ps.codePath.isDirectory()) {
2615                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2616            } else {
2617                ps.codePath.delete();
2618            }
2619        }
2620        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2621            if (ps.resourcePath.isDirectory()) {
2622                FileUtils.deleteContents(ps.resourcePath);
2623            }
2624            ps.resourcePath.delete();
2625        }
2626        mSettings.removePackageLPw(ps.name);
2627    }
2628
2629    static int[] appendInts(int[] cur, int[] add) {
2630        if (add == null) return cur;
2631        if (cur == null) return add;
2632        final int N = add.length;
2633        for (int i=0; i<N; i++) {
2634            cur = appendInt(cur, add[i]);
2635        }
2636        return cur;
2637    }
2638
2639    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2640        if (!sUserManager.exists(userId)) return null;
2641        final PackageSetting ps = (PackageSetting) p.mExtras;
2642        if (ps == null) {
2643            return null;
2644        }
2645
2646        final PermissionsState permissionsState = ps.getPermissionsState();
2647
2648        final int[] gids = permissionsState.computeGids(userId);
2649        final Set<String> permissions = permissionsState.getPermissions(userId);
2650        final PackageUserState state = ps.readUserState(userId);
2651
2652        return PackageParser.generatePackageInfo(p, gids, flags,
2653                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2654    }
2655
2656    @Override
2657    public boolean isPackageFrozen(String packageName) {
2658        synchronized (mPackages) {
2659            final PackageSetting ps = mSettings.mPackages.get(packageName);
2660            if (ps != null) {
2661                return ps.frozen;
2662            }
2663        }
2664        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2665        return true;
2666    }
2667
2668    @Override
2669    public boolean isPackageAvailable(String packageName, int userId) {
2670        if (!sUserManager.exists(userId)) return false;
2671        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2672        synchronized (mPackages) {
2673            PackageParser.Package p = mPackages.get(packageName);
2674            if (p != null) {
2675                final PackageSetting ps = (PackageSetting) p.mExtras;
2676                if (ps != null) {
2677                    final PackageUserState state = ps.readUserState(userId);
2678                    if (state != null) {
2679                        return PackageParser.isAvailable(state);
2680                    }
2681                }
2682            }
2683        }
2684        return false;
2685    }
2686
2687    @Override
2688    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2689        if (!sUserManager.exists(userId)) return null;
2690        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2691        // reader
2692        synchronized (mPackages) {
2693            PackageParser.Package p = mPackages.get(packageName);
2694            if (DEBUG_PACKAGE_INFO)
2695                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2696            if (p != null) {
2697                return generatePackageInfo(p, flags, userId);
2698            }
2699            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2700                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2701            }
2702        }
2703        return null;
2704    }
2705
2706    @Override
2707    public String[] currentToCanonicalPackageNames(String[] names) {
2708        String[] out = new String[names.length];
2709        // reader
2710        synchronized (mPackages) {
2711            for (int i=names.length-1; i>=0; i--) {
2712                PackageSetting ps = mSettings.mPackages.get(names[i]);
2713                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2714            }
2715        }
2716        return out;
2717    }
2718
2719    @Override
2720    public String[] canonicalToCurrentPackageNames(String[] names) {
2721        String[] out = new String[names.length];
2722        // reader
2723        synchronized (mPackages) {
2724            for (int i=names.length-1; i>=0; i--) {
2725                String cur = mSettings.mRenamedPackages.get(names[i]);
2726                out[i] = cur != null ? cur : names[i];
2727            }
2728        }
2729        return out;
2730    }
2731
2732    @Override
2733    public int getPackageUid(String packageName, int userId) {
2734        if (!sUserManager.exists(userId)) return -1;
2735        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2736
2737        // reader
2738        synchronized (mPackages) {
2739            PackageParser.Package p = mPackages.get(packageName);
2740            if(p != null) {
2741                return UserHandle.getUid(userId, p.applicationInfo.uid);
2742            }
2743            PackageSetting ps = mSettings.mPackages.get(packageName);
2744            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2745                return -1;
2746            }
2747            p = ps.pkg;
2748            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2749        }
2750    }
2751
2752    @Override
2753    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2754        if (!sUserManager.exists(userId)) {
2755            return null;
2756        }
2757
2758        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2759                "getPackageGids");
2760
2761        // reader
2762        synchronized (mPackages) {
2763            PackageParser.Package p = mPackages.get(packageName);
2764            if (DEBUG_PACKAGE_INFO) {
2765                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2766            }
2767            if (p != null) {
2768                PackageSetting ps = (PackageSetting) p.mExtras;
2769                return ps.getPermissionsState().computeGids(userId);
2770            }
2771        }
2772
2773        return null;
2774    }
2775
2776    static PermissionInfo generatePermissionInfo(
2777            BasePermission bp, int flags) {
2778        if (bp.perm != null) {
2779            return PackageParser.generatePermissionInfo(bp.perm, flags);
2780        }
2781        PermissionInfo pi = new PermissionInfo();
2782        pi.name = bp.name;
2783        pi.packageName = bp.sourcePackage;
2784        pi.nonLocalizedLabel = bp.name;
2785        pi.protectionLevel = bp.protectionLevel;
2786        return pi;
2787    }
2788
2789    @Override
2790    public PermissionInfo getPermissionInfo(String name, int flags) {
2791        // reader
2792        synchronized (mPackages) {
2793            final BasePermission p = mSettings.mPermissions.get(name);
2794            if (p != null) {
2795                return generatePermissionInfo(p, flags);
2796            }
2797            return null;
2798        }
2799    }
2800
2801    @Override
2802    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2803        // reader
2804        synchronized (mPackages) {
2805            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2806            for (BasePermission p : mSettings.mPermissions.values()) {
2807                if (group == null) {
2808                    if (p.perm == null || p.perm.info.group == null) {
2809                        out.add(generatePermissionInfo(p, flags));
2810                    }
2811                } else {
2812                    if (p.perm != null && group.equals(p.perm.info.group)) {
2813                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2814                    }
2815                }
2816            }
2817
2818            if (out.size() > 0) {
2819                return out;
2820            }
2821            return mPermissionGroups.containsKey(group) ? out : null;
2822        }
2823    }
2824
2825    @Override
2826    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2827        // reader
2828        synchronized (mPackages) {
2829            return PackageParser.generatePermissionGroupInfo(
2830                    mPermissionGroups.get(name), flags);
2831        }
2832    }
2833
2834    @Override
2835    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2836        // reader
2837        synchronized (mPackages) {
2838            final int N = mPermissionGroups.size();
2839            ArrayList<PermissionGroupInfo> out
2840                    = new ArrayList<PermissionGroupInfo>(N);
2841            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2842                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2843            }
2844            return out;
2845        }
2846    }
2847
2848    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2849            int userId) {
2850        if (!sUserManager.exists(userId)) return null;
2851        PackageSetting ps = mSettings.mPackages.get(packageName);
2852        if (ps != null) {
2853            if (ps.pkg == null) {
2854                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2855                        flags, userId);
2856                if (pInfo != null) {
2857                    return pInfo.applicationInfo;
2858                }
2859                return null;
2860            }
2861            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2862                    ps.readUserState(userId), userId);
2863        }
2864        return null;
2865    }
2866
2867    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2868            int userId) {
2869        if (!sUserManager.exists(userId)) return null;
2870        PackageSetting ps = mSettings.mPackages.get(packageName);
2871        if (ps != null) {
2872            PackageParser.Package pkg = ps.pkg;
2873            if (pkg == null) {
2874                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2875                    return null;
2876                }
2877                // Only data remains, so we aren't worried about code paths
2878                pkg = new PackageParser.Package(packageName);
2879                pkg.applicationInfo.packageName = packageName;
2880                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2881                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2882                pkg.applicationInfo.dataDir = Environment
2883                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2884                        .getAbsolutePath();
2885                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2886                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2887            }
2888            return generatePackageInfo(pkg, flags, userId);
2889        }
2890        return null;
2891    }
2892
2893    @Override
2894    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2895        if (!sUserManager.exists(userId)) return null;
2896        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2897        // writer
2898        synchronized (mPackages) {
2899            PackageParser.Package p = mPackages.get(packageName);
2900            if (DEBUG_PACKAGE_INFO) Log.v(
2901                    TAG, "getApplicationInfo " + packageName
2902                    + ": " + p);
2903            if (p != null) {
2904                PackageSetting ps = mSettings.mPackages.get(packageName);
2905                if (ps == null) return null;
2906                // Note: isEnabledLP() does not apply here - always return info
2907                return PackageParser.generateApplicationInfo(
2908                        p, flags, ps.readUserState(userId), userId);
2909            }
2910            if ("android".equals(packageName)||"system".equals(packageName)) {
2911                return mAndroidApplication;
2912            }
2913            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2914                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2915            }
2916        }
2917        return null;
2918    }
2919
2920    @Override
2921    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2922            final IPackageDataObserver observer) {
2923        mContext.enforceCallingOrSelfPermission(
2924                android.Manifest.permission.CLEAR_APP_CACHE, null);
2925        // Queue up an async operation since clearing cache may take a little while.
2926        mHandler.post(new Runnable() {
2927            public void run() {
2928                mHandler.removeCallbacks(this);
2929                int retCode = -1;
2930                synchronized (mInstallLock) {
2931                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2932                    if (retCode < 0) {
2933                        Slog.w(TAG, "Couldn't clear application caches");
2934                    }
2935                }
2936                if (observer != null) {
2937                    try {
2938                        observer.onRemoveCompleted(null, (retCode >= 0));
2939                    } catch (RemoteException e) {
2940                        Slog.w(TAG, "RemoveException when invoking call back");
2941                    }
2942                }
2943            }
2944        });
2945    }
2946
2947    @Override
2948    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2949            final IntentSender pi) {
2950        mContext.enforceCallingOrSelfPermission(
2951                android.Manifest.permission.CLEAR_APP_CACHE, null);
2952        // Queue up an async operation since clearing cache may take a little while.
2953        mHandler.post(new Runnable() {
2954            public void run() {
2955                mHandler.removeCallbacks(this);
2956                int retCode = -1;
2957                synchronized (mInstallLock) {
2958                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2959                    if (retCode < 0) {
2960                        Slog.w(TAG, "Couldn't clear application caches");
2961                    }
2962                }
2963                if(pi != null) {
2964                    try {
2965                        // Callback via pending intent
2966                        int code = (retCode >= 0) ? 1 : 0;
2967                        pi.sendIntent(null, code, null,
2968                                null, null);
2969                    } catch (SendIntentException e1) {
2970                        Slog.i(TAG, "Failed to send pending intent");
2971                    }
2972                }
2973            }
2974        });
2975    }
2976
2977    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2978        synchronized (mInstallLock) {
2979            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2980                throw new IOException("Failed to free enough space");
2981            }
2982        }
2983    }
2984
2985    @Override
2986    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2987        if (!sUserManager.exists(userId)) return null;
2988        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2989        synchronized (mPackages) {
2990            PackageParser.Activity a = mActivities.mActivities.get(component);
2991
2992            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2993            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2994                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2995                if (ps == null) return null;
2996                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2997                        userId);
2998            }
2999            if (mResolveComponentName.equals(component)) {
3000                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3001                        new PackageUserState(), userId);
3002            }
3003        }
3004        return null;
3005    }
3006
3007    @Override
3008    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3009            String resolvedType) {
3010        synchronized (mPackages) {
3011            if (component.equals(mResolveComponentName)) {
3012                // The resolver supports EVERYTHING!
3013                return true;
3014            }
3015            PackageParser.Activity a = mActivities.mActivities.get(component);
3016            if (a == null) {
3017                return false;
3018            }
3019            for (int i=0; i<a.intents.size(); i++) {
3020                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3021                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3022                    return true;
3023                }
3024            }
3025            return false;
3026        }
3027    }
3028
3029    @Override
3030    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3031        if (!sUserManager.exists(userId)) return null;
3032        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3033        synchronized (mPackages) {
3034            PackageParser.Activity a = mReceivers.mActivities.get(component);
3035            if (DEBUG_PACKAGE_INFO) Log.v(
3036                TAG, "getReceiverInfo " + component + ": " + a);
3037            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3038                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3039                if (ps == null) return null;
3040                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3041                        userId);
3042            }
3043        }
3044        return null;
3045    }
3046
3047    @Override
3048    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3049        if (!sUserManager.exists(userId)) return null;
3050        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3051        synchronized (mPackages) {
3052            PackageParser.Service s = mServices.mServices.get(component);
3053            if (DEBUG_PACKAGE_INFO) Log.v(
3054                TAG, "getServiceInfo " + component + ": " + s);
3055            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3056                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3057                if (ps == null) return null;
3058                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3059                        userId);
3060            }
3061        }
3062        return null;
3063    }
3064
3065    @Override
3066    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3067        if (!sUserManager.exists(userId)) return null;
3068        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3069        synchronized (mPackages) {
3070            PackageParser.Provider p = mProviders.mProviders.get(component);
3071            if (DEBUG_PACKAGE_INFO) Log.v(
3072                TAG, "getProviderInfo " + component + ": " + p);
3073            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3074                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3075                if (ps == null) return null;
3076                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3077                        userId);
3078            }
3079        }
3080        return null;
3081    }
3082
3083    @Override
3084    public String[] getSystemSharedLibraryNames() {
3085        Set<String> libSet;
3086        synchronized (mPackages) {
3087            libSet = mSharedLibraries.keySet();
3088            int size = libSet.size();
3089            if (size > 0) {
3090                String[] libs = new String[size];
3091                libSet.toArray(libs);
3092                return libs;
3093            }
3094        }
3095        return null;
3096    }
3097
3098    /**
3099     * @hide
3100     */
3101    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3102        synchronized (mPackages) {
3103            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3104            if (lib != null && lib.apk != null) {
3105                return mPackages.get(lib.apk);
3106            }
3107        }
3108        return null;
3109    }
3110
3111    @Override
3112    public FeatureInfo[] getSystemAvailableFeatures() {
3113        Collection<FeatureInfo> featSet;
3114        synchronized (mPackages) {
3115            featSet = mAvailableFeatures.values();
3116            int size = featSet.size();
3117            if (size > 0) {
3118                FeatureInfo[] features = new FeatureInfo[size+1];
3119                featSet.toArray(features);
3120                FeatureInfo fi = new FeatureInfo();
3121                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3122                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3123                features[size] = fi;
3124                return features;
3125            }
3126        }
3127        return null;
3128    }
3129
3130    @Override
3131    public boolean hasSystemFeature(String name) {
3132        synchronized (mPackages) {
3133            return mAvailableFeatures.containsKey(name);
3134        }
3135    }
3136
3137    private void checkValidCaller(int uid, int userId) {
3138        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3139            return;
3140
3141        throw new SecurityException("Caller uid=" + uid
3142                + " is not privileged to communicate with user=" + userId);
3143    }
3144
3145    @Override
3146    public int checkPermission(String permName, String pkgName, int userId) {
3147        if (!sUserManager.exists(userId)) {
3148            return PackageManager.PERMISSION_DENIED;
3149        }
3150
3151        synchronized (mPackages) {
3152            final PackageParser.Package p = mPackages.get(pkgName);
3153            if (p != null && p.mExtras != null) {
3154                final PackageSetting ps = (PackageSetting) p.mExtras;
3155                final PermissionsState permissionsState = ps.getPermissionsState();
3156                if (permissionsState.hasPermission(permName, userId)) {
3157                    return PackageManager.PERMISSION_GRANTED;
3158                }
3159                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3160                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3161                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3162                    return PackageManager.PERMISSION_GRANTED;
3163                }
3164            }
3165        }
3166
3167        return PackageManager.PERMISSION_DENIED;
3168    }
3169
3170    @Override
3171    public int checkUidPermission(String permName, int uid) {
3172        final int userId = UserHandle.getUserId(uid);
3173
3174        if (!sUserManager.exists(userId)) {
3175            return PackageManager.PERMISSION_DENIED;
3176        }
3177
3178        synchronized (mPackages) {
3179            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3180            if (obj != null) {
3181                final SettingBase ps = (SettingBase) obj;
3182                final PermissionsState permissionsState = ps.getPermissionsState();
3183                if (permissionsState.hasPermission(permName, userId)) {
3184                    return PackageManager.PERMISSION_GRANTED;
3185                }
3186                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3187                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3188                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3189                    return PackageManager.PERMISSION_GRANTED;
3190                }
3191            } else {
3192                ArraySet<String> perms = mSystemPermissions.get(uid);
3193                if (perms != null) {
3194                    if (perms.contains(permName)) {
3195                        return PackageManager.PERMISSION_GRANTED;
3196                    }
3197                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3198                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3199                        return PackageManager.PERMISSION_GRANTED;
3200                    }
3201                }
3202            }
3203        }
3204
3205        return PackageManager.PERMISSION_DENIED;
3206    }
3207
3208    @Override
3209    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3210        if (UserHandle.getCallingUserId() != userId) {
3211            mContext.enforceCallingPermission(
3212                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3213                    "isPermissionRevokedByPolicy for user " + userId);
3214        }
3215
3216        if (checkPermission(permission, packageName, userId)
3217                == PackageManager.PERMISSION_GRANTED) {
3218            return false;
3219        }
3220
3221        final long identity = Binder.clearCallingIdentity();
3222        try {
3223            final int flags = getPermissionFlags(permission, packageName, userId);
3224            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3225        } finally {
3226            Binder.restoreCallingIdentity(identity);
3227        }
3228    }
3229
3230    @Override
3231    public String getPermissionControllerPackageName() {
3232        synchronized (mPackages) {
3233            return mRequiredInstallerPackage;
3234        }
3235    }
3236
3237    /**
3238     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3239     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3240     * @param checkShell TODO(yamasani):
3241     * @param message the message to log on security exception
3242     */
3243    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3244            boolean checkShell, String message) {
3245        if (userId < 0) {
3246            throw new IllegalArgumentException("Invalid userId " + userId);
3247        }
3248        if (checkShell) {
3249            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3250        }
3251        if (userId == UserHandle.getUserId(callingUid)) return;
3252        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3253            if (requireFullPermission) {
3254                mContext.enforceCallingOrSelfPermission(
3255                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3256            } else {
3257                try {
3258                    mContext.enforceCallingOrSelfPermission(
3259                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3260                } catch (SecurityException se) {
3261                    mContext.enforceCallingOrSelfPermission(
3262                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3263                }
3264            }
3265        }
3266    }
3267
3268    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3269        if (callingUid == Process.SHELL_UID) {
3270            if (userHandle >= 0
3271                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3272                throw new SecurityException("Shell does not have permission to access user "
3273                        + userHandle);
3274            } else if (userHandle < 0) {
3275                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3276                        + Debug.getCallers(3));
3277            }
3278        }
3279    }
3280
3281    private BasePermission findPermissionTreeLP(String permName) {
3282        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3283            if (permName.startsWith(bp.name) &&
3284                    permName.length() > bp.name.length() &&
3285                    permName.charAt(bp.name.length()) == '.') {
3286                return bp;
3287            }
3288        }
3289        return null;
3290    }
3291
3292    private BasePermission checkPermissionTreeLP(String permName) {
3293        if (permName != null) {
3294            BasePermission bp = findPermissionTreeLP(permName);
3295            if (bp != null) {
3296                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3297                    return bp;
3298                }
3299                throw new SecurityException("Calling uid "
3300                        + Binder.getCallingUid()
3301                        + " is not allowed to add to permission tree "
3302                        + bp.name + " owned by uid " + bp.uid);
3303            }
3304        }
3305        throw new SecurityException("No permission tree found for " + permName);
3306    }
3307
3308    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3309        if (s1 == null) {
3310            return s2 == null;
3311        }
3312        if (s2 == null) {
3313            return false;
3314        }
3315        if (s1.getClass() != s2.getClass()) {
3316            return false;
3317        }
3318        return s1.equals(s2);
3319    }
3320
3321    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3322        if (pi1.icon != pi2.icon) return false;
3323        if (pi1.logo != pi2.logo) return false;
3324        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3325        if (!compareStrings(pi1.name, pi2.name)) return false;
3326        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3327        // We'll take care of setting this one.
3328        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3329        // These are not currently stored in settings.
3330        //if (!compareStrings(pi1.group, pi2.group)) return false;
3331        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3332        //if (pi1.labelRes != pi2.labelRes) return false;
3333        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3334        return true;
3335    }
3336
3337    int permissionInfoFootprint(PermissionInfo info) {
3338        int size = info.name.length();
3339        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3340        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3341        return size;
3342    }
3343
3344    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3345        int size = 0;
3346        for (BasePermission perm : mSettings.mPermissions.values()) {
3347            if (perm.uid == tree.uid) {
3348                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3349            }
3350        }
3351        return size;
3352    }
3353
3354    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3355        // We calculate the max size of permissions defined by this uid and throw
3356        // if that plus the size of 'info' would exceed our stated maximum.
3357        if (tree.uid != Process.SYSTEM_UID) {
3358            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3359            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3360                throw new SecurityException("Permission tree size cap exceeded");
3361            }
3362        }
3363    }
3364
3365    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3366        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3367            throw new SecurityException("Label must be specified in permission");
3368        }
3369        BasePermission tree = checkPermissionTreeLP(info.name);
3370        BasePermission bp = mSettings.mPermissions.get(info.name);
3371        boolean added = bp == null;
3372        boolean changed = true;
3373        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3374        if (added) {
3375            enforcePermissionCapLocked(info, tree);
3376            bp = new BasePermission(info.name, tree.sourcePackage,
3377                    BasePermission.TYPE_DYNAMIC);
3378        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3379            throw new SecurityException(
3380                    "Not allowed to modify non-dynamic permission "
3381                    + info.name);
3382        } else {
3383            if (bp.protectionLevel == fixedLevel
3384                    && bp.perm.owner.equals(tree.perm.owner)
3385                    && bp.uid == tree.uid
3386                    && comparePermissionInfos(bp.perm.info, info)) {
3387                changed = false;
3388            }
3389        }
3390        bp.protectionLevel = fixedLevel;
3391        info = new PermissionInfo(info);
3392        info.protectionLevel = fixedLevel;
3393        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3394        bp.perm.info.packageName = tree.perm.info.packageName;
3395        bp.uid = tree.uid;
3396        if (added) {
3397            mSettings.mPermissions.put(info.name, bp);
3398        }
3399        if (changed) {
3400            if (!async) {
3401                mSettings.writeLPr();
3402            } else {
3403                scheduleWriteSettingsLocked();
3404            }
3405        }
3406        return added;
3407    }
3408
3409    @Override
3410    public boolean addPermission(PermissionInfo info) {
3411        synchronized (mPackages) {
3412            return addPermissionLocked(info, false);
3413        }
3414    }
3415
3416    @Override
3417    public boolean addPermissionAsync(PermissionInfo info) {
3418        synchronized (mPackages) {
3419            return addPermissionLocked(info, true);
3420        }
3421    }
3422
3423    @Override
3424    public void removePermission(String name) {
3425        synchronized (mPackages) {
3426            checkPermissionTreeLP(name);
3427            BasePermission bp = mSettings.mPermissions.get(name);
3428            if (bp != null) {
3429                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3430                    throw new SecurityException(
3431                            "Not allowed to modify non-dynamic permission "
3432                            + name);
3433                }
3434                mSettings.mPermissions.remove(name);
3435                mSettings.writeLPr();
3436            }
3437        }
3438    }
3439
3440    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3441            BasePermission bp) {
3442        int index = pkg.requestedPermissions.indexOf(bp.name);
3443        if (index == -1) {
3444            throw new SecurityException("Package " + pkg.packageName
3445                    + " has not requested permission " + bp.name);
3446        }
3447        if (!bp.isRuntime() && !bp.isDevelopment()) {
3448            throw new SecurityException("Permission " + bp.name
3449                    + " is not a changeable permission type");
3450        }
3451    }
3452
3453    @Override
3454    public void grantRuntimePermission(String packageName, String name, final int userId) {
3455        if (!sUserManager.exists(userId)) {
3456            Log.e(TAG, "No such user:" + userId);
3457            return;
3458        }
3459
3460        mContext.enforceCallingOrSelfPermission(
3461                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3462                "grantRuntimePermission");
3463
3464        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3465                "grantRuntimePermission");
3466
3467        final int uid;
3468        final SettingBase sb;
3469
3470        synchronized (mPackages) {
3471            final PackageParser.Package pkg = mPackages.get(packageName);
3472            if (pkg == null) {
3473                throw new IllegalArgumentException("Unknown package: " + packageName);
3474            }
3475
3476            final BasePermission bp = mSettings.mPermissions.get(name);
3477            if (bp == null) {
3478                throw new IllegalArgumentException("Unknown permission: " + name);
3479            }
3480
3481            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3482
3483            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3484            sb = (SettingBase) pkg.mExtras;
3485            if (sb == null) {
3486                throw new IllegalArgumentException("Unknown package: " + packageName);
3487            }
3488
3489            final PermissionsState permissionsState = sb.getPermissionsState();
3490
3491            final int flags = permissionsState.getPermissionFlags(name, userId);
3492            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3493                throw new SecurityException("Cannot grant system fixed permission: "
3494                        + name + " for package: " + packageName);
3495            }
3496
3497            if (bp.isDevelopment()) {
3498                // Development permissions must be handled specially, since they are not
3499                // normal runtime permissions.  For now they apply to all users.
3500                if (permissionsState.grantInstallPermission(bp) !=
3501                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3502                    scheduleWriteSettingsLocked();
3503                }
3504                return;
3505            }
3506
3507            final int result = permissionsState.grantRuntimePermission(bp, userId);
3508            switch (result) {
3509                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3510                    return;
3511                }
3512
3513                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3514                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3515                    mHandler.post(new Runnable() {
3516                        @Override
3517                        public void run() {
3518                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3519                        }
3520                    });
3521                } break;
3522            }
3523
3524            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3525
3526            // Not critical if that is lost - app has to request again.
3527            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3528        }
3529
3530        // Only need to do this if user is initialized. Otherwise it's a new user
3531        // and there are no processes running as the user yet and there's no need
3532        // to make an expensive call to remount processes for the changed permissions.
3533        if (READ_EXTERNAL_STORAGE.equals(name)
3534                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3535            final long token = Binder.clearCallingIdentity();
3536            try {
3537                if (sUserManager.isInitialized(userId)) {
3538                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3539                            MountServiceInternal.class);
3540                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3541                }
3542            } finally {
3543                Binder.restoreCallingIdentity(token);
3544            }
3545        }
3546    }
3547
3548    @Override
3549    public void revokeRuntimePermission(String packageName, String name, int userId) {
3550        if (!sUserManager.exists(userId)) {
3551            Log.e(TAG, "No such user:" + userId);
3552            return;
3553        }
3554
3555        mContext.enforceCallingOrSelfPermission(
3556                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3557                "revokeRuntimePermission");
3558
3559        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3560                "revokeRuntimePermission");
3561
3562        final int appId;
3563
3564        synchronized (mPackages) {
3565            final PackageParser.Package pkg = mPackages.get(packageName);
3566            if (pkg == null) {
3567                throw new IllegalArgumentException("Unknown package: " + packageName);
3568            }
3569
3570            final BasePermission bp = mSettings.mPermissions.get(name);
3571            if (bp == null) {
3572                throw new IllegalArgumentException("Unknown permission: " + name);
3573            }
3574
3575            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3576
3577            SettingBase sb = (SettingBase) pkg.mExtras;
3578            if (sb == null) {
3579                throw new IllegalArgumentException("Unknown package: " + packageName);
3580            }
3581
3582            final PermissionsState permissionsState = sb.getPermissionsState();
3583
3584            final int flags = permissionsState.getPermissionFlags(name, userId);
3585            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3586                throw new SecurityException("Cannot revoke system fixed permission: "
3587                        + name + " for package: " + packageName);
3588            }
3589
3590            if (bp.isDevelopment()) {
3591                // Development permissions must be handled specially, since they are not
3592                // normal runtime permissions.  For now they apply to all users.
3593                if (permissionsState.revokeInstallPermission(bp) !=
3594                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3595                    scheduleWriteSettingsLocked();
3596                }
3597                return;
3598            }
3599
3600            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3601                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3602                return;
3603            }
3604
3605            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3606
3607            // Critical, after this call app should never have the permission.
3608            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3609
3610            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3611        }
3612
3613        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3614    }
3615
3616    @Override
3617    public void resetRuntimePermissions() {
3618        mContext.enforceCallingOrSelfPermission(
3619                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3620                "revokeRuntimePermission");
3621
3622        int callingUid = Binder.getCallingUid();
3623        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3624            mContext.enforceCallingOrSelfPermission(
3625                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3626                    "resetRuntimePermissions");
3627        }
3628
3629        synchronized (mPackages) {
3630            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3631            for (int userId : UserManagerService.getInstance().getUserIds()) {
3632                final int packageCount = mPackages.size();
3633                for (int i = 0; i < packageCount; i++) {
3634                    PackageParser.Package pkg = mPackages.valueAt(i);
3635                    if (!(pkg.mExtras instanceof PackageSetting)) {
3636                        continue;
3637                    }
3638                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3639                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3640                }
3641            }
3642        }
3643    }
3644
3645    @Override
3646    public int getPermissionFlags(String name, String packageName, int userId) {
3647        if (!sUserManager.exists(userId)) {
3648            return 0;
3649        }
3650
3651        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3652
3653        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3654                "getPermissionFlags");
3655
3656        synchronized (mPackages) {
3657            final PackageParser.Package pkg = mPackages.get(packageName);
3658            if (pkg == null) {
3659                throw new IllegalArgumentException("Unknown package: " + packageName);
3660            }
3661
3662            final BasePermission bp = mSettings.mPermissions.get(name);
3663            if (bp == null) {
3664                throw new IllegalArgumentException("Unknown permission: " + name);
3665            }
3666
3667            SettingBase sb = (SettingBase) pkg.mExtras;
3668            if (sb == null) {
3669                throw new IllegalArgumentException("Unknown package: " + packageName);
3670            }
3671
3672            PermissionsState permissionsState = sb.getPermissionsState();
3673            return permissionsState.getPermissionFlags(name, userId);
3674        }
3675    }
3676
3677    @Override
3678    public void updatePermissionFlags(String name, String packageName, int flagMask,
3679            int flagValues, int userId) {
3680        if (!sUserManager.exists(userId)) {
3681            return;
3682        }
3683
3684        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3685
3686        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3687                "updatePermissionFlags");
3688
3689        // Only the system can change these flags and nothing else.
3690        if (getCallingUid() != Process.SYSTEM_UID) {
3691            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3692            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3693            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3694            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3695        }
3696
3697        synchronized (mPackages) {
3698            final PackageParser.Package pkg = mPackages.get(packageName);
3699            if (pkg == null) {
3700                throw new IllegalArgumentException("Unknown package: " + packageName);
3701            }
3702
3703            final BasePermission bp = mSettings.mPermissions.get(name);
3704            if (bp == null) {
3705                throw new IllegalArgumentException("Unknown permission: " + name);
3706            }
3707
3708            SettingBase sb = (SettingBase) pkg.mExtras;
3709            if (sb == null) {
3710                throw new IllegalArgumentException("Unknown package: " + packageName);
3711            }
3712
3713            PermissionsState permissionsState = sb.getPermissionsState();
3714
3715            // Only the package manager can change flags for system component permissions.
3716            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3717            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3718                return;
3719            }
3720
3721            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3722
3723            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3724                // Install and runtime permissions are stored in different places,
3725                // so figure out what permission changed and persist the change.
3726                if (permissionsState.getInstallPermissionState(name) != null) {
3727                    scheduleWriteSettingsLocked();
3728                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3729                        || hadState) {
3730                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3731                }
3732            }
3733        }
3734    }
3735
3736    /**
3737     * Update the permission flags for all packages and runtime permissions of a user in order
3738     * to allow device or profile owner to remove POLICY_FIXED.
3739     */
3740    @Override
3741    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3742        if (!sUserManager.exists(userId)) {
3743            return;
3744        }
3745
3746        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3747
3748        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3749                "updatePermissionFlagsForAllApps");
3750
3751        // Only the system can change system fixed flags.
3752        if (getCallingUid() != Process.SYSTEM_UID) {
3753            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3754            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3755        }
3756
3757        synchronized (mPackages) {
3758            boolean changed = false;
3759            final int packageCount = mPackages.size();
3760            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3761                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3762                SettingBase sb = (SettingBase) pkg.mExtras;
3763                if (sb == null) {
3764                    continue;
3765                }
3766                PermissionsState permissionsState = sb.getPermissionsState();
3767                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3768                        userId, flagMask, flagValues);
3769            }
3770            if (changed) {
3771                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3772            }
3773        }
3774    }
3775
3776    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3777        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3778                != PackageManager.PERMISSION_GRANTED
3779            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3780                != PackageManager.PERMISSION_GRANTED) {
3781            throw new SecurityException(message + " requires "
3782                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3783                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3784        }
3785    }
3786
3787    @Override
3788    public boolean shouldShowRequestPermissionRationale(String permissionName,
3789            String packageName, int userId) {
3790        if (UserHandle.getCallingUserId() != userId) {
3791            mContext.enforceCallingPermission(
3792                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3793                    "canShowRequestPermissionRationale for user " + userId);
3794        }
3795
3796        final int uid = getPackageUid(packageName, userId);
3797        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3798            return false;
3799        }
3800
3801        if (checkPermission(permissionName, packageName, userId)
3802                == PackageManager.PERMISSION_GRANTED) {
3803            return false;
3804        }
3805
3806        final int flags;
3807
3808        final long identity = Binder.clearCallingIdentity();
3809        try {
3810            flags = getPermissionFlags(permissionName,
3811                    packageName, userId);
3812        } finally {
3813            Binder.restoreCallingIdentity(identity);
3814        }
3815
3816        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3817                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3818                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3819
3820        if ((flags & fixedFlags) != 0) {
3821            return false;
3822        }
3823
3824        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3825    }
3826
3827    @Override
3828    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3829        mContext.enforceCallingOrSelfPermission(
3830                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3831                "addOnPermissionsChangeListener");
3832
3833        synchronized (mPackages) {
3834            mOnPermissionChangeListeners.addListenerLocked(listener);
3835        }
3836    }
3837
3838    @Override
3839    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3840        synchronized (mPackages) {
3841            mOnPermissionChangeListeners.removeListenerLocked(listener);
3842        }
3843    }
3844
3845    @Override
3846    public boolean isProtectedBroadcast(String actionName) {
3847        synchronized (mPackages) {
3848            return mProtectedBroadcasts.contains(actionName);
3849        }
3850    }
3851
3852    @Override
3853    public int checkSignatures(String pkg1, String pkg2) {
3854        synchronized (mPackages) {
3855            final PackageParser.Package p1 = mPackages.get(pkg1);
3856            final PackageParser.Package p2 = mPackages.get(pkg2);
3857            if (p1 == null || p1.mExtras == null
3858                    || p2 == null || p2.mExtras == null) {
3859                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3860            }
3861            return compareSignatures(p1.mSignatures, p2.mSignatures);
3862        }
3863    }
3864
3865    @Override
3866    public int checkUidSignatures(int uid1, int uid2) {
3867        // Map to base uids.
3868        uid1 = UserHandle.getAppId(uid1);
3869        uid2 = UserHandle.getAppId(uid2);
3870        // reader
3871        synchronized (mPackages) {
3872            Signature[] s1;
3873            Signature[] s2;
3874            Object obj = mSettings.getUserIdLPr(uid1);
3875            if (obj != null) {
3876                if (obj instanceof SharedUserSetting) {
3877                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3878                } else if (obj instanceof PackageSetting) {
3879                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3880                } else {
3881                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3882                }
3883            } else {
3884                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3885            }
3886            obj = mSettings.getUserIdLPr(uid2);
3887            if (obj != null) {
3888                if (obj instanceof SharedUserSetting) {
3889                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3890                } else if (obj instanceof PackageSetting) {
3891                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3892                } else {
3893                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3894                }
3895            } else {
3896                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3897            }
3898            return compareSignatures(s1, s2);
3899        }
3900    }
3901
3902    private void killUid(int appId, int userId, String reason) {
3903        final long identity = Binder.clearCallingIdentity();
3904        try {
3905            IActivityManager am = ActivityManagerNative.getDefault();
3906            if (am != null) {
3907                try {
3908                    am.killUid(appId, userId, reason);
3909                } catch (RemoteException e) {
3910                    /* ignore - same process */
3911                }
3912            }
3913        } finally {
3914            Binder.restoreCallingIdentity(identity);
3915        }
3916    }
3917
3918    /**
3919     * Compares two sets of signatures. Returns:
3920     * <br />
3921     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3922     * <br />
3923     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3924     * <br />
3925     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3926     * <br />
3927     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3928     * <br />
3929     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3930     */
3931    static int compareSignatures(Signature[] s1, Signature[] s2) {
3932        if (s1 == null) {
3933            return s2 == null
3934                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3935                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3936        }
3937
3938        if (s2 == null) {
3939            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3940        }
3941
3942        if (s1.length != s2.length) {
3943            return PackageManager.SIGNATURE_NO_MATCH;
3944        }
3945
3946        // Since both signature sets are of size 1, we can compare without HashSets.
3947        if (s1.length == 1) {
3948            return s1[0].equals(s2[0]) ?
3949                    PackageManager.SIGNATURE_MATCH :
3950                    PackageManager.SIGNATURE_NO_MATCH;
3951        }
3952
3953        ArraySet<Signature> set1 = new ArraySet<Signature>();
3954        for (Signature sig : s1) {
3955            set1.add(sig);
3956        }
3957        ArraySet<Signature> set2 = new ArraySet<Signature>();
3958        for (Signature sig : s2) {
3959            set2.add(sig);
3960        }
3961        // Make sure s2 contains all signatures in s1.
3962        if (set1.equals(set2)) {
3963            return PackageManager.SIGNATURE_MATCH;
3964        }
3965        return PackageManager.SIGNATURE_NO_MATCH;
3966    }
3967
3968    /**
3969     * If the database version for this type of package (internal storage or
3970     * external storage) is less than the version where package signatures
3971     * were updated, return true.
3972     */
3973    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3974        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3975        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3976    }
3977
3978    /**
3979     * Used for backward compatibility to make sure any packages with
3980     * certificate chains get upgraded to the new style. {@code existingSigs}
3981     * will be in the old format (since they were stored on disk from before the
3982     * system upgrade) and {@code scannedSigs} will be in the newer format.
3983     */
3984    private int compareSignaturesCompat(PackageSignatures existingSigs,
3985            PackageParser.Package scannedPkg) {
3986        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3987            return PackageManager.SIGNATURE_NO_MATCH;
3988        }
3989
3990        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3991        for (Signature sig : existingSigs.mSignatures) {
3992            existingSet.add(sig);
3993        }
3994        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3995        for (Signature sig : scannedPkg.mSignatures) {
3996            try {
3997                Signature[] chainSignatures = sig.getChainSignatures();
3998                for (Signature chainSig : chainSignatures) {
3999                    scannedCompatSet.add(chainSig);
4000                }
4001            } catch (CertificateEncodingException e) {
4002                scannedCompatSet.add(sig);
4003            }
4004        }
4005        /*
4006         * Make sure the expanded scanned set contains all signatures in the
4007         * existing one.
4008         */
4009        if (scannedCompatSet.equals(existingSet)) {
4010            // Migrate the old signatures to the new scheme.
4011            existingSigs.assignSignatures(scannedPkg.mSignatures);
4012            // The new KeySets will be re-added later in the scanning process.
4013            synchronized (mPackages) {
4014                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4015            }
4016            return PackageManager.SIGNATURE_MATCH;
4017        }
4018        return PackageManager.SIGNATURE_NO_MATCH;
4019    }
4020
4021    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4022        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4023        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4024    }
4025
4026    private int compareSignaturesRecover(PackageSignatures existingSigs,
4027            PackageParser.Package scannedPkg) {
4028        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4029            return PackageManager.SIGNATURE_NO_MATCH;
4030        }
4031
4032        String msg = null;
4033        try {
4034            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4035                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4036                        + scannedPkg.packageName);
4037                return PackageManager.SIGNATURE_MATCH;
4038            }
4039        } catch (CertificateException e) {
4040            msg = e.getMessage();
4041        }
4042
4043        logCriticalInfo(Log.INFO,
4044                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4045        return PackageManager.SIGNATURE_NO_MATCH;
4046    }
4047
4048    @Override
4049    public String[] getPackagesForUid(int uid) {
4050        uid = UserHandle.getAppId(uid);
4051        // reader
4052        synchronized (mPackages) {
4053            Object obj = mSettings.getUserIdLPr(uid);
4054            if (obj instanceof SharedUserSetting) {
4055                final SharedUserSetting sus = (SharedUserSetting) obj;
4056                final int N = sus.packages.size();
4057                final String[] res = new String[N];
4058                final Iterator<PackageSetting> it = sus.packages.iterator();
4059                int i = 0;
4060                while (it.hasNext()) {
4061                    res[i++] = it.next().name;
4062                }
4063                return res;
4064            } else if (obj instanceof PackageSetting) {
4065                final PackageSetting ps = (PackageSetting) obj;
4066                return new String[] { ps.name };
4067            }
4068        }
4069        return null;
4070    }
4071
4072    @Override
4073    public String getNameForUid(int uid) {
4074        // reader
4075        synchronized (mPackages) {
4076            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4077            if (obj instanceof SharedUserSetting) {
4078                final SharedUserSetting sus = (SharedUserSetting) obj;
4079                return sus.name + ":" + sus.userId;
4080            } else if (obj instanceof PackageSetting) {
4081                final PackageSetting ps = (PackageSetting) obj;
4082                return ps.name;
4083            }
4084        }
4085        return null;
4086    }
4087
4088    @Override
4089    public int getUidForSharedUser(String sharedUserName) {
4090        if(sharedUserName == null) {
4091            return -1;
4092        }
4093        // reader
4094        synchronized (mPackages) {
4095            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4096            if (suid == null) {
4097                return -1;
4098            }
4099            return suid.userId;
4100        }
4101    }
4102
4103    @Override
4104    public int getFlagsForUid(int uid) {
4105        synchronized (mPackages) {
4106            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4107            if (obj instanceof SharedUserSetting) {
4108                final SharedUserSetting sus = (SharedUserSetting) obj;
4109                return sus.pkgFlags;
4110            } else if (obj instanceof PackageSetting) {
4111                final PackageSetting ps = (PackageSetting) obj;
4112                return ps.pkgFlags;
4113            }
4114        }
4115        return 0;
4116    }
4117
4118    @Override
4119    public int getPrivateFlagsForUid(int uid) {
4120        synchronized (mPackages) {
4121            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4122            if (obj instanceof SharedUserSetting) {
4123                final SharedUserSetting sus = (SharedUserSetting) obj;
4124                return sus.pkgPrivateFlags;
4125            } else if (obj instanceof PackageSetting) {
4126                final PackageSetting ps = (PackageSetting) obj;
4127                return ps.pkgPrivateFlags;
4128            }
4129        }
4130        return 0;
4131    }
4132
4133    @Override
4134    public boolean isUidPrivileged(int uid) {
4135        uid = UserHandle.getAppId(uid);
4136        // reader
4137        synchronized (mPackages) {
4138            Object obj = mSettings.getUserIdLPr(uid);
4139            if (obj instanceof SharedUserSetting) {
4140                final SharedUserSetting sus = (SharedUserSetting) obj;
4141                final Iterator<PackageSetting> it = sus.packages.iterator();
4142                while (it.hasNext()) {
4143                    if (it.next().isPrivileged()) {
4144                        return true;
4145                    }
4146                }
4147            } else if (obj instanceof PackageSetting) {
4148                final PackageSetting ps = (PackageSetting) obj;
4149                return ps.isPrivileged();
4150            }
4151        }
4152        return false;
4153    }
4154
4155    @Override
4156    public String[] getAppOpPermissionPackages(String permissionName) {
4157        synchronized (mPackages) {
4158            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4159            if (pkgs == null) {
4160                return null;
4161            }
4162            return pkgs.toArray(new String[pkgs.size()]);
4163        }
4164    }
4165
4166    @Override
4167    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4168            int flags, int userId) {
4169        if (!sUserManager.exists(userId)) return null;
4170        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4171        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4172        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4173    }
4174
4175    @Override
4176    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4177            IntentFilter filter, int match, ComponentName activity) {
4178        final int userId = UserHandle.getCallingUserId();
4179        if (DEBUG_PREFERRED) {
4180            Log.v(TAG, "setLastChosenActivity intent=" + intent
4181                + " resolvedType=" + resolvedType
4182                + " flags=" + flags
4183                + " filter=" + filter
4184                + " match=" + match
4185                + " activity=" + activity);
4186            filter.dump(new PrintStreamPrinter(System.out), "    ");
4187        }
4188        intent.setComponent(null);
4189        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4190        // Find any earlier preferred or last chosen entries and nuke them
4191        findPreferredActivity(intent, resolvedType,
4192                flags, query, 0, false, true, false, userId);
4193        // Add the new activity as the last chosen for this filter
4194        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4195                "Setting last chosen");
4196    }
4197
4198    @Override
4199    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4200        final int userId = UserHandle.getCallingUserId();
4201        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4202        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4203        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4204                false, false, false, userId);
4205    }
4206
4207    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4208            int flags, List<ResolveInfo> query, int userId) {
4209        if (query != null) {
4210            final int N = query.size();
4211            if (N == 1) {
4212                return query.get(0);
4213            } else if (N > 1) {
4214                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4215                // If there is more than one activity with the same priority,
4216                // then let the user decide between them.
4217                ResolveInfo r0 = query.get(0);
4218                ResolveInfo r1 = query.get(1);
4219                if (DEBUG_INTENT_MATCHING || debug) {
4220                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4221                            + r1.activityInfo.name + "=" + r1.priority);
4222                }
4223                // If the first activity has a higher priority, or a different
4224                // default, then it is always desireable to pick it.
4225                if (r0.priority != r1.priority
4226                        || r0.preferredOrder != r1.preferredOrder
4227                        || r0.isDefault != r1.isDefault) {
4228                    return query.get(0);
4229                }
4230                // If we have saved a preference for a preferred activity for
4231                // this Intent, use that.
4232                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4233                        flags, query, r0.priority, true, false, debug, userId);
4234                if (ri != null) {
4235                    return ri;
4236                }
4237                if (userId != 0) {
4238                    ri = new ResolveInfo(mResolveInfo);
4239                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4240                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4241                            ri.activityInfo.applicationInfo);
4242                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4243                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4244                    return ri;
4245                }
4246                return mResolveInfo;
4247            }
4248        }
4249        return null;
4250    }
4251
4252    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4253            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4254        final int N = query.size();
4255        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4256                .get(userId);
4257        // Get the list of persistent preferred activities that handle the intent
4258        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4259        List<PersistentPreferredActivity> pprefs = ppir != null
4260                ? ppir.queryIntent(intent, resolvedType,
4261                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4262                : null;
4263        if (pprefs != null && pprefs.size() > 0) {
4264            final int M = pprefs.size();
4265            for (int i=0; i<M; i++) {
4266                final PersistentPreferredActivity ppa = pprefs.get(i);
4267                if (DEBUG_PREFERRED || debug) {
4268                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4269                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4270                            + "\n  component=" + ppa.mComponent);
4271                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4272                }
4273                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4274                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4275                if (DEBUG_PREFERRED || debug) {
4276                    Slog.v(TAG, "Found persistent preferred activity:");
4277                    if (ai != null) {
4278                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4279                    } else {
4280                        Slog.v(TAG, "  null");
4281                    }
4282                }
4283                if (ai == null) {
4284                    // This previously registered persistent preferred activity
4285                    // component is no longer known. Ignore it and do NOT remove it.
4286                    continue;
4287                }
4288                for (int j=0; j<N; j++) {
4289                    final ResolveInfo ri = query.get(j);
4290                    if (!ri.activityInfo.applicationInfo.packageName
4291                            .equals(ai.applicationInfo.packageName)) {
4292                        continue;
4293                    }
4294                    if (!ri.activityInfo.name.equals(ai.name)) {
4295                        continue;
4296                    }
4297                    //  Found a persistent preference that can handle the intent.
4298                    if (DEBUG_PREFERRED || debug) {
4299                        Slog.v(TAG, "Returning persistent preferred activity: " +
4300                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4301                    }
4302                    return ri;
4303                }
4304            }
4305        }
4306        return null;
4307    }
4308
4309    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4310            List<ResolveInfo> query, int priority, boolean always,
4311            boolean removeMatches, boolean debug, int userId) {
4312        if (!sUserManager.exists(userId)) return null;
4313        // writer
4314        synchronized (mPackages) {
4315            if (intent.getSelector() != null) {
4316                intent = intent.getSelector();
4317            }
4318            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4319
4320            // Try to find a matching persistent preferred activity.
4321            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4322                    debug, userId);
4323
4324            // If a persistent preferred activity matched, use it.
4325            if (pri != null) {
4326                return pri;
4327            }
4328
4329            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4330            // Get the list of preferred activities that handle the intent
4331            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4332            List<PreferredActivity> prefs = pir != null
4333                    ? pir.queryIntent(intent, resolvedType,
4334                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4335                    : null;
4336            if (prefs != null && prefs.size() > 0) {
4337                boolean changed = false;
4338                try {
4339                    // First figure out how good the original match set is.
4340                    // We will only allow preferred activities that came
4341                    // from the same match quality.
4342                    int match = 0;
4343
4344                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4345
4346                    final int N = query.size();
4347                    for (int j=0; j<N; j++) {
4348                        final ResolveInfo ri = query.get(j);
4349                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4350                                + ": 0x" + Integer.toHexString(match));
4351                        if (ri.match > match) {
4352                            match = ri.match;
4353                        }
4354                    }
4355
4356                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4357                            + Integer.toHexString(match));
4358
4359                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4360                    final int M = prefs.size();
4361                    for (int i=0; i<M; i++) {
4362                        final PreferredActivity pa = prefs.get(i);
4363                        if (DEBUG_PREFERRED || debug) {
4364                            Slog.v(TAG, "Checking PreferredActivity ds="
4365                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4366                                    + "\n  component=" + pa.mPref.mComponent);
4367                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4368                        }
4369                        if (pa.mPref.mMatch != match) {
4370                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4371                                    + Integer.toHexString(pa.mPref.mMatch));
4372                            continue;
4373                        }
4374                        // If it's not an "always" type preferred activity and that's what we're
4375                        // looking for, skip it.
4376                        if (always && !pa.mPref.mAlways) {
4377                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4378                            continue;
4379                        }
4380                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4381                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4382                        if (DEBUG_PREFERRED || debug) {
4383                            Slog.v(TAG, "Found preferred activity:");
4384                            if (ai != null) {
4385                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4386                            } else {
4387                                Slog.v(TAG, "  null");
4388                            }
4389                        }
4390                        if (ai == null) {
4391                            // This previously registered preferred activity
4392                            // component is no longer known.  Most likely an update
4393                            // to the app was installed and in the new version this
4394                            // component no longer exists.  Clean it up by removing
4395                            // it from the preferred activities list, and skip it.
4396                            Slog.w(TAG, "Removing dangling preferred activity: "
4397                                    + pa.mPref.mComponent);
4398                            pir.removeFilter(pa);
4399                            changed = true;
4400                            continue;
4401                        }
4402                        for (int j=0; j<N; j++) {
4403                            final ResolveInfo ri = query.get(j);
4404                            if (!ri.activityInfo.applicationInfo.packageName
4405                                    .equals(ai.applicationInfo.packageName)) {
4406                                continue;
4407                            }
4408                            if (!ri.activityInfo.name.equals(ai.name)) {
4409                                continue;
4410                            }
4411
4412                            if (removeMatches) {
4413                                pir.removeFilter(pa);
4414                                changed = true;
4415                                if (DEBUG_PREFERRED) {
4416                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4417                                }
4418                                break;
4419                            }
4420
4421                            // Okay we found a previously set preferred or last chosen app.
4422                            // If the result set is different from when this
4423                            // was created, we need to clear it and re-ask the
4424                            // user their preference, if we're looking for an "always" type entry.
4425                            if (always && !pa.mPref.sameSet(query)) {
4426                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4427                                        + intent + " type " + resolvedType);
4428                                if (DEBUG_PREFERRED) {
4429                                    Slog.v(TAG, "Removing preferred activity since set changed "
4430                                            + pa.mPref.mComponent);
4431                                }
4432                                pir.removeFilter(pa);
4433                                // Re-add the filter as a "last chosen" entry (!always)
4434                                PreferredActivity lastChosen = new PreferredActivity(
4435                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4436                                pir.addFilter(lastChosen);
4437                                changed = true;
4438                                return null;
4439                            }
4440
4441                            // Yay! Either the set matched or we're looking for the last chosen
4442                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4443                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4444                            return ri;
4445                        }
4446                    }
4447                } finally {
4448                    if (changed) {
4449                        if (DEBUG_PREFERRED) {
4450                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4451                        }
4452                        scheduleWritePackageRestrictionsLocked(userId);
4453                    }
4454                }
4455            }
4456        }
4457        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4458        return null;
4459    }
4460
4461    /*
4462     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4463     */
4464    @Override
4465    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4466            int targetUserId) {
4467        mContext.enforceCallingOrSelfPermission(
4468                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4469        List<CrossProfileIntentFilter> matches =
4470                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4471        if (matches != null) {
4472            int size = matches.size();
4473            for (int i = 0; i < size; i++) {
4474                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4475            }
4476        }
4477        if (hasWebURI(intent)) {
4478            // cross-profile app linking works only towards the parent.
4479            final UserInfo parent = getProfileParent(sourceUserId);
4480            synchronized(mPackages) {
4481                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4482                        intent, resolvedType, 0, sourceUserId, parent.id);
4483                return xpDomainInfo != null;
4484            }
4485        }
4486        return false;
4487    }
4488
4489    private UserInfo getProfileParent(int userId) {
4490        final long identity = Binder.clearCallingIdentity();
4491        try {
4492            return sUserManager.getProfileParent(userId);
4493        } finally {
4494            Binder.restoreCallingIdentity(identity);
4495        }
4496    }
4497
4498    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4499            String resolvedType, int userId) {
4500        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4501        if (resolver != null) {
4502            return resolver.queryIntent(intent, resolvedType, false, userId);
4503        }
4504        return null;
4505    }
4506
4507    @Override
4508    public List<ResolveInfo> queryIntentActivities(Intent intent,
4509            String resolvedType, int flags, int userId) {
4510        if (!sUserManager.exists(userId)) return Collections.emptyList();
4511        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4512        ComponentName comp = intent.getComponent();
4513        if (comp == null) {
4514            if (intent.getSelector() != null) {
4515                intent = intent.getSelector();
4516                comp = intent.getComponent();
4517            }
4518        }
4519
4520        if (comp != null) {
4521            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4522            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4523            if (ai != null) {
4524                final ResolveInfo ri = new ResolveInfo();
4525                ri.activityInfo = ai;
4526                list.add(ri);
4527            }
4528            return list;
4529        }
4530
4531        // reader
4532        synchronized (mPackages) {
4533            final String pkgName = intent.getPackage();
4534            if (pkgName == null) {
4535                List<CrossProfileIntentFilter> matchingFilters =
4536                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4537                // Check for results that need to skip the current profile.
4538                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4539                        resolvedType, flags, userId);
4540                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4541                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4542                    result.add(xpResolveInfo);
4543                    return filterIfNotPrimaryUser(result, userId);
4544                }
4545
4546                // Check for results in the current profile.
4547                List<ResolveInfo> result = mActivities.queryIntent(
4548                        intent, resolvedType, flags, userId);
4549
4550                // Check for cross profile results.
4551                xpResolveInfo = queryCrossProfileIntents(
4552                        matchingFilters, intent, resolvedType, flags, userId);
4553                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4554                    result.add(xpResolveInfo);
4555                    Collections.sort(result, mResolvePrioritySorter);
4556                }
4557                result = filterIfNotPrimaryUser(result, userId);
4558                if (hasWebURI(intent)) {
4559                    CrossProfileDomainInfo xpDomainInfo = null;
4560                    final UserInfo parent = getProfileParent(userId);
4561                    if (parent != null) {
4562                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4563                                flags, userId, parent.id);
4564                    }
4565                    if (xpDomainInfo != null) {
4566                        if (xpResolveInfo != null) {
4567                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4568                            // in the result.
4569                            result.remove(xpResolveInfo);
4570                        }
4571                        if (result.size() == 0) {
4572                            result.add(xpDomainInfo.resolveInfo);
4573                            return result;
4574                        }
4575                    } else if (result.size() <= 1) {
4576                        return result;
4577                    }
4578                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4579                            xpDomainInfo, userId);
4580                    Collections.sort(result, mResolvePrioritySorter);
4581                }
4582                return result;
4583            }
4584            final PackageParser.Package pkg = mPackages.get(pkgName);
4585            if (pkg != null) {
4586                return filterIfNotPrimaryUser(
4587                        mActivities.queryIntentForPackage(
4588                                intent, resolvedType, flags, pkg.activities, userId),
4589                        userId);
4590            }
4591            return new ArrayList<ResolveInfo>();
4592        }
4593    }
4594
4595    private static class CrossProfileDomainInfo {
4596        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4597        ResolveInfo resolveInfo;
4598        /* Best domain verification status of the activities found in the other profile */
4599        int bestDomainVerificationStatus;
4600    }
4601
4602    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4603            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4604        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4605                sourceUserId)) {
4606            return null;
4607        }
4608        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4609                resolvedType, flags, parentUserId);
4610
4611        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4612            return null;
4613        }
4614        CrossProfileDomainInfo result = null;
4615        int size = resultTargetUser.size();
4616        for (int i = 0; i < size; i++) {
4617            ResolveInfo riTargetUser = resultTargetUser.get(i);
4618            // Intent filter verification is only for filters that specify a host. So don't return
4619            // those that handle all web uris.
4620            if (riTargetUser.handleAllWebDataURI) {
4621                continue;
4622            }
4623            String packageName = riTargetUser.activityInfo.packageName;
4624            PackageSetting ps = mSettings.mPackages.get(packageName);
4625            if (ps == null) {
4626                continue;
4627            }
4628            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4629            int status = (int)(verificationState >> 32);
4630            if (result == null) {
4631                result = new CrossProfileDomainInfo();
4632                result.resolveInfo =
4633                        createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId);
4634                result.bestDomainVerificationStatus = status;
4635            } else {
4636                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4637                        result.bestDomainVerificationStatus);
4638            }
4639        }
4640        // Don't consider matches with status NEVER across profiles.
4641        if (result != null && result.bestDomainVerificationStatus
4642                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4643            return null;
4644        }
4645        return result;
4646    }
4647
4648    /**
4649     * Verification statuses are ordered from the worse to the best, except for
4650     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4651     */
4652    private int bestDomainVerificationStatus(int status1, int status2) {
4653        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4654            return status2;
4655        }
4656        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4657            return status1;
4658        }
4659        return (int) MathUtils.max(status1, status2);
4660    }
4661
4662    private boolean isUserEnabled(int userId) {
4663        long callingId = Binder.clearCallingIdentity();
4664        try {
4665            UserInfo userInfo = sUserManager.getUserInfo(userId);
4666            return userInfo != null && userInfo.isEnabled();
4667        } finally {
4668            Binder.restoreCallingIdentity(callingId);
4669        }
4670    }
4671
4672    /**
4673     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4674     *
4675     * @return filtered list
4676     */
4677    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4678        if (userId == UserHandle.USER_OWNER) {
4679            return resolveInfos;
4680        }
4681        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4682            ResolveInfo info = resolveInfos.get(i);
4683            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4684                resolveInfos.remove(i);
4685            }
4686        }
4687        return resolveInfos;
4688    }
4689
4690    private static boolean hasWebURI(Intent intent) {
4691        if (intent.getData() == null) {
4692            return false;
4693        }
4694        final String scheme = intent.getScheme();
4695        if (TextUtils.isEmpty(scheme)) {
4696            return false;
4697        }
4698        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4699    }
4700
4701    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4702            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4703            int userId) {
4704        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4705
4706        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4707            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4708                    candidates.size());
4709        }
4710
4711        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4712        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4713        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4714        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4715        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4716        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4717
4718        synchronized (mPackages) {
4719            final int count = candidates.size();
4720            // First, try to use linked apps. Partition the candidates into four lists:
4721            // one for the final results, one for the "do not use ever", one for "undefined status"
4722            // and finally one for "browser app type".
4723            for (int n=0; n<count; n++) {
4724                ResolveInfo info = candidates.get(n);
4725                String packageName = info.activityInfo.packageName;
4726                PackageSetting ps = mSettings.mPackages.get(packageName);
4727                if (ps != null) {
4728                    // Add to the special match all list (Browser use case)
4729                    if (info.handleAllWebDataURI) {
4730                        matchAllList.add(info);
4731                        continue;
4732                    }
4733                    // Try to get the status from User settings first
4734                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4735                    int status = (int)(packedStatus >> 32);
4736                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4737                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4738                        if (DEBUG_DOMAIN_VERIFICATION) {
4739                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4740                                    + " : linkgen=" + linkGeneration);
4741                        }
4742                        // Use link-enabled generation as preferredOrder, i.e.
4743                        // prefer newly-enabled over earlier-enabled.
4744                        info.preferredOrder = linkGeneration;
4745                        alwaysList.add(info);
4746                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4747                        if (DEBUG_DOMAIN_VERIFICATION) {
4748                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4749                        }
4750                        neverList.add(info);
4751                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4752                        if (DEBUG_DOMAIN_VERIFICATION) {
4753                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4754                        }
4755                        alwaysAskList.add(info);
4756                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4757                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4758                        if (DEBUG_DOMAIN_VERIFICATION) {
4759                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4760                        }
4761                        undefinedList.add(info);
4762                    }
4763                }
4764            }
4765
4766            // We'll want to include browser possibilities in a few cases
4767            boolean includeBrowser = false;
4768
4769            // First try to add the "always" resolution(s) for the current user, if any
4770            if (alwaysList.size() > 0) {
4771                result.addAll(alwaysList);
4772            // if there is an "always" for the parent user, add it.
4773            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4774                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4775                result.add(xpDomainInfo.resolveInfo);
4776            } else {
4777                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4778                result.addAll(undefinedList);
4779                if (xpDomainInfo != null && (
4780                        xpDomainInfo.bestDomainVerificationStatus
4781                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4782                        || xpDomainInfo.bestDomainVerificationStatus
4783                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4784                    result.add(xpDomainInfo.resolveInfo);
4785                }
4786                includeBrowser = true;
4787            }
4788
4789            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4790            // If there were 'always' entries their preferred order has been set, so we also
4791            // back that off to make the alternatives equivalent
4792            if (alwaysAskList.size() > 0) {
4793                for (ResolveInfo i : result) {
4794                    i.preferredOrder = 0;
4795                }
4796                result.addAll(alwaysAskList);
4797                includeBrowser = true;
4798            }
4799
4800            if (includeBrowser) {
4801                // Also add browsers (all of them or only the default one)
4802                if (DEBUG_DOMAIN_VERIFICATION) {
4803                    Slog.v(TAG, "   ...including browsers in candidate set");
4804                }
4805                if ((matchFlags & MATCH_ALL) != 0) {
4806                    result.addAll(matchAllList);
4807                } else {
4808                    // Browser/generic handling case.  If there's a default browser, go straight
4809                    // to that (but only if there is no other higher-priority match).
4810                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4811                    int maxMatchPrio = 0;
4812                    ResolveInfo defaultBrowserMatch = null;
4813                    final int numCandidates = matchAllList.size();
4814                    for (int n = 0; n < numCandidates; n++) {
4815                        ResolveInfo info = matchAllList.get(n);
4816                        // track the highest overall match priority...
4817                        if (info.priority > maxMatchPrio) {
4818                            maxMatchPrio = info.priority;
4819                        }
4820                        // ...and the highest-priority default browser match
4821                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4822                            if (defaultBrowserMatch == null
4823                                    || (defaultBrowserMatch.priority < info.priority)) {
4824                                if (debug) {
4825                                    Slog.v(TAG, "Considering default browser match " + info);
4826                                }
4827                                defaultBrowserMatch = info;
4828                            }
4829                        }
4830                    }
4831                    if (defaultBrowserMatch != null
4832                            && defaultBrowserMatch.priority >= maxMatchPrio
4833                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4834                    {
4835                        if (debug) {
4836                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4837                        }
4838                        result.add(defaultBrowserMatch);
4839                    } else {
4840                        result.addAll(matchAllList);
4841                    }
4842                }
4843
4844                // If there is nothing selected, add all candidates and remove the ones that the user
4845                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4846                if (result.size() == 0) {
4847                    result.addAll(candidates);
4848                    result.removeAll(neverList);
4849                }
4850            }
4851        }
4852        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4853            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4854                    result.size());
4855            for (ResolveInfo info : result) {
4856                Slog.v(TAG, "  + " + info.activityInfo);
4857            }
4858        }
4859        return result;
4860    }
4861
4862    // Returns a packed value as a long:
4863    //
4864    // high 'int'-sized word: link status: undefined/ask/never/always.
4865    // low 'int'-sized word: relative priority among 'always' results.
4866    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4867        long result = ps.getDomainVerificationStatusForUser(userId);
4868        // if none available, get the master status
4869        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4870            if (ps.getIntentFilterVerificationInfo() != null) {
4871                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4872            }
4873        }
4874        return result;
4875    }
4876
4877    private ResolveInfo querySkipCurrentProfileIntents(
4878            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4879            int flags, int sourceUserId) {
4880        if (matchingFilters != null) {
4881            int size = matchingFilters.size();
4882            for (int i = 0; i < size; i ++) {
4883                CrossProfileIntentFilter filter = matchingFilters.get(i);
4884                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4885                    // Checking if there are activities in the target user that can handle the
4886                    // intent.
4887                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4888                            flags, sourceUserId);
4889                    if (resolveInfo != null) {
4890                        return resolveInfo;
4891                    }
4892                }
4893            }
4894        }
4895        return null;
4896    }
4897
4898    // Return matching ResolveInfo if any for skip current profile intent filters.
4899    private ResolveInfo queryCrossProfileIntents(
4900            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4901            int flags, int sourceUserId) {
4902        if (matchingFilters != null) {
4903            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4904            // match the same intent. For performance reasons, it is better not to
4905            // run queryIntent twice for the same userId
4906            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4907            int size = matchingFilters.size();
4908            for (int i = 0; i < size; i++) {
4909                CrossProfileIntentFilter filter = matchingFilters.get(i);
4910                int targetUserId = filter.getTargetUserId();
4911                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4912                        && !alreadyTriedUserIds.get(targetUserId)) {
4913                    // Checking if there are activities in the target user that can handle the
4914                    // intent.
4915                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4916                            flags, sourceUserId);
4917                    if (resolveInfo != null) return resolveInfo;
4918                    alreadyTriedUserIds.put(targetUserId, true);
4919                }
4920            }
4921        }
4922        return null;
4923    }
4924
4925    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4926            String resolvedType, int flags, int sourceUserId) {
4927        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4928                resolvedType, flags, filter.getTargetUserId());
4929        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4930            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4931        }
4932        return null;
4933    }
4934
4935    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4936            int sourceUserId, int targetUserId) {
4937        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4938        String className;
4939        if (targetUserId == UserHandle.USER_OWNER) {
4940            className = FORWARD_INTENT_TO_USER_OWNER;
4941        } else {
4942            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4943        }
4944        ComponentName forwardingActivityComponentName = new ComponentName(
4945                mAndroidApplication.packageName, className);
4946        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4947                sourceUserId);
4948        if (targetUserId == UserHandle.USER_OWNER) {
4949            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4950            forwardingResolveInfo.noResourceId = true;
4951        }
4952        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4953        forwardingResolveInfo.priority = 0;
4954        forwardingResolveInfo.preferredOrder = 0;
4955        forwardingResolveInfo.match = 0;
4956        forwardingResolveInfo.isDefault = true;
4957        forwardingResolveInfo.filter = filter;
4958        forwardingResolveInfo.targetUserId = targetUserId;
4959        return forwardingResolveInfo;
4960    }
4961
4962    @Override
4963    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4964            Intent[] specifics, String[] specificTypes, Intent intent,
4965            String resolvedType, int flags, int userId) {
4966        if (!sUserManager.exists(userId)) return Collections.emptyList();
4967        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4968                false, "query intent activity options");
4969        final String resultsAction = intent.getAction();
4970
4971        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4972                | PackageManager.GET_RESOLVED_FILTER, userId);
4973
4974        if (DEBUG_INTENT_MATCHING) {
4975            Log.v(TAG, "Query " + intent + ": " + results);
4976        }
4977
4978        int specificsPos = 0;
4979        int N;
4980
4981        // todo: note that the algorithm used here is O(N^2).  This
4982        // isn't a problem in our current environment, but if we start running
4983        // into situations where we have more than 5 or 10 matches then this
4984        // should probably be changed to something smarter...
4985
4986        // First we go through and resolve each of the specific items
4987        // that were supplied, taking care of removing any corresponding
4988        // duplicate items in the generic resolve list.
4989        if (specifics != null) {
4990            for (int i=0; i<specifics.length; i++) {
4991                final Intent sintent = specifics[i];
4992                if (sintent == null) {
4993                    continue;
4994                }
4995
4996                if (DEBUG_INTENT_MATCHING) {
4997                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4998                }
4999
5000                String action = sintent.getAction();
5001                if (resultsAction != null && resultsAction.equals(action)) {
5002                    // If this action was explicitly requested, then don't
5003                    // remove things that have it.
5004                    action = null;
5005                }
5006
5007                ResolveInfo ri = null;
5008                ActivityInfo ai = null;
5009
5010                ComponentName comp = sintent.getComponent();
5011                if (comp == null) {
5012                    ri = resolveIntent(
5013                        sintent,
5014                        specificTypes != null ? specificTypes[i] : null,
5015                            flags, userId);
5016                    if (ri == null) {
5017                        continue;
5018                    }
5019                    if (ri == mResolveInfo) {
5020                        // ACK!  Must do something better with this.
5021                    }
5022                    ai = ri.activityInfo;
5023                    comp = new ComponentName(ai.applicationInfo.packageName,
5024                            ai.name);
5025                } else {
5026                    ai = getActivityInfo(comp, flags, userId);
5027                    if (ai == null) {
5028                        continue;
5029                    }
5030                }
5031
5032                // Look for any generic query activities that are duplicates
5033                // of this specific one, and remove them from the results.
5034                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5035                N = results.size();
5036                int j;
5037                for (j=specificsPos; j<N; j++) {
5038                    ResolveInfo sri = results.get(j);
5039                    if ((sri.activityInfo.name.equals(comp.getClassName())
5040                            && sri.activityInfo.applicationInfo.packageName.equals(
5041                                    comp.getPackageName()))
5042                        || (action != null && sri.filter.matchAction(action))) {
5043                        results.remove(j);
5044                        if (DEBUG_INTENT_MATCHING) Log.v(
5045                            TAG, "Removing duplicate item from " + j
5046                            + " due to specific " + specificsPos);
5047                        if (ri == null) {
5048                            ri = sri;
5049                        }
5050                        j--;
5051                        N--;
5052                    }
5053                }
5054
5055                // Add this specific item to its proper place.
5056                if (ri == null) {
5057                    ri = new ResolveInfo();
5058                    ri.activityInfo = ai;
5059                }
5060                results.add(specificsPos, ri);
5061                ri.specificIndex = i;
5062                specificsPos++;
5063            }
5064        }
5065
5066        // Now we go through the remaining generic results and remove any
5067        // duplicate actions that are found here.
5068        N = results.size();
5069        for (int i=specificsPos; i<N-1; i++) {
5070            final ResolveInfo rii = results.get(i);
5071            if (rii.filter == null) {
5072                continue;
5073            }
5074
5075            // Iterate over all of the actions of this result's intent
5076            // filter...  typically this should be just one.
5077            final Iterator<String> it = rii.filter.actionsIterator();
5078            if (it == null) {
5079                continue;
5080            }
5081            while (it.hasNext()) {
5082                final String action = it.next();
5083                if (resultsAction != null && resultsAction.equals(action)) {
5084                    // If this action was explicitly requested, then don't
5085                    // remove things that have it.
5086                    continue;
5087                }
5088                for (int j=i+1; j<N; j++) {
5089                    final ResolveInfo rij = results.get(j);
5090                    if (rij.filter != null && rij.filter.hasAction(action)) {
5091                        results.remove(j);
5092                        if (DEBUG_INTENT_MATCHING) Log.v(
5093                            TAG, "Removing duplicate item from " + j
5094                            + " due to action " + action + " at " + i);
5095                        j--;
5096                        N--;
5097                    }
5098                }
5099            }
5100
5101            // If the caller didn't request filter information, drop it now
5102            // so we don't have to marshall/unmarshall it.
5103            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5104                rii.filter = null;
5105            }
5106        }
5107
5108        // Filter out the caller activity if so requested.
5109        if (caller != null) {
5110            N = results.size();
5111            for (int i=0; i<N; i++) {
5112                ActivityInfo ainfo = results.get(i).activityInfo;
5113                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5114                        && caller.getClassName().equals(ainfo.name)) {
5115                    results.remove(i);
5116                    break;
5117                }
5118            }
5119        }
5120
5121        // If the caller didn't request filter information,
5122        // drop them now so we don't have to
5123        // marshall/unmarshall it.
5124        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5125            N = results.size();
5126            for (int i=0; i<N; i++) {
5127                results.get(i).filter = null;
5128            }
5129        }
5130
5131        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5132        return results;
5133    }
5134
5135    @Override
5136    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5137            int userId) {
5138        if (!sUserManager.exists(userId)) return Collections.emptyList();
5139        ComponentName comp = intent.getComponent();
5140        if (comp == null) {
5141            if (intent.getSelector() != null) {
5142                intent = intent.getSelector();
5143                comp = intent.getComponent();
5144            }
5145        }
5146        if (comp != null) {
5147            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5148            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5149            if (ai != null) {
5150                ResolveInfo ri = new ResolveInfo();
5151                ri.activityInfo = ai;
5152                list.add(ri);
5153            }
5154            return list;
5155        }
5156
5157        // reader
5158        synchronized (mPackages) {
5159            String pkgName = intent.getPackage();
5160            if (pkgName == null) {
5161                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5162            }
5163            final PackageParser.Package pkg = mPackages.get(pkgName);
5164            if (pkg != null) {
5165                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5166                        userId);
5167            }
5168            return null;
5169        }
5170    }
5171
5172    @Override
5173    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5174        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5175        if (!sUserManager.exists(userId)) return null;
5176        if (query != null) {
5177            if (query.size() >= 1) {
5178                // If there is more than one service with the same priority,
5179                // just arbitrarily pick the first one.
5180                return query.get(0);
5181            }
5182        }
5183        return null;
5184    }
5185
5186    @Override
5187    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5188            int userId) {
5189        if (!sUserManager.exists(userId)) return Collections.emptyList();
5190        ComponentName comp = intent.getComponent();
5191        if (comp == null) {
5192            if (intent.getSelector() != null) {
5193                intent = intent.getSelector();
5194                comp = intent.getComponent();
5195            }
5196        }
5197        if (comp != null) {
5198            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5199            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5200            if (si != null) {
5201                final ResolveInfo ri = new ResolveInfo();
5202                ri.serviceInfo = si;
5203                list.add(ri);
5204            }
5205            return list;
5206        }
5207
5208        // reader
5209        synchronized (mPackages) {
5210            String pkgName = intent.getPackage();
5211            if (pkgName == null) {
5212                return mServices.queryIntent(intent, resolvedType, flags, userId);
5213            }
5214            final PackageParser.Package pkg = mPackages.get(pkgName);
5215            if (pkg != null) {
5216                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5217                        userId);
5218            }
5219            return null;
5220        }
5221    }
5222
5223    @Override
5224    public List<ResolveInfo> queryIntentContentProviders(
5225            Intent intent, String resolvedType, int flags, int userId) {
5226        if (!sUserManager.exists(userId)) return Collections.emptyList();
5227        ComponentName comp = intent.getComponent();
5228        if (comp == null) {
5229            if (intent.getSelector() != null) {
5230                intent = intent.getSelector();
5231                comp = intent.getComponent();
5232            }
5233        }
5234        if (comp != null) {
5235            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5236            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5237            if (pi != null) {
5238                final ResolveInfo ri = new ResolveInfo();
5239                ri.providerInfo = pi;
5240                list.add(ri);
5241            }
5242            return list;
5243        }
5244
5245        // reader
5246        synchronized (mPackages) {
5247            String pkgName = intent.getPackage();
5248            if (pkgName == null) {
5249                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5250            }
5251            final PackageParser.Package pkg = mPackages.get(pkgName);
5252            if (pkg != null) {
5253                return mProviders.queryIntentForPackage(
5254                        intent, resolvedType, flags, pkg.providers, userId);
5255            }
5256            return null;
5257        }
5258    }
5259
5260    @Override
5261    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5262        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5263
5264        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5265
5266        // writer
5267        synchronized (mPackages) {
5268            ArrayList<PackageInfo> list;
5269            if (listUninstalled) {
5270                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5271                for (PackageSetting ps : mSettings.mPackages.values()) {
5272                    PackageInfo pi;
5273                    if (ps.pkg != null) {
5274                        pi = generatePackageInfo(ps.pkg, flags, userId);
5275                    } else {
5276                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5277                    }
5278                    if (pi != null) {
5279                        list.add(pi);
5280                    }
5281                }
5282            } else {
5283                list = new ArrayList<PackageInfo>(mPackages.size());
5284                for (PackageParser.Package p : mPackages.values()) {
5285                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5286                    if (pi != null) {
5287                        list.add(pi);
5288                    }
5289                }
5290            }
5291
5292            return new ParceledListSlice<PackageInfo>(list);
5293        }
5294    }
5295
5296    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5297            String[] permissions, boolean[] tmp, int flags, int userId) {
5298        int numMatch = 0;
5299        final PermissionsState permissionsState = ps.getPermissionsState();
5300        for (int i=0; i<permissions.length; i++) {
5301            final String permission = permissions[i];
5302            if (permissionsState.hasPermission(permission, userId)) {
5303                tmp[i] = true;
5304                numMatch++;
5305            } else {
5306                tmp[i] = false;
5307            }
5308        }
5309        if (numMatch == 0) {
5310            return;
5311        }
5312        PackageInfo pi;
5313        if (ps.pkg != null) {
5314            pi = generatePackageInfo(ps.pkg, flags, userId);
5315        } else {
5316            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5317        }
5318        // The above might return null in cases of uninstalled apps or install-state
5319        // skew across users/profiles.
5320        if (pi != null) {
5321            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5322                if (numMatch == permissions.length) {
5323                    pi.requestedPermissions = permissions;
5324                } else {
5325                    pi.requestedPermissions = new String[numMatch];
5326                    numMatch = 0;
5327                    for (int i=0; i<permissions.length; i++) {
5328                        if (tmp[i]) {
5329                            pi.requestedPermissions[numMatch] = permissions[i];
5330                            numMatch++;
5331                        }
5332                    }
5333                }
5334            }
5335            list.add(pi);
5336        }
5337    }
5338
5339    @Override
5340    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5341            String[] permissions, int flags, int userId) {
5342        if (!sUserManager.exists(userId)) return null;
5343        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5344
5345        // writer
5346        synchronized (mPackages) {
5347            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5348            boolean[] tmpBools = new boolean[permissions.length];
5349            if (listUninstalled) {
5350                for (PackageSetting ps : mSettings.mPackages.values()) {
5351                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5352                }
5353            } else {
5354                for (PackageParser.Package pkg : mPackages.values()) {
5355                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5356                    if (ps != null) {
5357                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5358                                userId);
5359                    }
5360                }
5361            }
5362
5363            return new ParceledListSlice<PackageInfo>(list);
5364        }
5365    }
5366
5367    @Override
5368    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5369        if (!sUserManager.exists(userId)) return null;
5370        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5371
5372        // writer
5373        synchronized (mPackages) {
5374            ArrayList<ApplicationInfo> list;
5375            if (listUninstalled) {
5376                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5377                for (PackageSetting ps : mSettings.mPackages.values()) {
5378                    ApplicationInfo ai;
5379                    if (ps.pkg != null) {
5380                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5381                                ps.readUserState(userId), userId);
5382                    } else {
5383                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5384                    }
5385                    if (ai != null) {
5386                        list.add(ai);
5387                    }
5388                }
5389            } else {
5390                list = new ArrayList<ApplicationInfo>(mPackages.size());
5391                for (PackageParser.Package p : mPackages.values()) {
5392                    if (p.mExtras != null) {
5393                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5394                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5395                        if (ai != null) {
5396                            list.add(ai);
5397                        }
5398                    }
5399                }
5400            }
5401
5402            return new ParceledListSlice<ApplicationInfo>(list);
5403        }
5404    }
5405
5406    public List<ApplicationInfo> getPersistentApplications(int flags) {
5407        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5408
5409        // reader
5410        synchronized (mPackages) {
5411            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5412            final int userId = UserHandle.getCallingUserId();
5413            while (i.hasNext()) {
5414                final PackageParser.Package p = i.next();
5415                if (p.applicationInfo != null
5416                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5417                        && (!mSafeMode || isSystemApp(p))) {
5418                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5419                    if (ps != null) {
5420                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5421                                ps.readUserState(userId), userId);
5422                        if (ai != null) {
5423                            finalList.add(ai);
5424                        }
5425                    }
5426                }
5427            }
5428        }
5429
5430        return finalList;
5431    }
5432
5433    @Override
5434    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5435        if (!sUserManager.exists(userId)) return null;
5436        // reader
5437        synchronized (mPackages) {
5438            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5439            PackageSetting ps = provider != null
5440                    ? mSettings.mPackages.get(provider.owner.packageName)
5441                    : null;
5442            return ps != null
5443                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5444                    && (!mSafeMode || (provider.info.applicationInfo.flags
5445                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5446                    ? PackageParser.generateProviderInfo(provider, flags,
5447                            ps.readUserState(userId), userId)
5448                    : null;
5449        }
5450    }
5451
5452    /**
5453     * @deprecated
5454     */
5455    @Deprecated
5456    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5457        // reader
5458        synchronized (mPackages) {
5459            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5460                    .entrySet().iterator();
5461            final int userId = UserHandle.getCallingUserId();
5462            while (i.hasNext()) {
5463                Map.Entry<String, PackageParser.Provider> entry = i.next();
5464                PackageParser.Provider p = entry.getValue();
5465                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5466
5467                if (ps != null && p.syncable
5468                        && (!mSafeMode || (p.info.applicationInfo.flags
5469                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5470                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5471                            ps.readUserState(userId), userId);
5472                    if (info != null) {
5473                        outNames.add(entry.getKey());
5474                        outInfo.add(info);
5475                    }
5476                }
5477            }
5478        }
5479    }
5480
5481    @Override
5482    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5483            int uid, int flags) {
5484        ArrayList<ProviderInfo> finalList = null;
5485        // reader
5486        synchronized (mPackages) {
5487            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5488            final int userId = processName != null ?
5489                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5490            while (i.hasNext()) {
5491                final PackageParser.Provider p = i.next();
5492                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5493                if (ps != null && p.info.authority != null
5494                        && (processName == null
5495                                || (p.info.processName.equals(processName)
5496                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5497                        && mSettings.isEnabledLPr(p.info, flags, userId)
5498                        && (!mSafeMode
5499                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5500                    if (finalList == null) {
5501                        finalList = new ArrayList<ProviderInfo>(3);
5502                    }
5503                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5504                            ps.readUserState(userId), userId);
5505                    if (info != null) {
5506                        finalList.add(info);
5507                    }
5508                }
5509            }
5510        }
5511
5512        if (finalList != null) {
5513            Collections.sort(finalList, mProviderInitOrderSorter);
5514            return new ParceledListSlice<ProviderInfo>(finalList);
5515        }
5516
5517        return null;
5518    }
5519
5520    @Override
5521    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5522            int flags) {
5523        // reader
5524        synchronized (mPackages) {
5525            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5526            return PackageParser.generateInstrumentationInfo(i, flags);
5527        }
5528    }
5529
5530    @Override
5531    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5532            int flags) {
5533        ArrayList<InstrumentationInfo> finalList =
5534            new ArrayList<InstrumentationInfo>();
5535
5536        // reader
5537        synchronized (mPackages) {
5538            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5539            while (i.hasNext()) {
5540                final PackageParser.Instrumentation p = i.next();
5541                if (targetPackage == null
5542                        || targetPackage.equals(p.info.targetPackage)) {
5543                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5544                            flags);
5545                    if (ii != null) {
5546                        finalList.add(ii);
5547                    }
5548                }
5549            }
5550        }
5551
5552        return finalList;
5553    }
5554
5555    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5556        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5557        if (overlays == null) {
5558            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5559            return;
5560        }
5561        for (PackageParser.Package opkg : overlays.values()) {
5562            // Not much to do if idmap fails: we already logged the error
5563            // and we certainly don't want to abort installation of pkg simply
5564            // because an overlay didn't fit properly. For these reasons,
5565            // ignore the return value of createIdmapForPackagePairLI.
5566            createIdmapForPackagePairLI(pkg, opkg);
5567        }
5568    }
5569
5570    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5571            PackageParser.Package opkg) {
5572        if (!opkg.mTrustedOverlay) {
5573            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5574                    opkg.baseCodePath + ": overlay not trusted");
5575            return false;
5576        }
5577        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5578        if (overlaySet == null) {
5579            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5580                    opkg.baseCodePath + " but target package has no known overlays");
5581            return false;
5582        }
5583        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5584        // TODO: generate idmap for split APKs
5585        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5586            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5587                    + opkg.baseCodePath);
5588            return false;
5589        }
5590        PackageParser.Package[] overlayArray =
5591            overlaySet.values().toArray(new PackageParser.Package[0]);
5592        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5593            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5594                return p1.mOverlayPriority - p2.mOverlayPriority;
5595            }
5596        };
5597        Arrays.sort(overlayArray, cmp);
5598
5599        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5600        int i = 0;
5601        for (PackageParser.Package p : overlayArray) {
5602            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5603        }
5604        return true;
5605    }
5606
5607    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5608        final File[] files = dir.listFiles();
5609        if (ArrayUtils.isEmpty(files)) {
5610            Log.d(TAG, "No files in app dir " + dir);
5611            return;
5612        }
5613
5614        if (DEBUG_PACKAGE_SCANNING) {
5615            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5616                    + " flags=0x" + Integer.toHexString(parseFlags));
5617        }
5618
5619        for (File file : files) {
5620            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5621                    && !PackageInstallerService.isStageName(file.getName());
5622            if (!isPackage) {
5623                // Ignore entries which are not packages
5624                continue;
5625            }
5626            try {
5627                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5628                        scanFlags, currentTime, null);
5629            } catch (PackageManagerException e) {
5630                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5631
5632                // Delete invalid userdata apps
5633                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5634                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5635                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5636                    if (file.isDirectory()) {
5637                        mInstaller.rmPackageDir(file.getAbsolutePath());
5638                    } else {
5639                        file.delete();
5640                    }
5641                }
5642            }
5643        }
5644    }
5645
5646    private static File getSettingsProblemFile() {
5647        File dataDir = Environment.getDataDirectory();
5648        File systemDir = new File(dataDir, "system");
5649        File fname = new File(systemDir, "uiderrors.txt");
5650        return fname;
5651    }
5652
5653    static void reportSettingsProblem(int priority, String msg) {
5654        logCriticalInfo(priority, msg);
5655    }
5656
5657    static void logCriticalInfo(int priority, String msg) {
5658        Slog.println(priority, TAG, msg);
5659        EventLogTags.writePmCriticalInfo(msg);
5660        try {
5661            File fname = getSettingsProblemFile();
5662            FileOutputStream out = new FileOutputStream(fname, true);
5663            PrintWriter pw = new FastPrintWriter(out);
5664            SimpleDateFormat formatter = new SimpleDateFormat();
5665            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5666            pw.println(dateString + ": " + msg);
5667            pw.close();
5668            FileUtils.setPermissions(
5669                    fname.toString(),
5670                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5671                    -1, -1);
5672        } catch (java.io.IOException e) {
5673        }
5674    }
5675
5676    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5677            PackageParser.Package pkg, File srcFile, int parseFlags)
5678            throws PackageManagerException {
5679        if (ps != null
5680                && ps.codePath.equals(srcFile)
5681                && ps.timeStamp == srcFile.lastModified()
5682                && !isCompatSignatureUpdateNeeded(pkg)
5683                && !isRecoverSignatureUpdateNeeded(pkg)) {
5684            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5685            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5686            ArraySet<PublicKey> signingKs;
5687            synchronized (mPackages) {
5688                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5689            }
5690            if (ps.signatures.mSignatures != null
5691                    && ps.signatures.mSignatures.length != 0
5692                    && signingKs != null) {
5693                // Optimization: reuse the existing cached certificates
5694                // if the package appears to be unchanged.
5695                pkg.mSignatures = ps.signatures.mSignatures;
5696                pkg.mSigningKeys = signingKs;
5697                return;
5698            }
5699
5700            Slog.w(TAG, "PackageSetting for " + ps.name
5701                    + " is missing signatures.  Collecting certs again to recover them.");
5702        } else {
5703            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5704        }
5705
5706        try {
5707            pp.collectCertificates(pkg, parseFlags);
5708            pp.collectManifestDigest(pkg);
5709        } catch (PackageParserException e) {
5710            throw PackageManagerException.from(e);
5711        }
5712    }
5713
5714    /*
5715     *  Scan a package and return the newly parsed package.
5716     *  Returns null in case of errors and the error code is stored in mLastScanError
5717     */
5718    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5719            long currentTime, UserHandle user) throws PackageManagerException {
5720        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5721        parseFlags |= mDefParseFlags;
5722        PackageParser pp = new PackageParser();
5723        pp.setSeparateProcesses(mSeparateProcesses);
5724        pp.setOnlyCoreApps(mOnlyCore);
5725        pp.setDisplayMetrics(mMetrics);
5726
5727        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5728            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5729        }
5730
5731        final PackageParser.Package pkg;
5732        try {
5733            pkg = pp.parsePackage(scanFile, parseFlags);
5734        } catch (PackageParserException e) {
5735            throw PackageManagerException.from(e);
5736        }
5737
5738        PackageSetting ps = null;
5739        PackageSetting updatedPkg;
5740        // reader
5741        synchronized (mPackages) {
5742            // Look to see if we already know about this package.
5743            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5744            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5745                // This package has been renamed to its original name.  Let's
5746                // use that.
5747                ps = mSettings.peekPackageLPr(oldName);
5748            }
5749            // If there was no original package, see one for the real package name.
5750            if (ps == null) {
5751                ps = mSettings.peekPackageLPr(pkg.packageName);
5752            }
5753            // Check to see if this package could be hiding/updating a system
5754            // package.  Must look for it either under the original or real
5755            // package name depending on our state.
5756            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5757            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5758        }
5759        boolean updatedPkgBetter = false;
5760        // First check if this is a system package that may involve an update
5761        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5762            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5763            // it needs to drop FLAG_PRIVILEGED.
5764            if (locationIsPrivileged(scanFile)) {
5765                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5766            } else {
5767                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5768            }
5769
5770            if (ps != null && !ps.codePath.equals(scanFile)) {
5771                // The path has changed from what was last scanned...  check the
5772                // version of the new path against what we have stored to determine
5773                // what to do.
5774                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5775                if (pkg.mVersionCode <= ps.versionCode) {
5776                    // The system package has been updated and the code path does not match
5777                    // Ignore entry. Skip it.
5778                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5779                            + " ignored: updated version " + ps.versionCode
5780                            + " better than this " + pkg.mVersionCode);
5781                    if (!updatedPkg.codePath.equals(scanFile)) {
5782                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5783                                + ps.name + " changing from " + updatedPkg.codePathString
5784                                + " to " + scanFile);
5785                        updatedPkg.codePath = scanFile;
5786                        updatedPkg.codePathString = scanFile.toString();
5787                        updatedPkg.resourcePath = scanFile;
5788                        updatedPkg.resourcePathString = scanFile.toString();
5789                    }
5790                    updatedPkg.pkg = pkg;
5791                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5792                            "Package " + ps.name + " at " + scanFile
5793                                    + " ignored: updated version " + ps.versionCode
5794                                    + " better than this " + pkg.mVersionCode);
5795                } else {
5796                    // The current app on the system partition is better than
5797                    // what we have updated to on the data partition; switch
5798                    // back to the system partition version.
5799                    // At this point, its safely assumed that package installation for
5800                    // apps in system partition will go through. If not there won't be a working
5801                    // version of the app
5802                    // writer
5803                    synchronized (mPackages) {
5804                        // Just remove the loaded entries from package lists.
5805                        mPackages.remove(ps.name);
5806                    }
5807
5808                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5809                            + " reverting from " + ps.codePathString
5810                            + ": new version " + pkg.mVersionCode
5811                            + " better than installed " + ps.versionCode);
5812
5813                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5814                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5815                    synchronized (mInstallLock) {
5816                        args.cleanUpResourcesLI();
5817                    }
5818                    synchronized (mPackages) {
5819                        mSettings.enableSystemPackageLPw(ps.name);
5820                    }
5821                    updatedPkgBetter = true;
5822                }
5823            }
5824        }
5825
5826        if (updatedPkg != null) {
5827            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5828            // initially
5829            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5830
5831            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5832            // flag set initially
5833            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5834                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5835            }
5836        }
5837
5838        // Verify certificates against what was last scanned
5839        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5840
5841        /*
5842         * A new system app appeared, but we already had a non-system one of the
5843         * same name installed earlier.
5844         */
5845        boolean shouldHideSystemApp = false;
5846        if (updatedPkg == null && ps != null
5847                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5848            /*
5849             * Check to make sure the signatures match first. If they don't,
5850             * wipe the installed application and its data.
5851             */
5852            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5853                    != PackageManager.SIGNATURE_MATCH) {
5854                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5855                        + " signatures don't match existing userdata copy; removing");
5856                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5857                ps = null;
5858            } else {
5859                /*
5860                 * If the newly-added system app is an older version than the
5861                 * already installed version, hide it. It will be scanned later
5862                 * and re-added like an update.
5863                 */
5864                if (pkg.mVersionCode <= ps.versionCode) {
5865                    shouldHideSystemApp = true;
5866                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5867                            + " but new version " + pkg.mVersionCode + " better than installed "
5868                            + ps.versionCode + "; hiding system");
5869                } else {
5870                    /*
5871                     * The newly found system app is a newer version that the
5872                     * one previously installed. Simply remove the
5873                     * already-installed application and replace it with our own
5874                     * while keeping the application data.
5875                     */
5876                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5877                            + " reverting from " + ps.codePathString + ": new version "
5878                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5879                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5880                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5881                    synchronized (mInstallLock) {
5882                        args.cleanUpResourcesLI();
5883                    }
5884                }
5885            }
5886        }
5887
5888        // The apk is forward locked (not public) if its code and resources
5889        // are kept in different files. (except for app in either system or
5890        // vendor path).
5891        // TODO grab this value from PackageSettings
5892        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5893            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5894                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5895            }
5896        }
5897
5898        // TODO: extend to support forward-locked splits
5899        String resourcePath = null;
5900        String baseResourcePath = null;
5901        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5902            if (ps != null && ps.resourcePathString != null) {
5903                resourcePath = ps.resourcePathString;
5904                baseResourcePath = ps.resourcePathString;
5905            } else {
5906                // Should not happen at all. Just log an error.
5907                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5908            }
5909        } else {
5910            resourcePath = pkg.codePath;
5911            baseResourcePath = pkg.baseCodePath;
5912        }
5913
5914        // Set application objects path explicitly.
5915        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5916        pkg.applicationInfo.setCodePath(pkg.codePath);
5917        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5918        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5919        pkg.applicationInfo.setResourcePath(resourcePath);
5920        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5921        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5922
5923        // Note that we invoke the following method only if we are about to unpack an application
5924        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5925                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5926
5927        /*
5928         * If the system app should be overridden by a previously installed
5929         * data, hide the system app now and let the /data/app scan pick it up
5930         * again.
5931         */
5932        if (shouldHideSystemApp) {
5933            synchronized (mPackages) {
5934                /*
5935                 * We have to grant systems permissions before we hide, because
5936                 * grantPermissions will assume the package update is trying to
5937                 * expand its permissions.
5938                 */
5939                grantPermissionsLPw(pkg, true, pkg.packageName);
5940                mSettings.disableSystemPackageLPw(pkg.packageName);
5941            }
5942        }
5943
5944        return scannedPkg;
5945    }
5946
5947    private static String fixProcessName(String defProcessName,
5948            String processName, int uid) {
5949        if (processName == null) {
5950            return defProcessName;
5951        }
5952        return processName;
5953    }
5954
5955    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5956            throws PackageManagerException {
5957        if (pkgSetting.signatures.mSignatures != null) {
5958            // Already existing package. Make sure signatures match
5959            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5960                    == PackageManager.SIGNATURE_MATCH;
5961            if (!match) {
5962                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5963                        == PackageManager.SIGNATURE_MATCH;
5964            }
5965            if (!match) {
5966                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5967                        == PackageManager.SIGNATURE_MATCH;
5968            }
5969            if (!match) {
5970                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5971                        + pkg.packageName + " signatures do not match the "
5972                        + "previously installed version; ignoring!");
5973            }
5974        }
5975
5976        // Check for shared user signatures
5977        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5978            // Already existing package. Make sure signatures match
5979            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5980                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5981            if (!match) {
5982                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5983                        == PackageManager.SIGNATURE_MATCH;
5984            }
5985            if (!match) {
5986                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5987                        == PackageManager.SIGNATURE_MATCH;
5988            }
5989            if (!match) {
5990                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5991                        "Package " + pkg.packageName
5992                        + " has no signatures that match those in shared user "
5993                        + pkgSetting.sharedUser.name + "; ignoring!");
5994            }
5995        }
5996    }
5997
5998    /**
5999     * Enforces that only the system UID or root's UID can call a method exposed
6000     * via Binder.
6001     *
6002     * @param message used as message if SecurityException is thrown
6003     * @throws SecurityException if the caller is not system or root
6004     */
6005    private static final void enforceSystemOrRoot(String message) {
6006        final int uid = Binder.getCallingUid();
6007        if (uid != Process.SYSTEM_UID && uid != 0) {
6008            throw new SecurityException(message);
6009        }
6010    }
6011
6012    @Override
6013    public void performBootDexOpt() {
6014        enforceSystemOrRoot("Only the system can request dexopt be performed");
6015
6016        // Before everything else, see whether we need to fstrim.
6017        try {
6018            IMountService ms = PackageHelper.getMountService();
6019            if (ms != null) {
6020                final boolean isUpgrade = isUpgrade();
6021                boolean doTrim = isUpgrade;
6022                if (doTrim) {
6023                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6024                } else {
6025                    final long interval = android.provider.Settings.Global.getLong(
6026                            mContext.getContentResolver(),
6027                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6028                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6029                    if (interval > 0) {
6030                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6031                        if (timeSinceLast > interval) {
6032                            doTrim = true;
6033                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6034                                    + "; running immediately");
6035                        }
6036                    }
6037                }
6038                if (doTrim) {
6039                    if (!isFirstBoot()) {
6040                        try {
6041                            ActivityManagerNative.getDefault().showBootMessage(
6042                                    mContext.getResources().getString(
6043                                            R.string.android_upgrading_fstrim), true);
6044                        } catch (RemoteException e) {
6045                        }
6046                    }
6047                    ms.runMaintenance();
6048                }
6049            } else {
6050                Slog.e(TAG, "Mount service unavailable!");
6051            }
6052        } catch (RemoteException e) {
6053            // Can't happen; MountService is local
6054        }
6055
6056        final ArraySet<PackageParser.Package> pkgs;
6057        synchronized (mPackages) {
6058            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6059        }
6060
6061        if (pkgs != null) {
6062            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6063            // in case the device runs out of space.
6064            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6065            // Give priority to core apps.
6066            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6067                PackageParser.Package pkg = it.next();
6068                if (pkg.coreApp) {
6069                    if (DEBUG_DEXOPT) {
6070                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6071                    }
6072                    sortedPkgs.add(pkg);
6073                    it.remove();
6074                }
6075            }
6076            // Give priority to system apps that listen for pre boot complete.
6077            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6078            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6079            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6080                PackageParser.Package pkg = it.next();
6081                if (pkgNames.contains(pkg.packageName)) {
6082                    if (DEBUG_DEXOPT) {
6083                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6084                    }
6085                    sortedPkgs.add(pkg);
6086                    it.remove();
6087                }
6088            }
6089            // Filter out packages that aren't recently used.
6090            filterRecentlyUsedApps(pkgs);
6091            // Add all remaining apps.
6092            for (PackageParser.Package pkg : pkgs) {
6093                if (DEBUG_DEXOPT) {
6094                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6095                }
6096                sortedPkgs.add(pkg);
6097            }
6098
6099            // If we want to be lazy, filter everything that wasn't recently used.
6100            if (mLazyDexOpt) {
6101                filterRecentlyUsedApps(sortedPkgs);
6102            }
6103
6104            int i = 0;
6105            int total = sortedPkgs.size();
6106            File dataDir = Environment.getDataDirectory();
6107            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6108            if (lowThreshold == 0) {
6109                throw new IllegalStateException("Invalid low memory threshold");
6110            }
6111            for (PackageParser.Package pkg : sortedPkgs) {
6112                long usableSpace = dataDir.getUsableSpace();
6113                if (usableSpace < lowThreshold) {
6114                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6115                    break;
6116                }
6117                performBootDexOpt(pkg, ++i, total);
6118            }
6119        }
6120    }
6121
6122    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6123        // Filter out packages that aren't recently used.
6124        //
6125        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6126        // should do a full dexopt.
6127        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6128            int total = pkgs.size();
6129            int skipped = 0;
6130            long now = System.currentTimeMillis();
6131            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6132                PackageParser.Package pkg = i.next();
6133                long then = pkg.mLastPackageUsageTimeInMills;
6134                if (then + mDexOptLRUThresholdInMills < now) {
6135                    if (DEBUG_DEXOPT) {
6136                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6137                              ((then == 0) ? "never" : new Date(then)));
6138                    }
6139                    i.remove();
6140                    skipped++;
6141                }
6142            }
6143            if (DEBUG_DEXOPT) {
6144                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6145            }
6146        }
6147    }
6148
6149    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6150        List<ResolveInfo> ris = null;
6151        try {
6152            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6153                    intent, null, 0, UserHandle.USER_OWNER);
6154        } catch (RemoteException e) {
6155        }
6156        ArraySet<String> pkgNames = new ArraySet<String>();
6157        if (ris != null) {
6158            for (ResolveInfo ri : ris) {
6159                pkgNames.add(ri.activityInfo.packageName);
6160            }
6161        }
6162        return pkgNames;
6163    }
6164
6165    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6166        if (DEBUG_DEXOPT) {
6167            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6168        }
6169        if (!isFirstBoot()) {
6170            try {
6171                ActivityManagerNative.getDefault().showBootMessage(
6172                        mContext.getResources().getString(R.string.android_upgrading_apk,
6173                                curr, total), true);
6174            } catch (RemoteException e) {
6175            }
6176        }
6177        PackageParser.Package p = pkg;
6178        synchronized (mInstallLock) {
6179            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6180                    false /* force dex */, false /* defer */, true /* include dependencies */,
6181                    false /* boot complete */);
6182        }
6183    }
6184
6185    @Override
6186    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6187        return performDexOpt(packageName, instructionSet, false);
6188    }
6189
6190    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6191        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6192        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6193        if (!dexopt && !updateUsage) {
6194            // We aren't going to dexopt or update usage, so bail early.
6195            return false;
6196        }
6197        PackageParser.Package p;
6198        final String targetInstructionSet;
6199        synchronized (mPackages) {
6200            p = mPackages.get(packageName);
6201            if (p == null) {
6202                return false;
6203            }
6204            if (updateUsage) {
6205                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6206            }
6207            mPackageUsage.write(false);
6208            if (!dexopt) {
6209                // We aren't going to dexopt, so bail early.
6210                return false;
6211            }
6212
6213            targetInstructionSet = instructionSet != null ? instructionSet :
6214                    getPrimaryInstructionSet(p.applicationInfo);
6215            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6216                return false;
6217            }
6218        }
6219        long callingId = Binder.clearCallingIdentity();
6220        try {
6221            synchronized (mInstallLock) {
6222                final String[] instructionSets = new String[] { targetInstructionSet };
6223                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6224                        false /* forceDex */, false /* defer */, true /* inclDependencies */,
6225                        true /* boot complete */);
6226                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6227            }
6228        } finally {
6229            Binder.restoreCallingIdentity(callingId);
6230        }
6231    }
6232
6233    public ArraySet<String> getPackagesThatNeedDexOpt() {
6234        ArraySet<String> pkgs = null;
6235        synchronized (mPackages) {
6236            for (PackageParser.Package p : mPackages.values()) {
6237                if (DEBUG_DEXOPT) {
6238                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6239                }
6240                if (!p.mDexOptPerformed.isEmpty()) {
6241                    continue;
6242                }
6243                if (pkgs == null) {
6244                    pkgs = new ArraySet<String>();
6245                }
6246                pkgs.add(p.packageName);
6247            }
6248        }
6249        return pkgs;
6250    }
6251
6252    public void shutdown() {
6253        mPackageUsage.write(true);
6254    }
6255
6256    @Override
6257    public void forceDexOpt(String packageName) {
6258        enforceSystemOrRoot("forceDexOpt");
6259
6260        PackageParser.Package pkg;
6261        synchronized (mPackages) {
6262            pkg = mPackages.get(packageName);
6263            if (pkg == null) {
6264                throw new IllegalArgumentException("Missing package: " + packageName);
6265            }
6266        }
6267
6268        synchronized (mInstallLock) {
6269            final String[] instructionSets = new String[] {
6270                    getPrimaryInstructionSet(pkg.applicationInfo) };
6271            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6272                    true /*forceDex*/, false /* defer */, true /* inclDependencies */,
6273                    true /* boot complete */);
6274            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6275                throw new IllegalStateException("Failed to dexopt: " + res);
6276            }
6277        }
6278    }
6279
6280    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6281        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6282            Slog.w(TAG, "Unable to update from " + oldPkg.name
6283                    + " to " + newPkg.packageName
6284                    + ": old package not in system partition");
6285            return false;
6286        } else if (mPackages.get(oldPkg.name) != null) {
6287            Slog.w(TAG, "Unable to update from " + oldPkg.name
6288                    + " to " + newPkg.packageName
6289                    + ": old package still exists");
6290            return false;
6291        }
6292        return true;
6293    }
6294
6295    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6296        int[] users = sUserManager.getUserIds();
6297        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6298        if (res < 0) {
6299            return res;
6300        }
6301        for (int user : users) {
6302            if (user != 0) {
6303                res = mInstaller.createUserData(volumeUuid, packageName,
6304                        UserHandle.getUid(user, uid), user, seinfo);
6305                if (res < 0) {
6306                    return res;
6307                }
6308            }
6309        }
6310        return res;
6311    }
6312
6313    private int removeDataDirsLI(String volumeUuid, String packageName) {
6314        int[] users = sUserManager.getUserIds();
6315        int res = 0;
6316        for (int user : users) {
6317            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6318            if (resInner < 0) {
6319                res = resInner;
6320            }
6321        }
6322
6323        return res;
6324    }
6325
6326    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6327        int[] users = sUserManager.getUserIds();
6328        int res = 0;
6329        for (int user : users) {
6330            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6331            if (resInner < 0) {
6332                res = resInner;
6333            }
6334        }
6335        return res;
6336    }
6337
6338    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6339            PackageParser.Package changingLib) {
6340        if (file.path != null) {
6341            usesLibraryFiles.add(file.path);
6342            return;
6343        }
6344        PackageParser.Package p = mPackages.get(file.apk);
6345        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6346            // If we are doing this while in the middle of updating a library apk,
6347            // then we need to make sure to use that new apk for determining the
6348            // dependencies here.  (We haven't yet finished committing the new apk
6349            // to the package manager state.)
6350            if (p == null || p.packageName.equals(changingLib.packageName)) {
6351                p = changingLib;
6352            }
6353        }
6354        if (p != null) {
6355            usesLibraryFiles.addAll(p.getAllCodePaths());
6356        }
6357    }
6358
6359    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6360            PackageParser.Package changingLib) throws PackageManagerException {
6361        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6362            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6363            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6364            for (int i=0; i<N; i++) {
6365                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6366                if (file == null) {
6367                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6368                            "Package " + pkg.packageName + " requires unavailable shared library "
6369                            + pkg.usesLibraries.get(i) + "; failing!");
6370                }
6371                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6372            }
6373            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6374            for (int i=0; i<N; i++) {
6375                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6376                if (file == null) {
6377                    Slog.w(TAG, "Package " + pkg.packageName
6378                            + " desires unavailable shared library "
6379                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6380                } else {
6381                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6382                }
6383            }
6384            N = usesLibraryFiles.size();
6385            if (N > 0) {
6386                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6387            } else {
6388                pkg.usesLibraryFiles = null;
6389            }
6390        }
6391    }
6392
6393    private static boolean hasString(List<String> list, List<String> which) {
6394        if (list == null) {
6395            return false;
6396        }
6397        for (int i=list.size()-1; i>=0; i--) {
6398            for (int j=which.size()-1; j>=0; j--) {
6399                if (which.get(j).equals(list.get(i))) {
6400                    return true;
6401                }
6402            }
6403        }
6404        return false;
6405    }
6406
6407    private void updateAllSharedLibrariesLPw() {
6408        for (PackageParser.Package pkg : mPackages.values()) {
6409            try {
6410                updateSharedLibrariesLPw(pkg, null);
6411            } catch (PackageManagerException e) {
6412                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6413            }
6414        }
6415    }
6416
6417    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6418            PackageParser.Package changingPkg) {
6419        ArrayList<PackageParser.Package> res = null;
6420        for (PackageParser.Package pkg : mPackages.values()) {
6421            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6422                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6423                if (res == null) {
6424                    res = new ArrayList<PackageParser.Package>();
6425                }
6426                res.add(pkg);
6427                try {
6428                    updateSharedLibrariesLPw(pkg, changingPkg);
6429                } catch (PackageManagerException e) {
6430                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6431                }
6432            }
6433        }
6434        return res;
6435    }
6436
6437    /**
6438     * Derive the value of the {@code cpuAbiOverride} based on the provided
6439     * value and an optional stored value from the package settings.
6440     */
6441    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6442        String cpuAbiOverride = null;
6443
6444        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6445            cpuAbiOverride = null;
6446        } else if (abiOverride != null) {
6447            cpuAbiOverride = abiOverride;
6448        } else if (settings != null) {
6449            cpuAbiOverride = settings.cpuAbiOverrideString;
6450        }
6451
6452        return cpuAbiOverride;
6453    }
6454
6455    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6456            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6457        boolean success = false;
6458        try {
6459            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6460                    currentTime, user);
6461            success = true;
6462            return res;
6463        } finally {
6464            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6465                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6466            }
6467        }
6468    }
6469
6470    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6471            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6472        final File scanFile = new File(pkg.codePath);
6473        if (pkg.applicationInfo.getCodePath() == null ||
6474                pkg.applicationInfo.getResourcePath() == null) {
6475            // Bail out. The resource and code paths haven't been set.
6476            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6477                    "Code and resource paths haven't been set correctly");
6478        }
6479
6480        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6481            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6482        } else {
6483            // Only allow system apps to be flagged as core apps.
6484            pkg.coreApp = false;
6485        }
6486
6487        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6488            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6489        }
6490
6491        if (mCustomResolverComponentName != null &&
6492                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6493            setUpCustomResolverActivity(pkg);
6494        }
6495
6496        if (pkg.packageName.equals("android")) {
6497            synchronized (mPackages) {
6498                if (mAndroidApplication != null) {
6499                    Slog.w(TAG, "*************************************************");
6500                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6501                    Slog.w(TAG, " file=" + scanFile);
6502                    Slog.w(TAG, "*************************************************");
6503                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6504                            "Core android package being redefined.  Skipping.");
6505                }
6506
6507                // Set up information for our fall-back user intent resolution activity.
6508                mPlatformPackage = pkg;
6509                pkg.mVersionCode = mSdkVersion;
6510                mAndroidApplication = pkg.applicationInfo;
6511
6512                if (!mResolverReplaced) {
6513                    mResolveActivity.applicationInfo = mAndroidApplication;
6514                    mResolveActivity.name = ResolverActivity.class.getName();
6515                    mResolveActivity.packageName = mAndroidApplication.packageName;
6516                    mResolveActivity.processName = "system:ui";
6517                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6518                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6519                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6520                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6521                    mResolveActivity.exported = true;
6522                    mResolveActivity.enabled = true;
6523                    mResolveInfo.activityInfo = mResolveActivity;
6524                    mResolveInfo.priority = 0;
6525                    mResolveInfo.preferredOrder = 0;
6526                    mResolveInfo.match = 0;
6527                    mResolveComponentName = new ComponentName(
6528                            mAndroidApplication.packageName, mResolveActivity.name);
6529                }
6530            }
6531        }
6532
6533        if (DEBUG_PACKAGE_SCANNING) {
6534            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6535                Log.d(TAG, "Scanning package " + pkg.packageName);
6536        }
6537
6538        if (mPackages.containsKey(pkg.packageName)
6539                || mSharedLibraries.containsKey(pkg.packageName)) {
6540            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6541                    "Application package " + pkg.packageName
6542                    + " already installed.  Skipping duplicate.");
6543        }
6544
6545        // If we're only installing presumed-existing packages, require that the
6546        // scanned APK is both already known and at the path previously established
6547        // for it.  Previously unknown packages we pick up normally, but if we have an
6548        // a priori expectation about this package's install presence, enforce it.
6549        // With a singular exception for new system packages. When an OTA contains
6550        // a new system package, we allow the codepath to change from a system location
6551        // to the user-installed location. If we don't allow this change, any newer,
6552        // user-installed version of the application will be ignored.
6553        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6554            if (mExpectingBetter.containsKey(pkg.packageName)) {
6555                logCriticalInfo(Log.WARN,
6556                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6557            } else {
6558                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6559                if (known != null) {
6560                    if (DEBUG_PACKAGE_SCANNING) {
6561                        Log.d(TAG, "Examining " + pkg.codePath
6562                                + " and requiring known paths " + known.codePathString
6563                                + " & " + known.resourcePathString);
6564                    }
6565                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6566                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6567                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6568                                "Application package " + pkg.packageName
6569                                + " found at " + pkg.applicationInfo.getCodePath()
6570                                + " but expected at " + known.codePathString + "; ignoring.");
6571                    }
6572                }
6573            }
6574        }
6575
6576        // Initialize package source and resource directories
6577        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6578        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6579
6580        SharedUserSetting suid = null;
6581        PackageSetting pkgSetting = null;
6582
6583        if (!isSystemApp(pkg)) {
6584            // Only system apps can use these features.
6585            pkg.mOriginalPackages = null;
6586            pkg.mRealPackage = null;
6587            pkg.mAdoptPermissions = null;
6588        }
6589
6590        // writer
6591        synchronized (mPackages) {
6592            if (pkg.mSharedUserId != null) {
6593                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6594                if (suid == null) {
6595                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6596                            "Creating application package " + pkg.packageName
6597                            + " for shared user failed");
6598                }
6599                if (DEBUG_PACKAGE_SCANNING) {
6600                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6601                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6602                                + "): packages=" + suid.packages);
6603                }
6604            }
6605
6606            // Check if we are renaming from an original package name.
6607            PackageSetting origPackage = null;
6608            String realName = null;
6609            if (pkg.mOriginalPackages != null) {
6610                // This package may need to be renamed to a previously
6611                // installed name.  Let's check on that...
6612                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6613                if (pkg.mOriginalPackages.contains(renamed)) {
6614                    // This package had originally been installed as the
6615                    // original name, and we have already taken care of
6616                    // transitioning to the new one.  Just update the new
6617                    // one to continue using the old name.
6618                    realName = pkg.mRealPackage;
6619                    if (!pkg.packageName.equals(renamed)) {
6620                        // Callers into this function may have already taken
6621                        // care of renaming the package; only do it here if
6622                        // it is not already done.
6623                        pkg.setPackageName(renamed);
6624                    }
6625
6626                } else {
6627                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6628                        if ((origPackage = mSettings.peekPackageLPr(
6629                                pkg.mOriginalPackages.get(i))) != null) {
6630                            // We do have the package already installed under its
6631                            // original name...  should we use it?
6632                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6633                                // New package is not compatible with original.
6634                                origPackage = null;
6635                                continue;
6636                            } else if (origPackage.sharedUser != null) {
6637                                // Make sure uid is compatible between packages.
6638                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6639                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6640                                            + " to " + pkg.packageName + ": old uid "
6641                                            + origPackage.sharedUser.name
6642                                            + " differs from " + pkg.mSharedUserId);
6643                                    origPackage = null;
6644                                    continue;
6645                                }
6646                            } else {
6647                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6648                                        + pkg.packageName + " to old name " + origPackage.name);
6649                            }
6650                            break;
6651                        }
6652                    }
6653                }
6654            }
6655
6656            if (mTransferedPackages.contains(pkg.packageName)) {
6657                Slog.w(TAG, "Package " + pkg.packageName
6658                        + " was transferred to another, but its .apk remains");
6659            }
6660
6661            // Just create the setting, don't add it yet. For already existing packages
6662            // the PkgSetting exists already and doesn't have to be created.
6663            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6664                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6665                    pkg.applicationInfo.primaryCpuAbi,
6666                    pkg.applicationInfo.secondaryCpuAbi,
6667                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6668                    user, false);
6669            if (pkgSetting == null) {
6670                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6671                        "Creating application package " + pkg.packageName + " failed");
6672            }
6673
6674            if (pkgSetting.origPackage != null) {
6675                // If we are first transitioning from an original package,
6676                // fix up the new package's name now.  We need to do this after
6677                // looking up the package under its new name, so getPackageLP
6678                // can take care of fiddling things correctly.
6679                pkg.setPackageName(origPackage.name);
6680
6681                // File a report about this.
6682                String msg = "New package " + pkgSetting.realName
6683                        + " renamed to replace old package " + pkgSetting.name;
6684                reportSettingsProblem(Log.WARN, msg);
6685
6686                // Make a note of it.
6687                mTransferedPackages.add(origPackage.name);
6688
6689                // No longer need to retain this.
6690                pkgSetting.origPackage = null;
6691            }
6692
6693            if (realName != null) {
6694                // Make a note of it.
6695                mTransferedPackages.add(pkg.packageName);
6696            }
6697
6698            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6699                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6700            }
6701
6702            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6703                // Check all shared libraries and map to their actual file path.
6704                // We only do this here for apps not on a system dir, because those
6705                // are the only ones that can fail an install due to this.  We
6706                // will take care of the system apps by updating all of their
6707                // library paths after the scan is done.
6708                updateSharedLibrariesLPw(pkg, null);
6709            }
6710
6711            if (mFoundPolicyFile) {
6712                SELinuxMMAC.assignSeinfoValue(pkg);
6713            }
6714
6715            pkg.applicationInfo.uid = pkgSetting.appId;
6716            pkg.mExtras = pkgSetting;
6717            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6718                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6719                    // We just determined the app is signed correctly, so bring
6720                    // over the latest parsed certs.
6721                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6722                } else {
6723                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6724                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6725                                "Package " + pkg.packageName + " upgrade keys do not match the "
6726                                + "previously installed version");
6727                    } else {
6728                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6729                        String msg = "System package " + pkg.packageName
6730                            + " signature changed; retaining data.";
6731                        reportSettingsProblem(Log.WARN, msg);
6732                    }
6733                }
6734            } else {
6735                try {
6736                    verifySignaturesLP(pkgSetting, pkg);
6737                    // We just determined the app is signed correctly, so bring
6738                    // over the latest parsed certs.
6739                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6740                } catch (PackageManagerException e) {
6741                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6742                        throw e;
6743                    }
6744                    // The signature has changed, but this package is in the system
6745                    // image...  let's recover!
6746                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6747                    // However...  if this package is part of a shared user, but it
6748                    // doesn't match the signature of the shared user, let's fail.
6749                    // What this means is that you can't change the signatures
6750                    // associated with an overall shared user, which doesn't seem all
6751                    // that unreasonable.
6752                    if (pkgSetting.sharedUser != null) {
6753                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6754                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6755                            throw new PackageManagerException(
6756                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6757                                            "Signature mismatch for shared user : "
6758                                            + pkgSetting.sharedUser);
6759                        }
6760                    }
6761                    // File a report about this.
6762                    String msg = "System package " + pkg.packageName
6763                        + " signature changed; retaining data.";
6764                    reportSettingsProblem(Log.WARN, msg);
6765                }
6766            }
6767            // Verify that this new package doesn't have any content providers
6768            // that conflict with existing packages.  Only do this if the
6769            // package isn't already installed, since we don't want to break
6770            // things that are installed.
6771            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6772                final int N = pkg.providers.size();
6773                int i;
6774                for (i=0; i<N; i++) {
6775                    PackageParser.Provider p = pkg.providers.get(i);
6776                    if (p.info.authority != null) {
6777                        String names[] = p.info.authority.split(";");
6778                        for (int j = 0; j < names.length; j++) {
6779                            if (mProvidersByAuthority.containsKey(names[j])) {
6780                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6781                                final String otherPackageName =
6782                                        ((other != null && other.getComponentName() != null) ?
6783                                                other.getComponentName().getPackageName() : "?");
6784                                throw new PackageManagerException(
6785                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6786                                                "Can't install because provider name " + names[j]
6787                                                + " (in package " + pkg.applicationInfo.packageName
6788                                                + ") is already used by " + otherPackageName);
6789                            }
6790                        }
6791                    }
6792                }
6793            }
6794
6795            if (pkg.mAdoptPermissions != null) {
6796                // This package wants to adopt ownership of permissions from
6797                // another package.
6798                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6799                    final String origName = pkg.mAdoptPermissions.get(i);
6800                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6801                    if (orig != null) {
6802                        if (verifyPackageUpdateLPr(orig, pkg)) {
6803                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6804                                    + pkg.packageName);
6805                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6806                        }
6807                    }
6808                }
6809            }
6810        }
6811
6812        final String pkgName = pkg.packageName;
6813
6814        final long scanFileTime = scanFile.lastModified();
6815        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6816        pkg.applicationInfo.processName = fixProcessName(
6817                pkg.applicationInfo.packageName,
6818                pkg.applicationInfo.processName,
6819                pkg.applicationInfo.uid);
6820
6821        File dataPath;
6822        if (mPlatformPackage == pkg) {
6823            // The system package is special.
6824            dataPath = new File(Environment.getDataDirectory(), "system");
6825
6826            pkg.applicationInfo.dataDir = dataPath.getPath();
6827
6828        } else {
6829            // This is a normal package, need to make its data directory.
6830            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6831                    UserHandle.USER_OWNER, pkg.packageName);
6832
6833            boolean uidError = false;
6834            if (dataPath.exists()) {
6835                int currentUid = 0;
6836                try {
6837                    StructStat stat = Os.stat(dataPath.getPath());
6838                    currentUid = stat.st_uid;
6839                } catch (ErrnoException e) {
6840                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6841                }
6842
6843                // If we have mismatched owners for the data path, we have a problem.
6844                if (currentUid != pkg.applicationInfo.uid) {
6845                    boolean recovered = false;
6846                    if (currentUid == 0) {
6847                        // The directory somehow became owned by root.  Wow.
6848                        // This is probably because the system was stopped while
6849                        // installd was in the middle of messing with its libs
6850                        // directory.  Ask installd to fix that.
6851                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6852                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6853                        if (ret >= 0) {
6854                            recovered = true;
6855                            String msg = "Package " + pkg.packageName
6856                                    + " unexpectedly changed to uid 0; recovered to " +
6857                                    + pkg.applicationInfo.uid;
6858                            reportSettingsProblem(Log.WARN, msg);
6859                        }
6860                    }
6861                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6862                            || (scanFlags&SCAN_BOOTING) != 0)) {
6863                        // If this is a system app, we can at least delete its
6864                        // current data so the application will still work.
6865                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6866                        if (ret >= 0) {
6867                            // TODO: Kill the processes first
6868                            // Old data gone!
6869                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6870                                    ? "System package " : "Third party package ";
6871                            String msg = prefix + pkg.packageName
6872                                    + " has changed from uid: "
6873                                    + currentUid + " to "
6874                                    + pkg.applicationInfo.uid + "; old data erased";
6875                            reportSettingsProblem(Log.WARN, msg);
6876                            recovered = true;
6877
6878                            // And now re-install the app.
6879                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6880                                    pkg.applicationInfo.seinfo);
6881                            if (ret == -1) {
6882                                // Ack should not happen!
6883                                msg = prefix + pkg.packageName
6884                                        + " could not have data directory re-created after delete.";
6885                                reportSettingsProblem(Log.WARN, msg);
6886                                throw new PackageManagerException(
6887                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6888                            }
6889                        }
6890                        if (!recovered) {
6891                            mHasSystemUidErrors = true;
6892                        }
6893                    } else if (!recovered) {
6894                        // If we allow this install to proceed, we will be broken.
6895                        // Abort, abort!
6896                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6897                                "scanPackageLI");
6898                    }
6899                    if (!recovered) {
6900                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6901                            + pkg.applicationInfo.uid + "/fs_"
6902                            + currentUid;
6903                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6904                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6905                        String msg = "Package " + pkg.packageName
6906                                + " has mismatched uid: "
6907                                + currentUid + " on disk, "
6908                                + pkg.applicationInfo.uid + " in settings";
6909                        // writer
6910                        synchronized (mPackages) {
6911                            mSettings.mReadMessages.append(msg);
6912                            mSettings.mReadMessages.append('\n');
6913                            uidError = true;
6914                            if (!pkgSetting.uidError) {
6915                                reportSettingsProblem(Log.ERROR, msg);
6916                            }
6917                        }
6918                    }
6919                }
6920                pkg.applicationInfo.dataDir = dataPath.getPath();
6921                if (mShouldRestoreconData) {
6922                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6923                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6924                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6925                }
6926            } else {
6927                if (DEBUG_PACKAGE_SCANNING) {
6928                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6929                        Log.v(TAG, "Want this data dir: " + dataPath);
6930                }
6931                //invoke installer to do the actual installation
6932                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6933                        pkg.applicationInfo.seinfo);
6934                if (ret < 0) {
6935                    // Error from installer
6936                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6937                            "Unable to create data dirs [errorCode=" + ret + "]");
6938                }
6939
6940                if (dataPath.exists()) {
6941                    pkg.applicationInfo.dataDir = dataPath.getPath();
6942                } else {
6943                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6944                    pkg.applicationInfo.dataDir = null;
6945                }
6946            }
6947
6948            pkgSetting.uidError = uidError;
6949        }
6950
6951        final String path = scanFile.getPath();
6952        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6953
6954        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6955            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6956
6957            // Some system apps still use directory structure for native libraries
6958            // in which case we might end up not detecting abi solely based on apk
6959            // structure. Try to detect abi based on directory structure.
6960            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6961                    pkg.applicationInfo.primaryCpuAbi == null) {
6962                setBundledAppAbisAndRoots(pkg, pkgSetting);
6963                setNativeLibraryPaths(pkg);
6964            }
6965
6966        } else {
6967            if ((scanFlags & SCAN_MOVE) != 0) {
6968                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6969                // but we already have this packages package info in the PackageSetting. We just
6970                // use that and derive the native library path based on the new codepath.
6971                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6972                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6973            }
6974
6975            // Set native library paths again. For moves, the path will be updated based on the
6976            // ABIs we've determined above. For non-moves, the path will be updated based on the
6977            // ABIs we determined during compilation, but the path will depend on the final
6978            // package path (after the rename away from the stage path).
6979            setNativeLibraryPaths(pkg);
6980        }
6981
6982        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6983        final int[] userIds = sUserManager.getUserIds();
6984        synchronized (mInstallLock) {
6985            // Make sure all user data directories are ready to roll; we're okay
6986            // if they already exist
6987            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6988                for (int userId : userIds) {
6989                    if (userId != 0) {
6990                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6991                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6992                                pkg.applicationInfo.seinfo);
6993                    }
6994                }
6995            }
6996
6997            // Create a native library symlink only if we have native libraries
6998            // and if the native libraries are 32 bit libraries. We do not provide
6999            // this symlink for 64 bit libraries.
7000            if (pkg.applicationInfo.primaryCpuAbi != null &&
7001                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7002                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7003                for (int userId : userIds) {
7004                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7005                            nativeLibPath, userId) < 0) {
7006                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7007                                "Failed linking native library dir (user=" + userId + ")");
7008                    }
7009                }
7010            }
7011        }
7012
7013        // This is a special case for the "system" package, where the ABI is
7014        // dictated by the zygote configuration (and init.rc). We should keep track
7015        // of this ABI so that we can deal with "normal" applications that run under
7016        // the same UID correctly.
7017        if (mPlatformPackage == pkg) {
7018            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7019                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7020        }
7021
7022        // If there's a mismatch between the abi-override in the package setting
7023        // and the abiOverride specified for the install. Warn about this because we
7024        // would've already compiled the app without taking the package setting into
7025        // account.
7026        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7027            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7028                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7029                        " for package: " + pkg.packageName);
7030            }
7031        }
7032
7033        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7034        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7035        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7036
7037        // Copy the derived override back to the parsed package, so that we can
7038        // update the package settings accordingly.
7039        pkg.cpuAbiOverride = cpuAbiOverride;
7040
7041        if (DEBUG_ABI_SELECTION) {
7042            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7043                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7044                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7045        }
7046
7047        // Push the derived path down into PackageSettings so we know what to
7048        // clean up at uninstall time.
7049        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7050
7051        if (DEBUG_ABI_SELECTION) {
7052            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7053                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7054                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7055        }
7056
7057        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7058            // We don't do this here during boot because we can do it all
7059            // at once after scanning all existing packages.
7060            //
7061            // We also do this *before* we perform dexopt on this package, so that
7062            // we can avoid redundant dexopts, and also to make sure we've got the
7063            // code and package path correct.
7064            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7065                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */);
7066        }
7067
7068        if ((scanFlags & SCAN_NO_DEX) == 0) {
7069            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7070                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */,
7071                    (scanFlags & SCAN_BOOTING) == 0);
7072            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7073                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7074            }
7075        }
7076        if (mFactoryTest && pkg.requestedPermissions.contains(
7077                android.Manifest.permission.FACTORY_TEST)) {
7078            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7079        }
7080
7081        ArrayList<PackageParser.Package> clientLibPkgs = null;
7082
7083        // writer
7084        synchronized (mPackages) {
7085            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7086                // Only system apps can add new shared libraries.
7087                if (pkg.libraryNames != null) {
7088                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7089                        String name = pkg.libraryNames.get(i);
7090                        boolean allowed = false;
7091                        if (pkg.isUpdatedSystemApp()) {
7092                            // New library entries can only be added through the
7093                            // system image.  This is important to get rid of a lot
7094                            // of nasty edge cases: for example if we allowed a non-
7095                            // system update of the app to add a library, then uninstalling
7096                            // the update would make the library go away, and assumptions
7097                            // we made such as through app install filtering would now
7098                            // have allowed apps on the device which aren't compatible
7099                            // with it.  Better to just have the restriction here, be
7100                            // conservative, and create many fewer cases that can negatively
7101                            // impact the user experience.
7102                            final PackageSetting sysPs = mSettings
7103                                    .getDisabledSystemPkgLPr(pkg.packageName);
7104                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7105                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7106                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7107                                        allowed = true;
7108                                        allowed = true;
7109                                        break;
7110                                    }
7111                                }
7112                            }
7113                        } else {
7114                            allowed = true;
7115                        }
7116                        if (allowed) {
7117                            if (!mSharedLibraries.containsKey(name)) {
7118                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7119                            } else if (!name.equals(pkg.packageName)) {
7120                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7121                                        + name + " already exists; skipping");
7122                            }
7123                        } else {
7124                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7125                                    + name + " that is not declared on system image; skipping");
7126                        }
7127                    }
7128                    if ((scanFlags&SCAN_BOOTING) == 0) {
7129                        // If we are not booting, we need to update any applications
7130                        // that are clients of our shared library.  If we are booting,
7131                        // this will all be done once the scan is complete.
7132                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7133                    }
7134                }
7135            }
7136        }
7137
7138        // We also need to dexopt any apps that are dependent on this library.  Note that
7139        // if these fail, we should abort the install since installing the library will
7140        // result in some apps being broken.
7141        if (clientLibPkgs != null) {
7142            if ((scanFlags & SCAN_NO_DEX) == 0) {
7143                for (int i = 0; i < clientLibPkgs.size(); i++) {
7144                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7145                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7146                            null /* instruction sets */, forceDex,
7147                            (scanFlags & SCAN_DEFER_DEX) != 0, false,
7148                            (scanFlags & SCAN_BOOTING) == 0);
7149                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7150                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7151                                "scanPackageLI failed to dexopt clientLibPkgs");
7152                    }
7153                }
7154            }
7155        }
7156
7157        // Request the ActivityManager to kill the process(only for existing packages)
7158        // so that we do not end up in a confused state while the user is still using the older
7159        // version of the application while the new one gets installed.
7160        if ((scanFlags & SCAN_REPLACING) != 0) {
7161            killApplication(pkg.applicationInfo.packageName,
7162                        pkg.applicationInfo.uid, "replace pkg");
7163        }
7164
7165        // Also need to kill any apps that are dependent on the library.
7166        if (clientLibPkgs != null) {
7167            for (int i=0; i<clientLibPkgs.size(); i++) {
7168                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7169                killApplication(clientPkg.applicationInfo.packageName,
7170                        clientPkg.applicationInfo.uid, "update lib");
7171            }
7172        }
7173
7174        // Make sure we're not adding any bogus keyset info
7175        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7176        ksms.assertScannedPackageValid(pkg);
7177
7178        // writer
7179        synchronized (mPackages) {
7180            // We don't expect installation to fail beyond this point
7181
7182            // Add the new setting to mSettings
7183            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7184            // Add the new setting to mPackages
7185            mPackages.put(pkg.applicationInfo.packageName, pkg);
7186            // Make sure we don't accidentally delete its data.
7187            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7188            while (iter.hasNext()) {
7189                PackageCleanItem item = iter.next();
7190                if (pkgName.equals(item.packageName)) {
7191                    iter.remove();
7192                }
7193            }
7194
7195            // Take care of first install / last update times.
7196            if (currentTime != 0) {
7197                if (pkgSetting.firstInstallTime == 0) {
7198                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7199                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7200                    pkgSetting.lastUpdateTime = currentTime;
7201                }
7202            } else if (pkgSetting.firstInstallTime == 0) {
7203                // We need *something*.  Take time time stamp of the file.
7204                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7205            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7206                if (scanFileTime != pkgSetting.timeStamp) {
7207                    // A package on the system image has changed; consider this
7208                    // to be an update.
7209                    pkgSetting.lastUpdateTime = scanFileTime;
7210                }
7211            }
7212
7213            // Add the package's KeySets to the global KeySetManagerService
7214            ksms.addScannedPackageLPw(pkg);
7215
7216            int N = pkg.providers.size();
7217            StringBuilder r = null;
7218            int i;
7219            for (i=0; i<N; i++) {
7220                PackageParser.Provider p = pkg.providers.get(i);
7221                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7222                        p.info.processName, pkg.applicationInfo.uid);
7223                mProviders.addProvider(p);
7224                p.syncable = p.info.isSyncable;
7225                if (p.info.authority != null) {
7226                    String names[] = p.info.authority.split(";");
7227                    p.info.authority = null;
7228                    for (int j = 0; j < names.length; j++) {
7229                        if (j == 1 && p.syncable) {
7230                            // We only want the first authority for a provider to possibly be
7231                            // syncable, so if we already added this provider using a different
7232                            // authority clear the syncable flag. We copy the provider before
7233                            // changing it because the mProviders object contains a reference
7234                            // to a provider that we don't want to change.
7235                            // Only do this for the second authority since the resulting provider
7236                            // object can be the same for all future authorities for this provider.
7237                            p = new PackageParser.Provider(p);
7238                            p.syncable = false;
7239                        }
7240                        if (!mProvidersByAuthority.containsKey(names[j])) {
7241                            mProvidersByAuthority.put(names[j], p);
7242                            if (p.info.authority == null) {
7243                                p.info.authority = names[j];
7244                            } else {
7245                                p.info.authority = p.info.authority + ";" + names[j];
7246                            }
7247                            if (DEBUG_PACKAGE_SCANNING) {
7248                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7249                                    Log.d(TAG, "Registered content provider: " + names[j]
7250                                            + ", className = " + p.info.name + ", isSyncable = "
7251                                            + p.info.isSyncable);
7252                            }
7253                        } else {
7254                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7255                            Slog.w(TAG, "Skipping provider name " + names[j] +
7256                                    " (in package " + pkg.applicationInfo.packageName +
7257                                    "): name already used by "
7258                                    + ((other != null && other.getComponentName() != null)
7259                                            ? other.getComponentName().getPackageName() : "?"));
7260                        }
7261                    }
7262                }
7263                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7264                    if (r == null) {
7265                        r = new StringBuilder(256);
7266                    } else {
7267                        r.append(' ');
7268                    }
7269                    r.append(p.info.name);
7270                }
7271            }
7272            if (r != null) {
7273                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7274            }
7275
7276            N = pkg.services.size();
7277            r = null;
7278            for (i=0; i<N; i++) {
7279                PackageParser.Service s = pkg.services.get(i);
7280                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7281                        s.info.processName, pkg.applicationInfo.uid);
7282                mServices.addService(s);
7283                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7284                    if (r == null) {
7285                        r = new StringBuilder(256);
7286                    } else {
7287                        r.append(' ');
7288                    }
7289                    r.append(s.info.name);
7290                }
7291            }
7292            if (r != null) {
7293                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7294            }
7295
7296            N = pkg.receivers.size();
7297            r = null;
7298            for (i=0; i<N; i++) {
7299                PackageParser.Activity a = pkg.receivers.get(i);
7300                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7301                        a.info.processName, pkg.applicationInfo.uid);
7302                mReceivers.addActivity(a, "receiver");
7303                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7304                    if (r == null) {
7305                        r = new StringBuilder(256);
7306                    } else {
7307                        r.append(' ');
7308                    }
7309                    r.append(a.info.name);
7310                }
7311            }
7312            if (r != null) {
7313                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7314            }
7315
7316            N = pkg.activities.size();
7317            r = null;
7318            for (i=0; i<N; i++) {
7319                PackageParser.Activity a = pkg.activities.get(i);
7320                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7321                        a.info.processName, pkg.applicationInfo.uid);
7322                mActivities.addActivity(a, "activity");
7323                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7324                    if (r == null) {
7325                        r = new StringBuilder(256);
7326                    } else {
7327                        r.append(' ');
7328                    }
7329                    r.append(a.info.name);
7330                }
7331            }
7332            if (r != null) {
7333                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7334            }
7335
7336            N = pkg.permissionGroups.size();
7337            r = null;
7338            for (i=0; i<N; i++) {
7339                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7340                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7341                if (cur == null) {
7342                    mPermissionGroups.put(pg.info.name, pg);
7343                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7344                        if (r == null) {
7345                            r = new StringBuilder(256);
7346                        } else {
7347                            r.append(' ');
7348                        }
7349                        r.append(pg.info.name);
7350                    }
7351                } else {
7352                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7353                            + pg.info.packageName + " ignored: original from "
7354                            + cur.info.packageName);
7355                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7356                        if (r == null) {
7357                            r = new StringBuilder(256);
7358                        } else {
7359                            r.append(' ');
7360                        }
7361                        r.append("DUP:");
7362                        r.append(pg.info.name);
7363                    }
7364                }
7365            }
7366            if (r != null) {
7367                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7368            }
7369
7370            N = pkg.permissions.size();
7371            r = null;
7372            for (i=0; i<N; i++) {
7373                PackageParser.Permission p = pkg.permissions.get(i);
7374
7375                // Assume by default that we did not install this permission into the system.
7376                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7377
7378                // Now that permission groups have a special meaning, we ignore permission
7379                // groups for legacy apps to prevent unexpected behavior. In particular,
7380                // permissions for one app being granted to someone just becuase they happen
7381                // to be in a group defined by another app (before this had no implications).
7382                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7383                    p.group = mPermissionGroups.get(p.info.group);
7384                    // Warn for a permission in an unknown group.
7385                    if (p.info.group != null && p.group == null) {
7386                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7387                                + p.info.packageName + " in an unknown group " + p.info.group);
7388                    }
7389                }
7390
7391                ArrayMap<String, BasePermission> permissionMap =
7392                        p.tree ? mSettings.mPermissionTrees
7393                                : mSettings.mPermissions;
7394                BasePermission bp = permissionMap.get(p.info.name);
7395
7396                // Allow system apps to redefine non-system permissions
7397                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7398                    final boolean currentOwnerIsSystem = (bp.perm != null
7399                            && isSystemApp(bp.perm.owner));
7400                    if (isSystemApp(p.owner)) {
7401                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7402                            // It's a built-in permission and no owner, take ownership now
7403                            bp.packageSetting = pkgSetting;
7404                            bp.perm = p;
7405                            bp.uid = pkg.applicationInfo.uid;
7406                            bp.sourcePackage = p.info.packageName;
7407                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7408                        } else if (!currentOwnerIsSystem) {
7409                            String msg = "New decl " + p.owner + " of permission  "
7410                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7411                            reportSettingsProblem(Log.WARN, msg);
7412                            bp = null;
7413                        }
7414                    }
7415                }
7416
7417                if (bp == null) {
7418                    bp = new BasePermission(p.info.name, p.info.packageName,
7419                            BasePermission.TYPE_NORMAL);
7420                    permissionMap.put(p.info.name, bp);
7421                }
7422
7423                if (bp.perm == null) {
7424                    if (bp.sourcePackage == null
7425                            || bp.sourcePackage.equals(p.info.packageName)) {
7426                        BasePermission tree = findPermissionTreeLP(p.info.name);
7427                        if (tree == null
7428                                || tree.sourcePackage.equals(p.info.packageName)) {
7429                            bp.packageSetting = pkgSetting;
7430                            bp.perm = p;
7431                            bp.uid = pkg.applicationInfo.uid;
7432                            bp.sourcePackage = p.info.packageName;
7433                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7434                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7435                                if (r == null) {
7436                                    r = new StringBuilder(256);
7437                                } else {
7438                                    r.append(' ');
7439                                }
7440                                r.append(p.info.name);
7441                            }
7442                        } else {
7443                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7444                                    + p.info.packageName + " ignored: base tree "
7445                                    + tree.name + " is from package "
7446                                    + tree.sourcePackage);
7447                        }
7448                    } else {
7449                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7450                                + p.info.packageName + " ignored: original from "
7451                                + bp.sourcePackage);
7452                    }
7453                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7454                    if (r == null) {
7455                        r = new StringBuilder(256);
7456                    } else {
7457                        r.append(' ');
7458                    }
7459                    r.append("DUP:");
7460                    r.append(p.info.name);
7461                }
7462                if (bp.perm == p) {
7463                    bp.protectionLevel = p.info.protectionLevel;
7464                }
7465            }
7466
7467            if (r != null) {
7468                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7469            }
7470
7471            N = pkg.instrumentation.size();
7472            r = null;
7473            for (i=0; i<N; i++) {
7474                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7475                a.info.packageName = pkg.applicationInfo.packageName;
7476                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7477                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7478                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7479                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7480                a.info.dataDir = pkg.applicationInfo.dataDir;
7481
7482                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7483                // need other information about the application, like the ABI and what not ?
7484                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7485                mInstrumentation.put(a.getComponentName(), a);
7486                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7487                    if (r == null) {
7488                        r = new StringBuilder(256);
7489                    } else {
7490                        r.append(' ');
7491                    }
7492                    r.append(a.info.name);
7493                }
7494            }
7495            if (r != null) {
7496                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7497            }
7498
7499            if (pkg.protectedBroadcasts != null) {
7500                N = pkg.protectedBroadcasts.size();
7501                for (i=0; i<N; i++) {
7502                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7503                }
7504            }
7505
7506            pkgSetting.setTimeStamp(scanFileTime);
7507
7508            // Create idmap files for pairs of (packages, overlay packages).
7509            // Note: "android", ie framework-res.apk, is handled by native layers.
7510            if (pkg.mOverlayTarget != null) {
7511                // This is an overlay package.
7512                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7513                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7514                        mOverlays.put(pkg.mOverlayTarget,
7515                                new ArrayMap<String, PackageParser.Package>());
7516                    }
7517                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7518                    map.put(pkg.packageName, pkg);
7519                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7520                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7521                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7522                                "scanPackageLI failed to createIdmap");
7523                    }
7524                }
7525            } else if (mOverlays.containsKey(pkg.packageName) &&
7526                    !pkg.packageName.equals("android")) {
7527                // This is a regular package, with one or more known overlay packages.
7528                createIdmapsForPackageLI(pkg);
7529            }
7530        }
7531
7532        return pkg;
7533    }
7534
7535    /**
7536     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7537     * is derived purely on the basis of the contents of {@code scanFile} and
7538     * {@code cpuAbiOverride}.
7539     *
7540     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7541     */
7542    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7543                                 String cpuAbiOverride, boolean extractLibs)
7544            throws PackageManagerException {
7545        // TODO: We can probably be smarter about this stuff. For installed apps,
7546        // we can calculate this information at install time once and for all. For
7547        // system apps, we can probably assume that this information doesn't change
7548        // after the first boot scan. As things stand, we do lots of unnecessary work.
7549
7550        // Give ourselves some initial paths; we'll come back for another
7551        // pass once we've determined ABI below.
7552        setNativeLibraryPaths(pkg);
7553
7554        // We would never need to extract libs for forward-locked and external packages,
7555        // since the container service will do it for us. We shouldn't attempt to
7556        // extract libs from system app when it was not updated.
7557        if (pkg.isForwardLocked() || isExternal(pkg) ||
7558            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7559            extractLibs = false;
7560        }
7561
7562        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7563        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7564
7565        NativeLibraryHelper.Handle handle = null;
7566        try {
7567            handle = NativeLibraryHelper.Handle.create(scanFile);
7568            // TODO(multiArch): This can be null for apps that didn't go through the
7569            // usual installation process. We can calculate it again, like we
7570            // do during install time.
7571            //
7572            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7573            // unnecessary.
7574            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7575
7576            // Null out the abis so that they can be recalculated.
7577            pkg.applicationInfo.primaryCpuAbi = null;
7578            pkg.applicationInfo.secondaryCpuAbi = null;
7579            if (isMultiArch(pkg.applicationInfo)) {
7580                // Warn if we've set an abiOverride for multi-lib packages..
7581                // By definition, we need to copy both 32 and 64 bit libraries for
7582                // such packages.
7583                if (pkg.cpuAbiOverride != null
7584                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7585                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7586                }
7587
7588                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7589                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7590                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7591                    if (extractLibs) {
7592                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7593                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7594                                useIsaSpecificSubdirs);
7595                    } else {
7596                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7597                    }
7598                }
7599
7600                maybeThrowExceptionForMultiArchCopy(
7601                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7602
7603                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7604                    if (extractLibs) {
7605                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7606                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7607                                useIsaSpecificSubdirs);
7608                    } else {
7609                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7610                    }
7611                }
7612
7613                maybeThrowExceptionForMultiArchCopy(
7614                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7615
7616                if (abi64 >= 0) {
7617                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7618                }
7619
7620                if (abi32 >= 0) {
7621                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7622                    if (abi64 >= 0) {
7623                        pkg.applicationInfo.secondaryCpuAbi = abi;
7624                    } else {
7625                        pkg.applicationInfo.primaryCpuAbi = abi;
7626                    }
7627                }
7628            } else {
7629                String[] abiList = (cpuAbiOverride != null) ?
7630                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7631
7632                // Enable gross and lame hacks for apps that are built with old
7633                // SDK tools. We must scan their APKs for renderscript bitcode and
7634                // not launch them if it's present. Don't bother checking on devices
7635                // that don't have 64 bit support.
7636                boolean needsRenderScriptOverride = false;
7637                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7638                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7639                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7640                    needsRenderScriptOverride = true;
7641                }
7642
7643                final int copyRet;
7644                if (extractLibs) {
7645                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7646                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7647                } else {
7648                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7649                }
7650
7651                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7652                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7653                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7654                }
7655
7656                if (copyRet >= 0) {
7657                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7658                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7659                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7660                } else if (needsRenderScriptOverride) {
7661                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7662                }
7663            }
7664        } catch (IOException ioe) {
7665            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7666        } finally {
7667            IoUtils.closeQuietly(handle);
7668        }
7669
7670        // Now that we've calculated the ABIs and determined if it's an internal app,
7671        // we will go ahead and populate the nativeLibraryPath.
7672        setNativeLibraryPaths(pkg);
7673    }
7674
7675    /**
7676     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7677     * i.e, so that all packages can be run inside a single process if required.
7678     *
7679     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7680     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7681     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7682     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7683     * updating a package that belongs to a shared user.
7684     *
7685     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7686     * adds unnecessary complexity.
7687     */
7688    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7689            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt,
7690            boolean bootComplete) {
7691        String requiredInstructionSet = null;
7692        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7693            requiredInstructionSet = VMRuntime.getInstructionSet(
7694                     scannedPackage.applicationInfo.primaryCpuAbi);
7695        }
7696
7697        PackageSetting requirer = null;
7698        for (PackageSetting ps : packagesForUser) {
7699            // If packagesForUser contains scannedPackage, we skip it. This will happen
7700            // when scannedPackage is an update of an existing package. Without this check,
7701            // we will never be able to change the ABI of any package belonging to a shared
7702            // user, even if it's compatible with other packages.
7703            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7704                if (ps.primaryCpuAbiString == null) {
7705                    continue;
7706                }
7707
7708                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7709                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7710                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7711                    // this but there's not much we can do.
7712                    String errorMessage = "Instruction set mismatch, "
7713                            + ((requirer == null) ? "[caller]" : requirer)
7714                            + " requires " + requiredInstructionSet + " whereas " + ps
7715                            + " requires " + instructionSet;
7716                    Slog.w(TAG, errorMessage);
7717                }
7718
7719                if (requiredInstructionSet == null) {
7720                    requiredInstructionSet = instructionSet;
7721                    requirer = ps;
7722                }
7723            }
7724        }
7725
7726        if (requiredInstructionSet != null) {
7727            String adjustedAbi;
7728            if (requirer != null) {
7729                // requirer != null implies that either scannedPackage was null or that scannedPackage
7730                // did not require an ABI, in which case we have to adjust scannedPackage to match
7731                // the ABI of the set (which is the same as requirer's ABI)
7732                adjustedAbi = requirer.primaryCpuAbiString;
7733                if (scannedPackage != null) {
7734                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7735                }
7736            } else {
7737                // requirer == null implies that we're updating all ABIs in the set to
7738                // match scannedPackage.
7739                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7740            }
7741
7742            for (PackageSetting ps : packagesForUser) {
7743                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7744                    if (ps.primaryCpuAbiString != null) {
7745                        continue;
7746                    }
7747
7748                    ps.primaryCpuAbiString = adjustedAbi;
7749                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7750                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7751                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7752
7753                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7754                                null /* instruction sets */, forceDexOpt, deferDexOpt, true,
7755                                bootComplete);
7756                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7757                            ps.primaryCpuAbiString = null;
7758                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7759                            return;
7760                        } else {
7761                            mInstaller.rmdex(ps.codePathString,
7762                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7763                        }
7764                    }
7765                }
7766            }
7767        }
7768    }
7769
7770    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7771        synchronized (mPackages) {
7772            mResolverReplaced = true;
7773            // Set up information for custom user intent resolution activity.
7774            mResolveActivity.applicationInfo = pkg.applicationInfo;
7775            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7776            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7777            mResolveActivity.processName = pkg.applicationInfo.packageName;
7778            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7779            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7780                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7781            mResolveActivity.theme = 0;
7782            mResolveActivity.exported = true;
7783            mResolveActivity.enabled = true;
7784            mResolveInfo.activityInfo = mResolveActivity;
7785            mResolveInfo.priority = 0;
7786            mResolveInfo.preferredOrder = 0;
7787            mResolveInfo.match = 0;
7788            mResolveComponentName = mCustomResolverComponentName;
7789            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7790                    mResolveComponentName);
7791        }
7792    }
7793
7794    private static String calculateBundledApkRoot(final String codePathString) {
7795        final File codePath = new File(codePathString);
7796        final File codeRoot;
7797        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7798            codeRoot = Environment.getRootDirectory();
7799        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7800            codeRoot = Environment.getOemDirectory();
7801        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7802            codeRoot = Environment.getVendorDirectory();
7803        } else {
7804            // Unrecognized code path; take its top real segment as the apk root:
7805            // e.g. /something/app/blah.apk => /something
7806            try {
7807                File f = codePath.getCanonicalFile();
7808                File parent = f.getParentFile();    // non-null because codePath is a file
7809                File tmp;
7810                while ((tmp = parent.getParentFile()) != null) {
7811                    f = parent;
7812                    parent = tmp;
7813                }
7814                codeRoot = f;
7815                Slog.w(TAG, "Unrecognized code path "
7816                        + codePath + " - using " + codeRoot);
7817            } catch (IOException e) {
7818                // Can't canonicalize the code path -- shenanigans?
7819                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7820                return Environment.getRootDirectory().getPath();
7821            }
7822        }
7823        return codeRoot.getPath();
7824    }
7825
7826    /**
7827     * Derive and set the location of native libraries for the given package,
7828     * which varies depending on where and how the package was installed.
7829     */
7830    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7831        final ApplicationInfo info = pkg.applicationInfo;
7832        final String codePath = pkg.codePath;
7833        final File codeFile = new File(codePath);
7834        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7835        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7836
7837        info.nativeLibraryRootDir = null;
7838        info.nativeLibraryRootRequiresIsa = false;
7839        info.nativeLibraryDir = null;
7840        info.secondaryNativeLibraryDir = null;
7841
7842        if (isApkFile(codeFile)) {
7843            // Monolithic install
7844            if (bundledApp) {
7845                // If "/system/lib64/apkname" exists, assume that is the per-package
7846                // native library directory to use; otherwise use "/system/lib/apkname".
7847                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7848                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7849                        getPrimaryInstructionSet(info));
7850
7851                // This is a bundled system app so choose the path based on the ABI.
7852                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7853                // is just the default path.
7854                final String apkName = deriveCodePathName(codePath);
7855                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7856                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7857                        apkName).getAbsolutePath();
7858
7859                if (info.secondaryCpuAbi != null) {
7860                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7861                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7862                            secondaryLibDir, apkName).getAbsolutePath();
7863                }
7864            } else if (asecApp) {
7865                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7866                        .getAbsolutePath();
7867            } else {
7868                final String apkName = deriveCodePathName(codePath);
7869                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7870                        .getAbsolutePath();
7871            }
7872
7873            info.nativeLibraryRootRequiresIsa = false;
7874            info.nativeLibraryDir = info.nativeLibraryRootDir;
7875        } else {
7876            // Cluster install
7877            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7878            info.nativeLibraryRootRequiresIsa = true;
7879
7880            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7881                    getPrimaryInstructionSet(info)).getAbsolutePath();
7882
7883            if (info.secondaryCpuAbi != null) {
7884                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7885                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7886            }
7887        }
7888    }
7889
7890    /**
7891     * Calculate the abis and roots for a bundled app. These can uniquely
7892     * be determined from the contents of the system partition, i.e whether
7893     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7894     * of this information, and instead assume that the system was built
7895     * sensibly.
7896     */
7897    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7898                                           PackageSetting pkgSetting) {
7899        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7900
7901        // If "/system/lib64/apkname" exists, assume that is the per-package
7902        // native library directory to use; otherwise use "/system/lib/apkname".
7903        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7904        setBundledAppAbi(pkg, apkRoot, apkName);
7905        // pkgSetting might be null during rescan following uninstall of updates
7906        // to a bundled app, so accommodate that possibility.  The settings in
7907        // that case will be established later from the parsed package.
7908        //
7909        // If the settings aren't null, sync them up with what we've just derived.
7910        // note that apkRoot isn't stored in the package settings.
7911        if (pkgSetting != null) {
7912            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7913            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7914        }
7915    }
7916
7917    /**
7918     * Deduces the ABI of a bundled app and sets the relevant fields on the
7919     * parsed pkg object.
7920     *
7921     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7922     *        under which system libraries are installed.
7923     * @param apkName the name of the installed package.
7924     */
7925    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7926        final File codeFile = new File(pkg.codePath);
7927
7928        final boolean has64BitLibs;
7929        final boolean has32BitLibs;
7930        if (isApkFile(codeFile)) {
7931            // Monolithic install
7932            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7933            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7934        } else {
7935            // Cluster install
7936            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7937            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7938                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7939                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7940                has64BitLibs = (new File(rootDir, isa)).exists();
7941            } else {
7942                has64BitLibs = false;
7943            }
7944            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7945                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7946                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7947                has32BitLibs = (new File(rootDir, isa)).exists();
7948            } else {
7949                has32BitLibs = false;
7950            }
7951        }
7952
7953        if (has64BitLibs && !has32BitLibs) {
7954            // The package has 64 bit libs, but not 32 bit libs. Its primary
7955            // ABI should be 64 bit. We can safely assume here that the bundled
7956            // native libraries correspond to the most preferred ABI in the list.
7957
7958            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7959            pkg.applicationInfo.secondaryCpuAbi = null;
7960        } else if (has32BitLibs && !has64BitLibs) {
7961            // The package has 32 bit libs but not 64 bit libs. Its primary
7962            // ABI should be 32 bit.
7963
7964            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7965            pkg.applicationInfo.secondaryCpuAbi = null;
7966        } else if (has32BitLibs && has64BitLibs) {
7967            // The application has both 64 and 32 bit bundled libraries. We check
7968            // here that the app declares multiArch support, and warn if it doesn't.
7969            //
7970            // We will be lenient here and record both ABIs. The primary will be the
7971            // ABI that's higher on the list, i.e, a device that's configured to prefer
7972            // 64 bit apps will see a 64 bit primary ABI,
7973
7974            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7975                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7976            }
7977
7978            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7979                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7980                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7981            } else {
7982                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7983                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7984            }
7985        } else {
7986            pkg.applicationInfo.primaryCpuAbi = null;
7987            pkg.applicationInfo.secondaryCpuAbi = null;
7988        }
7989    }
7990
7991    private void killApplication(String pkgName, int appId, String reason) {
7992        // Request the ActivityManager to kill the process(only for existing packages)
7993        // so that we do not end up in a confused state while the user is still using the older
7994        // version of the application while the new one gets installed.
7995        IActivityManager am = ActivityManagerNative.getDefault();
7996        if (am != null) {
7997            try {
7998                am.killApplicationWithAppId(pkgName, appId, reason);
7999            } catch (RemoteException e) {
8000            }
8001        }
8002    }
8003
8004    void removePackageLI(PackageSetting ps, boolean chatty) {
8005        if (DEBUG_INSTALL) {
8006            if (chatty)
8007                Log.d(TAG, "Removing package " + ps.name);
8008        }
8009
8010        // writer
8011        synchronized (mPackages) {
8012            mPackages.remove(ps.name);
8013            final PackageParser.Package pkg = ps.pkg;
8014            if (pkg != null) {
8015                cleanPackageDataStructuresLILPw(pkg, chatty);
8016            }
8017        }
8018    }
8019
8020    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8021        if (DEBUG_INSTALL) {
8022            if (chatty)
8023                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8024        }
8025
8026        // writer
8027        synchronized (mPackages) {
8028            mPackages.remove(pkg.applicationInfo.packageName);
8029            cleanPackageDataStructuresLILPw(pkg, chatty);
8030        }
8031    }
8032
8033    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8034        int N = pkg.providers.size();
8035        StringBuilder r = null;
8036        int i;
8037        for (i=0; i<N; i++) {
8038            PackageParser.Provider p = pkg.providers.get(i);
8039            mProviders.removeProvider(p);
8040            if (p.info.authority == null) {
8041
8042                /* There was another ContentProvider with this authority when
8043                 * this app was installed so this authority is null,
8044                 * Ignore it as we don't have to unregister the provider.
8045                 */
8046                continue;
8047            }
8048            String names[] = p.info.authority.split(";");
8049            for (int j = 0; j < names.length; j++) {
8050                if (mProvidersByAuthority.get(names[j]) == p) {
8051                    mProvidersByAuthority.remove(names[j]);
8052                    if (DEBUG_REMOVE) {
8053                        if (chatty)
8054                            Log.d(TAG, "Unregistered content provider: " + names[j]
8055                                    + ", className = " + p.info.name + ", isSyncable = "
8056                                    + p.info.isSyncable);
8057                    }
8058                }
8059            }
8060            if (DEBUG_REMOVE && chatty) {
8061                if (r == null) {
8062                    r = new StringBuilder(256);
8063                } else {
8064                    r.append(' ');
8065                }
8066                r.append(p.info.name);
8067            }
8068        }
8069        if (r != null) {
8070            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8071        }
8072
8073        N = pkg.services.size();
8074        r = null;
8075        for (i=0; i<N; i++) {
8076            PackageParser.Service s = pkg.services.get(i);
8077            mServices.removeService(s);
8078            if (chatty) {
8079                if (r == null) {
8080                    r = new StringBuilder(256);
8081                } else {
8082                    r.append(' ');
8083                }
8084                r.append(s.info.name);
8085            }
8086        }
8087        if (r != null) {
8088            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8089        }
8090
8091        N = pkg.receivers.size();
8092        r = null;
8093        for (i=0; i<N; i++) {
8094            PackageParser.Activity a = pkg.receivers.get(i);
8095            mReceivers.removeActivity(a, "receiver");
8096            if (DEBUG_REMOVE && chatty) {
8097                if (r == null) {
8098                    r = new StringBuilder(256);
8099                } else {
8100                    r.append(' ');
8101                }
8102                r.append(a.info.name);
8103            }
8104        }
8105        if (r != null) {
8106            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8107        }
8108
8109        N = pkg.activities.size();
8110        r = null;
8111        for (i=0; i<N; i++) {
8112            PackageParser.Activity a = pkg.activities.get(i);
8113            mActivities.removeActivity(a, "activity");
8114            if (DEBUG_REMOVE && chatty) {
8115                if (r == null) {
8116                    r = new StringBuilder(256);
8117                } else {
8118                    r.append(' ');
8119                }
8120                r.append(a.info.name);
8121            }
8122        }
8123        if (r != null) {
8124            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8125        }
8126
8127        N = pkg.permissions.size();
8128        r = null;
8129        for (i=0; i<N; i++) {
8130            PackageParser.Permission p = pkg.permissions.get(i);
8131            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8132            if (bp == null) {
8133                bp = mSettings.mPermissionTrees.get(p.info.name);
8134            }
8135            if (bp != null && bp.perm == p) {
8136                bp.perm = null;
8137                if (DEBUG_REMOVE && chatty) {
8138                    if (r == null) {
8139                        r = new StringBuilder(256);
8140                    } else {
8141                        r.append(' ');
8142                    }
8143                    r.append(p.info.name);
8144                }
8145            }
8146            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8147                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8148                if (appOpPerms != null) {
8149                    appOpPerms.remove(pkg.packageName);
8150                }
8151            }
8152        }
8153        if (r != null) {
8154            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8155        }
8156
8157        N = pkg.requestedPermissions.size();
8158        r = null;
8159        for (i=0; i<N; i++) {
8160            String perm = pkg.requestedPermissions.get(i);
8161            BasePermission bp = mSettings.mPermissions.get(perm);
8162            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8163                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8164                if (appOpPerms != null) {
8165                    appOpPerms.remove(pkg.packageName);
8166                    if (appOpPerms.isEmpty()) {
8167                        mAppOpPermissionPackages.remove(perm);
8168                    }
8169                }
8170            }
8171        }
8172        if (r != null) {
8173            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8174        }
8175
8176        N = pkg.instrumentation.size();
8177        r = null;
8178        for (i=0; i<N; i++) {
8179            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8180            mInstrumentation.remove(a.getComponentName());
8181            if (DEBUG_REMOVE && chatty) {
8182                if (r == null) {
8183                    r = new StringBuilder(256);
8184                } else {
8185                    r.append(' ');
8186                }
8187                r.append(a.info.name);
8188            }
8189        }
8190        if (r != null) {
8191            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8192        }
8193
8194        r = null;
8195        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8196            // Only system apps can hold shared libraries.
8197            if (pkg.libraryNames != null) {
8198                for (i=0; i<pkg.libraryNames.size(); i++) {
8199                    String name = pkg.libraryNames.get(i);
8200                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8201                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8202                        mSharedLibraries.remove(name);
8203                        if (DEBUG_REMOVE && chatty) {
8204                            if (r == null) {
8205                                r = new StringBuilder(256);
8206                            } else {
8207                                r.append(' ');
8208                            }
8209                            r.append(name);
8210                        }
8211                    }
8212                }
8213            }
8214        }
8215        if (r != null) {
8216            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8217        }
8218    }
8219
8220    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8221        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8222            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8223                return true;
8224            }
8225        }
8226        return false;
8227    }
8228
8229    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8230    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8231    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8232
8233    private void updatePermissionsLPw(String changingPkg,
8234            PackageParser.Package pkgInfo, int flags) {
8235        // Make sure there are no dangling permission trees.
8236        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8237        while (it.hasNext()) {
8238            final BasePermission bp = it.next();
8239            if (bp.packageSetting == null) {
8240                // We may not yet have parsed the package, so just see if
8241                // we still know about its settings.
8242                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8243            }
8244            if (bp.packageSetting == null) {
8245                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8246                        + " from package " + bp.sourcePackage);
8247                it.remove();
8248            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8249                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8250                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8251                            + " from package " + bp.sourcePackage);
8252                    flags |= UPDATE_PERMISSIONS_ALL;
8253                    it.remove();
8254                }
8255            }
8256        }
8257
8258        // Make sure all dynamic permissions have been assigned to a package,
8259        // and make sure there are no dangling permissions.
8260        it = mSettings.mPermissions.values().iterator();
8261        while (it.hasNext()) {
8262            final BasePermission bp = it.next();
8263            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8264                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8265                        + bp.name + " pkg=" + bp.sourcePackage
8266                        + " info=" + bp.pendingInfo);
8267                if (bp.packageSetting == null && bp.pendingInfo != null) {
8268                    final BasePermission tree = findPermissionTreeLP(bp.name);
8269                    if (tree != null && tree.perm != null) {
8270                        bp.packageSetting = tree.packageSetting;
8271                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8272                                new PermissionInfo(bp.pendingInfo));
8273                        bp.perm.info.packageName = tree.perm.info.packageName;
8274                        bp.perm.info.name = bp.name;
8275                        bp.uid = tree.uid;
8276                    }
8277                }
8278            }
8279            if (bp.packageSetting == null) {
8280                // We may not yet have parsed the package, so just see if
8281                // we still know about its settings.
8282                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8283            }
8284            if (bp.packageSetting == null) {
8285                Slog.w(TAG, "Removing dangling permission: " + bp.name
8286                        + " from package " + bp.sourcePackage);
8287                it.remove();
8288            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8289                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8290                    Slog.i(TAG, "Removing old permission: " + bp.name
8291                            + " from package " + bp.sourcePackage);
8292                    flags |= UPDATE_PERMISSIONS_ALL;
8293                    it.remove();
8294                }
8295            }
8296        }
8297
8298        // Now update the permissions for all packages, in particular
8299        // replace the granted permissions of the system packages.
8300        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8301            for (PackageParser.Package pkg : mPackages.values()) {
8302                if (pkg != pkgInfo) {
8303                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8304                            changingPkg);
8305                }
8306            }
8307        }
8308
8309        if (pkgInfo != null) {
8310            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8311        }
8312    }
8313
8314    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8315            String packageOfInterest) {
8316        // IMPORTANT: There are two types of permissions: install and runtime.
8317        // Install time permissions are granted when the app is installed to
8318        // all device users and users added in the future. Runtime permissions
8319        // are granted at runtime explicitly to specific users. Normal and signature
8320        // protected permissions are install time permissions. Dangerous permissions
8321        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8322        // otherwise they are runtime permissions. This function does not manage
8323        // runtime permissions except for the case an app targeting Lollipop MR1
8324        // being upgraded to target a newer SDK, in which case dangerous permissions
8325        // are transformed from install time to runtime ones.
8326
8327        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8328        if (ps == null) {
8329            return;
8330        }
8331
8332        PermissionsState permissionsState = ps.getPermissionsState();
8333        PermissionsState origPermissions = permissionsState;
8334
8335        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8336
8337        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8338
8339        boolean changedInstallPermission = false;
8340
8341        if (replace) {
8342            ps.installPermissionsFixed = false;
8343            if (!ps.isSharedUser()) {
8344                origPermissions = new PermissionsState(permissionsState);
8345                permissionsState.reset();
8346            }
8347        }
8348
8349        permissionsState.setGlobalGids(mGlobalGids);
8350
8351        final int N = pkg.requestedPermissions.size();
8352        for (int i=0; i<N; i++) {
8353            final String name = pkg.requestedPermissions.get(i);
8354            final BasePermission bp = mSettings.mPermissions.get(name);
8355
8356            if (DEBUG_INSTALL) {
8357                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8358            }
8359
8360            if (bp == null || bp.packageSetting == null) {
8361                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8362                    Slog.w(TAG, "Unknown permission " + name
8363                            + " in package " + pkg.packageName);
8364                }
8365                continue;
8366            }
8367
8368            final String perm = bp.name;
8369            boolean allowedSig = false;
8370            int grant = GRANT_DENIED;
8371
8372            // Keep track of app op permissions.
8373            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8374                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8375                if (pkgs == null) {
8376                    pkgs = new ArraySet<>();
8377                    mAppOpPermissionPackages.put(bp.name, pkgs);
8378                }
8379                pkgs.add(pkg.packageName);
8380            }
8381
8382            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8383            switch (level) {
8384                case PermissionInfo.PROTECTION_NORMAL: {
8385                    // For all apps normal permissions are install time ones.
8386                    grant = GRANT_INSTALL;
8387                } break;
8388
8389                case PermissionInfo.PROTECTION_DANGEROUS: {
8390                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8391                        // For legacy apps dangerous permissions are install time ones.
8392                        grant = GRANT_INSTALL_LEGACY;
8393                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8394                        // For legacy apps that became modern, install becomes runtime.
8395                        grant = GRANT_UPGRADE;
8396                    } else if (mPromoteSystemApps
8397                            && isSystemApp(ps)
8398                            && mExistingSystemPackages.contains(ps.name)) {
8399                        // For legacy system apps, install becomes runtime.
8400                        // We cannot check hasInstallPermission() for system apps since those
8401                        // permissions were granted implicitly and not persisted pre-M.
8402                        grant = GRANT_UPGRADE;
8403                    } else {
8404                        // For modern apps keep runtime permissions unchanged.
8405                        grant = GRANT_RUNTIME;
8406                    }
8407                } break;
8408
8409                case PermissionInfo.PROTECTION_SIGNATURE: {
8410                    // For all apps signature permissions are install time ones.
8411                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8412                    if (allowedSig) {
8413                        grant = GRANT_INSTALL;
8414                    }
8415                } break;
8416            }
8417
8418            if (DEBUG_INSTALL) {
8419                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8420            }
8421
8422            if (grant != GRANT_DENIED) {
8423                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8424                    // If this is an existing, non-system package, then
8425                    // we can't add any new permissions to it.
8426                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8427                        // Except...  if this is a permission that was added
8428                        // to the platform (note: need to only do this when
8429                        // updating the platform).
8430                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8431                            grant = GRANT_DENIED;
8432                        }
8433                    }
8434                }
8435
8436                switch (grant) {
8437                    case GRANT_INSTALL: {
8438                        // Revoke this as runtime permission to handle the case of
8439                        // a runtime permission being downgraded to an install one.
8440                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8441                            if (origPermissions.getRuntimePermissionState(
8442                                    bp.name, userId) != null) {
8443                                // Revoke the runtime permission and clear the flags.
8444                                origPermissions.revokeRuntimePermission(bp, userId);
8445                                origPermissions.updatePermissionFlags(bp, userId,
8446                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8447                                // If we revoked a permission permission, we have to write.
8448                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8449                                        changedRuntimePermissionUserIds, userId);
8450                            }
8451                        }
8452                        // Grant an install permission.
8453                        if (permissionsState.grantInstallPermission(bp) !=
8454                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8455                            changedInstallPermission = true;
8456                        }
8457                    } break;
8458
8459                    case GRANT_INSTALL_LEGACY: {
8460                        // Grant an install permission.
8461                        if (permissionsState.grantInstallPermission(bp) !=
8462                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8463                            changedInstallPermission = true;
8464                        }
8465                    } break;
8466
8467                    case GRANT_RUNTIME: {
8468                        // Grant previously granted runtime permissions.
8469                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8470                            PermissionState permissionState = origPermissions
8471                                    .getRuntimePermissionState(bp.name, userId);
8472                            final int flags = permissionState != null
8473                                    ? permissionState.getFlags() : 0;
8474                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8475                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8476                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8477                                    // If we cannot put the permission as it was, we have to write.
8478                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8479                                            changedRuntimePermissionUserIds, userId);
8480                                }
8481                            }
8482                            // Propagate the permission flags.
8483                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8484                        }
8485                    } break;
8486
8487                    case GRANT_UPGRADE: {
8488                        // Grant runtime permissions for a previously held install permission.
8489                        PermissionState permissionState = origPermissions
8490                                .getInstallPermissionState(bp.name);
8491                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8492
8493                        if (origPermissions.revokeInstallPermission(bp)
8494                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8495                            // We will be transferring the permission flags, so clear them.
8496                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8497                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8498                            changedInstallPermission = true;
8499                        }
8500
8501                        // If the permission is not to be promoted to runtime we ignore it and
8502                        // also its other flags as they are not applicable to install permissions.
8503                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8504                            for (int userId : currentUserIds) {
8505                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8506                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8507                                    // Transfer the permission flags.
8508                                    permissionsState.updatePermissionFlags(bp, userId,
8509                                            flags, flags);
8510                                    // If we granted the permission, we have to write.
8511                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8512                                            changedRuntimePermissionUserIds, userId);
8513                                }
8514                            }
8515                        }
8516                    } break;
8517
8518                    default: {
8519                        if (packageOfInterest == null
8520                                || packageOfInterest.equals(pkg.packageName)) {
8521                            Slog.w(TAG, "Not granting permission " + perm
8522                                    + " to package " + pkg.packageName
8523                                    + " because it was previously installed without");
8524                        }
8525                    } break;
8526                }
8527            } else {
8528                if (permissionsState.revokeInstallPermission(bp) !=
8529                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8530                    // Also drop the permission flags.
8531                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8532                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8533                    changedInstallPermission = true;
8534                    Slog.i(TAG, "Un-granting permission " + perm
8535                            + " from package " + pkg.packageName
8536                            + " (protectionLevel=" + bp.protectionLevel
8537                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8538                            + ")");
8539                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8540                    // Don't print warning for app op permissions, since it is fine for them
8541                    // not to be granted, there is a UI for the user to decide.
8542                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8543                        Slog.w(TAG, "Not granting permission " + perm
8544                                + " to package " + pkg.packageName
8545                                + " (protectionLevel=" + bp.protectionLevel
8546                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8547                                + ")");
8548                    }
8549                }
8550            }
8551        }
8552
8553        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8554                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8555            // This is the first that we have heard about this package, so the
8556            // permissions we have now selected are fixed until explicitly
8557            // changed.
8558            ps.installPermissionsFixed = true;
8559        }
8560
8561        // Persist the runtime permissions state for users with changes.
8562        for (int userId : changedRuntimePermissionUserIds) {
8563            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8564        }
8565    }
8566
8567    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8568        boolean allowed = false;
8569        final int NP = PackageParser.NEW_PERMISSIONS.length;
8570        for (int ip=0; ip<NP; ip++) {
8571            final PackageParser.NewPermissionInfo npi
8572                    = PackageParser.NEW_PERMISSIONS[ip];
8573            if (npi.name.equals(perm)
8574                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8575                allowed = true;
8576                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8577                        + pkg.packageName);
8578                break;
8579            }
8580        }
8581        return allowed;
8582    }
8583
8584    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8585            BasePermission bp, PermissionsState origPermissions) {
8586        boolean allowed;
8587        allowed = (compareSignatures(
8588                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8589                        == PackageManager.SIGNATURE_MATCH)
8590                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8591                        == PackageManager.SIGNATURE_MATCH);
8592        if (!allowed && (bp.protectionLevel
8593                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8594            if (isSystemApp(pkg)) {
8595                // For updated system applications, a system permission
8596                // is granted only if it had been defined by the original application.
8597                if (pkg.isUpdatedSystemApp()) {
8598                    final PackageSetting sysPs = mSettings
8599                            .getDisabledSystemPkgLPr(pkg.packageName);
8600                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8601                        // If the original was granted this permission, we take
8602                        // that grant decision as read and propagate it to the
8603                        // update.
8604                        if (sysPs.isPrivileged()) {
8605                            allowed = true;
8606                        }
8607                    } else {
8608                        // The system apk may have been updated with an older
8609                        // version of the one on the data partition, but which
8610                        // granted a new system permission that it didn't have
8611                        // before.  In this case we do want to allow the app to
8612                        // now get the new permission if the ancestral apk is
8613                        // privileged to get it.
8614                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8615                            for (int j=0;
8616                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8617                                if (perm.equals(
8618                                        sysPs.pkg.requestedPermissions.get(j))) {
8619                                    allowed = true;
8620                                    break;
8621                                }
8622                            }
8623                        }
8624                    }
8625                } else {
8626                    allowed = isPrivilegedApp(pkg);
8627                }
8628            }
8629        }
8630        if (!allowed) {
8631            if (!allowed && (bp.protectionLevel
8632                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8633                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8634                // If this was a previously normal/dangerous permission that got moved
8635                // to a system permission as part of the runtime permission redesign, then
8636                // we still want to blindly grant it to old apps.
8637                allowed = true;
8638            }
8639            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8640                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8641                // If this permission is to be granted to the system installer and
8642                // this app is an installer, then it gets the permission.
8643                allowed = true;
8644            }
8645            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8646                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8647                // If this permission is to be granted to the system verifier and
8648                // this app is a verifier, then it gets the permission.
8649                allowed = true;
8650            }
8651            if (!allowed && (bp.protectionLevel
8652                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8653                    && isSystemApp(pkg)) {
8654                // Any pre-installed system app is allowed to get this permission.
8655                allowed = true;
8656            }
8657            if (!allowed && (bp.protectionLevel
8658                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8659                // For development permissions, a development permission
8660                // is granted only if it was already granted.
8661                allowed = origPermissions.hasInstallPermission(perm);
8662            }
8663        }
8664        return allowed;
8665    }
8666
8667    final class ActivityIntentResolver
8668            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8669        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8670                boolean defaultOnly, int userId) {
8671            if (!sUserManager.exists(userId)) return null;
8672            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8673            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8674        }
8675
8676        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8677                int userId) {
8678            if (!sUserManager.exists(userId)) return null;
8679            mFlags = flags;
8680            return super.queryIntent(intent, resolvedType,
8681                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8682        }
8683
8684        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8685                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8686            if (!sUserManager.exists(userId)) return null;
8687            if (packageActivities == null) {
8688                return null;
8689            }
8690            mFlags = flags;
8691            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8692            final int N = packageActivities.size();
8693            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8694                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8695
8696            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8697            for (int i = 0; i < N; ++i) {
8698                intentFilters = packageActivities.get(i).intents;
8699                if (intentFilters != null && intentFilters.size() > 0) {
8700                    PackageParser.ActivityIntentInfo[] array =
8701                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8702                    intentFilters.toArray(array);
8703                    listCut.add(array);
8704                }
8705            }
8706            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8707        }
8708
8709        public final void addActivity(PackageParser.Activity a, String type) {
8710            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8711            mActivities.put(a.getComponentName(), a);
8712            if (DEBUG_SHOW_INFO)
8713                Log.v(
8714                TAG, "  " + type + " " +
8715                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8716            if (DEBUG_SHOW_INFO)
8717                Log.v(TAG, "    Class=" + a.info.name);
8718            final int NI = a.intents.size();
8719            for (int j=0; j<NI; j++) {
8720                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8721                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8722                    intent.setPriority(0);
8723                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8724                            + a.className + " with priority > 0, forcing to 0");
8725                }
8726                if (DEBUG_SHOW_INFO) {
8727                    Log.v(TAG, "    IntentFilter:");
8728                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8729                }
8730                if (!intent.debugCheck()) {
8731                    Log.w(TAG, "==> For Activity " + a.info.name);
8732                }
8733                addFilter(intent);
8734            }
8735        }
8736
8737        public final void removeActivity(PackageParser.Activity a, String type) {
8738            mActivities.remove(a.getComponentName());
8739            if (DEBUG_SHOW_INFO) {
8740                Log.v(TAG, "  " + type + " "
8741                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8742                                : a.info.name) + ":");
8743                Log.v(TAG, "    Class=" + a.info.name);
8744            }
8745            final int NI = a.intents.size();
8746            for (int j=0; j<NI; j++) {
8747                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8748                if (DEBUG_SHOW_INFO) {
8749                    Log.v(TAG, "    IntentFilter:");
8750                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8751                }
8752                removeFilter(intent);
8753            }
8754        }
8755
8756        @Override
8757        protected boolean allowFilterResult(
8758                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8759            ActivityInfo filterAi = filter.activity.info;
8760            for (int i=dest.size()-1; i>=0; i--) {
8761                ActivityInfo destAi = dest.get(i).activityInfo;
8762                if (destAi.name == filterAi.name
8763                        && destAi.packageName == filterAi.packageName) {
8764                    return false;
8765                }
8766            }
8767            return true;
8768        }
8769
8770        @Override
8771        protected ActivityIntentInfo[] newArray(int size) {
8772            return new ActivityIntentInfo[size];
8773        }
8774
8775        @Override
8776        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8777            if (!sUserManager.exists(userId)) return true;
8778            PackageParser.Package p = filter.activity.owner;
8779            if (p != null) {
8780                PackageSetting ps = (PackageSetting)p.mExtras;
8781                if (ps != null) {
8782                    // System apps are never considered stopped for purposes of
8783                    // filtering, because there may be no way for the user to
8784                    // actually re-launch them.
8785                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8786                            && ps.getStopped(userId);
8787                }
8788            }
8789            return false;
8790        }
8791
8792        @Override
8793        protected boolean isPackageForFilter(String packageName,
8794                PackageParser.ActivityIntentInfo info) {
8795            return packageName.equals(info.activity.owner.packageName);
8796        }
8797
8798        @Override
8799        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8800                int match, int userId) {
8801            if (!sUserManager.exists(userId)) return null;
8802            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8803                return null;
8804            }
8805            final PackageParser.Activity activity = info.activity;
8806            if (mSafeMode && (activity.info.applicationInfo.flags
8807                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8808                return null;
8809            }
8810            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8811            if (ps == null) {
8812                return null;
8813            }
8814            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8815                    ps.readUserState(userId), userId);
8816            if (ai == null) {
8817                return null;
8818            }
8819            final ResolveInfo res = new ResolveInfo();
8820            res.activityInfo = ai;
8821            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8822                res.filter = info;
8823            }
8824            if (info != null) {
8825                res.handleAllWebDataURI = info.handleAllWebDataURI();
8826            }
8827            res.priority = info.getPriority();
8828            res.preferredOrder = activity.owner.mPreferredOrder;
8829            //System.out.println("Result: " + res.activityInfo.className +
8830            //                   " = " + res.priority);
8831            res.match = match;
8832            res.isDefault = info.hasDefault;
8833            res.labelRes = info.labelRes;
8834            res.nonLocalizedLabel = info.nonLocalizedLabel;
8835            if (userNeedsBadging(userId)) {
8836                res.noResourceId = true;
8837            } else {
8838                res.icon = info.icon;
8839            }
8840            res.iconResourceId = info.icon;
8841            res.system = res.activityInfo.applicationInfo.isSystemApp();
8842            return res;
8843        }
8844
8845        @Override
8846        protected void sortResults(List<ResolveInfo> results) {
8847            Collections.sort(results, mResolvePrioritySorter);
8848        }
8849
8850        @Override
8851        protected void dumpFilter(PrintWriter out, String prefix,
8852                PackageParser.ActivityIntentInfo filter) {
8853            out.print(prefix); out.print(
8854                    Integer.toHexString(System.identityHashCode(filter.activity)));
8855                    out.print(' ');
8856                    filter.activity.printComponentShortName(out);
8857                    out.print(" filter ");
8858                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8859        }
8860
8861        @Override
8862        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8863            return filter.activity;
8864        }
8865
8866        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8867            PackageParser.Activity activity = (PackageParser.Activity)label;
8868            out.print(prefix); out.print(
8869                    Integer.toHexString(System.identityHashCode(activity)));
8870                    out.print(' ');
8871                    activity.printComponentShortName(out);
8872            if (count > 1) {
8873                out.print(" ("); out.print(count); out.print(" filters)");
8874            }
8875            out.println();
8876        }
8877
8878//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8879//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8880//            final List<ResolveInfo> retList = Lists.newArrayList();
8881//            while (i.hasNext()) {
8882//                final ResolveInfo resolveInfo = i.next();
8883//                if (isEnabledLP(resolveInfo.activityInfo)) {
8884//                    retList.add(resolveInfo);
8885//                }
8886//            }
8887//            return retList;
8888//        }
8889
8890        // Keys are String (activity class name), values are Activity.
8891        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8892                = new ArrayMap<ComponentName, PackageParser.Activity>();
8893        private int mFlags;
8894    }
8895
8896    private final class ServiceIntentResolver
8897            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8898        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8899                boolean defaultOnly, int userId) {
8900            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8901            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8902        }
8903
8904        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8905                int userId) {
8906            if (!sUserManager.exists(userId)) return null;
8907            mFlags = flags;
8908            return super.queryIntent(intent, resolvedType,
8909                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8910        }
8911
8912        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8913                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8914            if (!sUserManager.exists(userId)) return null;
8915            if (packageServices == null) {
8916                return null;
8917            }
8918            mFlags = flags;
8919            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8920            final int N = packageServices.size();
8921            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8922                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8923
8924            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8925            for (int i = 0; i < N; ++i) {
8926                intentFilters = packageServices.get(i).intents;
8927                if (intentFilters != null && intentFilters.size() > 0) {
8928                    PackageParser.ServiceIntentInfo[] array =
8929                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8930                    intentFilters.toArray(array);
8931                    listCut.add(array);
8932                }
8933            }
8934            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8935        }
8936
8937        public final void addService(PackageParser.Service s) {
8938            mServices.put(s.getComponentName(), s);
8939            if (DEBUG_SHOW_INFO) {
8940                Log.v(TAG, "  "
8941                        + (s.info.nonLocalizedLabel != null
8942                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8943                Log.v(TAG, "    Class=" + s.info.name);
8944            }
8945            final int NI = s.intents.size();
8946            int j;
8947            for (j=0; j<NI; j++) {
8948                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8949                if (DEBUG_SHOW_INFO) {
8950                    Log.v(TAG, "    IntentFilter:");
8951                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8952                }
8953                if (!intent.debugCheck()) {
8954                    Log.w(TAG, "==> For Service " + s.info.name);
8955                }
8956                addFilter(intent);
8957            }
8958        }
8959
8960        public final void removeService(PackageParser.Service s) {
8961            mServices.remove(s.getComponentName());
8962            if (DEBUG_SHOW_INFO) {
8963                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8964                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8965                Log.v(TAG, "    Class=" + s.info.name);
8966            }
8967            final int NI = s.intents.size();
8968            int j;
8969            for (j=0; j<NI; j++) {
8970                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8971                if (DEBUG_SHOW_INFO) {
8972                    Log.v(TAG, "    IntentFilter:");
8973                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8974                }
8975                removeFilter(intent);
8976            }
8977        }
8978
8979        @Override
8980        protected boolean allowFilterResult(
8981                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8982            ServiceInfo filterSi = filter.service.info;
8983            for (int i=dest.size()-1; i>=0; i--) {
8984                ServiceInfo destAi = dest.get(i).serviceInfo;
8985                if (destAi.name == filterSi.name
8986                        && destAi.packageName == filterSi.packageName) {
8987                    return false;
8988                }
8989            }
8990            return true;
8991        }
8992
8993        @Override
8994        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8995            return new PackageParser.ServiceIntentInfo[size];
8996        }
8997
8998        @Override
8999        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9000            if (!sUserManager.exists(userId)) return true;
9001            PackageParser.Package p = filter.service.owner;
9002            if (p != null) {
9003                PackageSetting ps = (PackageSetting)p.mExtras;
9004                if (ps != null) {
9005                    // System apps are never considered stopped for purposes of
9006                    // filtering, because there may be no way for the user to
9007                    // actually re-launch them.
9008                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9009                            && ps.getStopped(userId);
9010                }
9011            }
9012            return false;
9013        }
9014
9015        @Override
9016        protected boolean isPackageForFilter(String packageName,
9017                PackageParser.ServiceIntentInfo info) {
9018            return packageName.equals(info.service.owner.packageName);
9019        }
9020
9021        @Override
9022        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9023                int match, int userId) {
9024            if (!sUserManager.exists(userId)) return null;
9025            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9026            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9027                return null;
9028            }
9029            final PackageParser.Service service = info.service;
9030            if (mSafeMode && (service.info.applicationInfo.flags
9031                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9032                return null;
9033            }
9034            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9035            if (ps == null) {
9036                return null;
9037            }
9038            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9039                    ps.readUserState(userId), userId);
9040            if (si == null) {
9041                return null;
9042            }
9043            final ResolveInfo res = new ResolveInfo();
9044            res.serviceInfo = si;
9045            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9046                res.filter = filter;
9047            }
9048            res.priority = info.getPriority();
9049            res.preferredOrder = service.owner.mPreferredOrder;
9050            res.match = match;
9051            res.isDefault = info.hasDefault;
9052            res.labelRes = info.labelRes;
9053            res.nonLocalizedLabel = info.nonLocalizedLabel;
9054            res.icon = info.icon;
9055            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9056            return res;
9057        }
9058
9059        @Override
9060        protected void sortResults(List<ResolveInfo> results) {
9061            Collections.sort(results, mResolvePrioritySorter);
9062        }
9063
9064        @Override
9065        protected void dumpFilter(PrintWriter out, String prefix,
9066                PackageParser.ServiceIntentInfo filter) {
9067            out.print(prefix); out.print(
9068                    Integer.toHexString(System.identityHashCode(filter.service)));
9069                    out.print(' ');
9070                    filter.service.printComponentShortName(out);
9071                    out.print(" filter ");
9072                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9073        }
9074
9075        @Override
9076        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9077            return filter.service;
9078        }
9079
9080        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9081            PackageParser.Service service = (PackageParser.Service)label;
9082            out.print(prefix); out.print(
9083                    Integer.toHexString(System.identityHashCode(service)));
9084                    out.print(' ');
9085                    service.printComponentShortName(out);
9086            if (count > 1) {
9087                out.print(" ("); out.print(count); out.print(" filters)");
9088            }
9089            out.println();
9090        }
9091
9092//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9093//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9094//            final List<ResolveInfo> retList = Lists.newArrayList();
9095//            while (i.hasNext()) {
9096//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9097//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9098//                    retList.add(resolveInfo);
9099//                }
9100//            }
9101//            return retList;
9102//        }
9103
9104        // Keys are String (activity class name), values are Activity.
9105        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9106                = new ArrayMap<ComponentName, PackageParser.Service>();
9107        private int mFlags;
9108    };
9109
9110    private final class ProviderIntentResolver
9111            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9112        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9113                boolean defaultOnly, int userId) {
9114            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9115            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9116        }
9117
9118        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9119                int userId) {
9120            if (!sUserManager.exists(userId))
9121                return null;
9122            mFlags = flags;
9123            return super.queryIntent(intent, resolvedType,
9124                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9125        }
9126
9127        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9128                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9129            if (!sUserManager.exists(userId))
9130                return null;
9131            if (packageProviders == null) {
9132                return null;
9133            }
9134            mFlags = flags;
9135            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9136            final int N = packageProviders.size();
9137            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9138                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9139
9140            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9141            for (int i = 0; i < N; ++i) {
9142                intentFilters = packageProviders.get(i).intents;
9143                if (intentFilters != null && intentFilters.size() > 0) {
9144                    PackageParser.ProviderIntentInfo[] array =
9145                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9146                    intentFilters.toArray(array);
9147                    listCut.add(array);
9148                }
9149            }
9150            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9151        }
9152
9153        public final void addProvider(PackageParser.Provider p) {
9154            if (mProviders.containsKey(p.getComponentName())) {
9155                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9156                return;
9157            }
9158
9159            mProviders.put(p.getComponentName(), p);
9160            if (DEBUG_SHOW_INFO) {
9161                Log.v(TAG, "  "
9162                        + (p.info.nonLocalizedLabel != null
9163                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9164                Log.v(TAG, "    Class=" + p.info.name);
9165            }
9166            final int NI = p.intents.size();
9167            int j;
9168            for (j = 0; j < NI; j++) {
9169                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9170                if (DEBUG_SHOW_INFO) {
9171                    Log.v(TAG, "    IntentFilter:");
9172                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9173                }
9174                if (!intent.debugCheck()) {
9175                    Log.w(TAG, "==> For Provider " + p.info.name);
9176                }
9177                addFilter(intent);
9178            }
9179        }
9180
9181        public final void removeProvider(PackageParser.Provider p) {
9182            mProviders.remove(p.getComponentName());
9183            if (DEBUG_SHOW_INFO) {
9184                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9185                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9186                Log.v(TAG, "    Class=" + p.info.name);
9187            }
9188            final int NI = p.intents.size();
9189            int j;
9190            for (j = 0; j < NI; j++) {
9191                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9192                if (DEBUG_SHOW_INFO) {
9193                    Log.v(TAG, "    IntentFilter:");
9194                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9195                }
9196                removeFilter(intent);
9197            }
9198        }
9199
9200        @Override
9201        protected boolean allowFilterResult(
9202                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9203            ProviderInfo filterPi = filter.provider.info;
9204            for (int i = dest.size() - 1; i >= 0; i--) {
9205                ProviderInfo destPi = dest.get(i).providerInfo;
9206                if (destPi.name == filterPi.name
9207                        && destPi.packageName == filterPi.packageName) {
9208                    return false;
9209                }
9210            }
9211            return true;
9212        }
9213
9214        @Override
9215        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9216            return new PackageParser.ProviderIntentInfo[size];
9217        }
9218
9219        @Override
9220        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9221            if (!sUserManager.exists(userId))
9222                return true;
9223            PackageParser.Package p = filter.provider.owner;
9224            if (p != null) {
9225                PackageSetting ps = (PackageSetting) p.mExtras;
9226                if (ps != null) {
9227                    // System apps are never considered stopped for purposes of
9228                    // filtering, because there may be no way for the user to
9229                    // actually re-launch them.
9230                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9231                            && ps.getStopped(userId);
9232                }
9233            }
9234            return false;
9235        }
9236
9237        @Override
9238        protected boolean isPackageForFilter(String packageName,
9239                PackageParser.ProviderIntentInfo info) {
9240            return packageName.equals(info.provider.owner.packageName);
9241        }
9242
9243        @Override
9244        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9245                int match, int userId) {
9246            if (!sUserManager.exists(userId))
9247                return null;
9248            final PackageParser.ProviderIntentInfo info = filter;
9249            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9250                return null;
9251            }
9252            final PackageParser.Provider provider = info.provider;
9253            if (mSafeMode && (provider.info.applicationInfo.flags
9254                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9255                return null;
9256            }
9257            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9258            if (ps == null) {
9259                return null;
9260            }
9261            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9262                    ps.readUserState(userId), userId);
9263            if (pi == null) {
9264                return null;
9265            }
9266            final ResolveInfo res = new ResolveInfo();
9267            res.providerInfo = pi;
9268            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9269                res.filter = filter;
9270            }
9271            res.priority = info.getPriority();
9272            res.preferredOrder = provider.owner.mPreferredOrder;
9273            res.match = match;
9274            res.isDefault = info.hasDefault;
9275            res.labelRes = info.labelRes;
9276            res.nonLocalizedLabel = info.nonLocalizedLabel;
9277            res.icon = info.icon;
9278            res.system = res.providerInfo.applicationInfo.isSystemApp();
9279            return res;
9280        }
9281
9282        @Override
9283        protected void sortResults(List<ResolveInfo> results) {
9284            Collections.sort(results, mResolvePrioritySorter);
9285        }
9286
9287        @Override
9288        protected void dumpFilter(PrintWriter out, String prefix,
9289                PackageParser.ProviderIntentInfo filter) {
9290            out.print(prefix);
9291            out.print(
9292                    Integer.toHexString(System.identityHashCode(filter.provider)));
9293            out.print(' ');
9294            filter.provider.printComponentShortName(out);
9295            out.print(" filter ");
9296            out.println(Integer.toHexString(System.identityHashCode(filter)));
9297        }
9298
9299        @Override
9300        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9301            return filter.provider;
9302        }
9303
9304        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9305            PackageParser.Provider provider = (PackageParser.Provider)label;
9306            out.print(prefix); out.print(
9307                    Integer.toHexString(System.identityHashCode(provider)));
9308                    out.print(' ');
9309                    provider.printComponentShortName(out);
9310            if (count > 1) {
9311                out.print(" ("); out.print(count); out.print(" filters)");
9312            }
9313            out.println();
9314        }
9315
9316        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9317                = new ArrayMap<ComponentName, PackageParser.Provider>();
9318        private int mFlags;
9319    };
9320
9321    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9322            new Comparator<ResolveInfo>() {
9323        public int compare(ResolveInfo r1, ResolveInfo r2) {
9324            int v1 = r1.priority;
9325            int v2 = r2.priority;
9326            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9327            if (v1 != v2) {
9328                return (v1 > v2) ? -1 : 1;
9329            }
9330            v1 = r1.preferredOrder;
9331            v2 = r2.preferredOrder;
9332            if (v1 != v2) {
9333                return (v1 > v2) ? -1 : 1;
9334            }
9335            if (r1.isDefault != r2.isDefault) {
9336                return r1.isDefault ? -1 : 1;
9337            }
9338            v1 = r1.match;
9339            v2 = r2.match;
9340            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9341            if (v1 != v2) {
9342                return (v1 > v2) ? -1 : 1;
9343            }
9344            if (r1.system != r2.system) {
9345                return r1.system ? -1 : 1;
9346            }
9347            return 0;
9348        }
9349    };
9350
9351    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9352            new Comparator<ProviderInfo>() {
9353        public int compare(ProviderInfo p1, ProviderInfo p2) {
9354            final int v1 = p1.initOrder;
9355            final int v2 = p2.initOrder;
9356            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9357        }
9358    };
9359
9360    final void sendPackageBroadcast(final String action, final String pkg,
9361            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9362            final int[] userIds) {
9363        mHandler.post(new Runnable() {
9364            @Override
9365            public void run() {
9366                try {
9367                    final IActivityManager am = ActivityManagerNative.getDefault();
9368                    if (am == null) return;
9369                    final int[] resolvedUserIds;
9370                    if (userIds == null) {
9371                        resolvedUserIds = am.getRunningUserIds();
9372                    } else {
9373                        resolvedUserIds = userIds;
9374                    }
9375                    for (int id : resolvedUserIds) {
9376                        final Intent intent = new Intent(action,
9377                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9378                        if (extras != null) {
9379                            intent.putExtras(extras);
9380                        }
9381                        if (targetPkg != null) {
9382                            intent.setPackage(targetPkg);
9383                        }
9384                        // Modify the UID when posting to other users
9385                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9386                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9387                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9388                            intent.putExtra(Intent.EXTRA_UID, uid);
9389                        }
9390                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9391                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9392                        if (DEBUG_BROADCASTS) {
9393                            RuntimeException here = new RuntimeException("here");
9394                            here.fillInStackTrace();
9395                            Slog.d(TAG, "Sending to user " + id + ": "
9396                                    + intent.toShortString(false, true, false, false)
9397                                    + " " + intent.getExtras(), here);
9398                        }
9399                        am.broadcastIntent(null, intent, null, finishedReceiver,
9400                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9401                                null, finishedReceiver != null, false, id);
9402                    }
9403                } catch (RemoteException ex) {
9404                }
9405            }
9406        });
9407    }
9408
9409    /**
9410     * Check if the external storage media is available. This is true if there
9411     * is a mounted external storage medium or if the external storage is
9412     * emulated.
9413     */
9414    private boolean isExternalMediaAvailable() {
9415        return mMediaMounted || Environment.isExternalStorageEmulated();
9416    }
9417
9418    @Override
9419    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9420        // writer
9421        synchronized (mPackages) {
9422            if (!isExternalMediaAvailable()) {
9423                // If the external storage is no longer mounted at this point,
9424                // the caller may not have been able to delete all of this
9425                // packages files and can not delete any more.  Bail.
9426                return null;
9427            }
9428            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9429            if (lastPackage != null) {
9430                pkgs.remove(lastPackage);
9431            }
9432            if (pkgs.size() > 0) {
9433                return pkgs.get(0);
9434            }
9435        }
9436        return null;
9437    }
9438
9439    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9440        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9441                userId, andCode ? 1 : 0, packageName);
9442        if (mSystemReady) {
9443            msg.sendToTarget();
9444        } else {
9445            if (mPostSystemReadyMessages == null) {
9446                mPostSystemReadyMessages = new ArrayList<>();
9447            }
9448            mPostSystemReadyMessages.add(msg);
9449        }
9450    }
9451
9452    void startCleaningPackages() {
9453        // reader
9454        synchronized (mPackages) {
9455            if (!isExternalMediaAvailable()) {
9456                return;
9457            }
9458            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9459                return;
9460            }
9461        }
9462        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9463        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9464        IActivityManager am = ActivityManagerNative.getDefault();
9465        if (am != null) {
9466            try {
9467                am.startService(null, intent, null, mContext.getOpPackageName(),
9468                        UserHandle.USER_OWNER);
9469            } catch (RemoteException e) {
9470            }
9471        }
9472    }
9473
9474    @Override
9475    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9476            int installFlags, String installerPackageName, VerificationParams verificationParams,
9477            String packageAbiOverride) {
9478        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9479                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9480    }
9481
9482    @Override
9483    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9484            int installFlags, String installerPackageName, VerificationParams verificationParams,
9485            String packageAbiOverride, int userId) {
9486        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9487
9488        final int callingUid = Binder.getCallingUid();
9489        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9490
9491        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9492            try {
9493                if (observer != null) {
9494                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9495                }
9496            } catch (RemoteException re) {
9497            }
9498            return;
9499        }
9500
9501        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9502            installFlags |= PackageManager.INSTALL_FROM_ADB;
9503
9504        } else {
9505            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9506            // about installerPackageName.
9507
9508            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9509            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9510        }
9511
9512        UserHandle user;
9513        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9514            user = UserHandle.ALL;
9515        } else {
9516            user = new UserHandle(userId);
9517        }
9518
9519        // Only system components can circumvent runtime permissions when installing.
9520        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9521                && mContext.checkCallingOrSelfPermission(Manifest.permission
9522                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9523            throw new SecurityException("You need the "
9524                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9525                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9526        }
9527
9528        verificationParams.setInstallerUid(callingUid);
9529
9530        final File originFile = new File(originPath);
9531        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9532
9533        final Message msg = mHandler.obtainMessage(INIT_COPY);
9534        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9535                null, verificationParams, user, packageAbiOverride, null);
9536        mHandler.sendMessage(msg);
9537    }
9538
9539    void installStage(String packageName, File stagedDir, String stagedCid,
9540            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9541            String installerPackageName, int installerUid, UserHandle user) {
9542        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9543                params.referrerUri, installerUid, null);
9544        verifParams.setInstallerUid(installerUid);
9545
9546        final OriginInfo origin;
9547        if (stagedDir != null) {
9548            origin = OriginInfo.fromStagedFile(stagedDir);
9549        } else {
9550            origin = OriginInfo.fromStagedContainer(stagedCid);
9551        }
9552
9553        final Message msg = mHandler.obtainMessage(INIT_COPY);
9554        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9555                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9556                params.grantedRuntimePermissions);
9557        mHandler.sendMessage(msg);
9558    }
9559
9560    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9561        Bundle extras = new Bundle(1);
9562        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9563
9564        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9565                packageName, extras, null, null, new int[] {userId});
9566        try {
9567            IActivityManager am = ActivityManagerNative.getDefault();
9568            final boolean isSystem =
9569                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9570            if (isSystem && am.isUserRunning(userId, false)) {
9571                // The just-installed/enabled app is bundled on the system, so presumed
9572                // to be able to run automatically without needing an explicit launch.
9573                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9574                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9575                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9576                        .setPackage(packageName);
9577                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9578                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9579            }
9580        } catch (RemoteException e) {
9581            // shouldn't happen
9582            Slog.w(TAG, "Unable to bootstrap installed package", e);
9583        }
9584    }
9585
9586    @Override
9587    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9588            int userId) {
9589        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9590        PackageSetting pkgSetting;
9591        final int uid = Binder.getCallingUid();
9592        enforceCrossUserPermission(uid, userId, true, true,
9593                "setApplicationHiddenSetting for user " + userId);
9594
9595        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9596            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9597            return false;
9598        }
9599
9600        long callingId = Binder.clearCallingIdentity();
9601        try {
9602            boolean sendAdded = false;
9603            boolean sendRemoved = false;
9604            // writer
9605            synchronized (mPackages) {
9606                pkgSetting = mSettings.mPackages.get(packageName);
9607                if (pkgSetting == null) {
9608                    return false;
9609                }
9610                if (pkgSetting.getHidden(userId) != hidden) {
9611                    pkgSetting.setHidden(hidden, userId);
9612                    mSettings.writePackageRestrictionsLPr(userId);
9613                    if (hidden) {
9614                        sendRemoved = true;
9615                    } else {
9616                        sendAdded = true;
9617                    }
9618                }
9619            }
9620            if (sendAdded) {
9621                sendPackageAddedForUser(packageName, pkgSetting, userId);
9622                return true;
9623            }
9624            if (sendRemoved) {
9625                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9626                        "hiding pkg");
9627                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9628                return true;
9629            }
9630        } finally {
9631            Binder.restoreCallingIdentity(callingId);
9632        }
9633        return false;
9634    }
9635
9636    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9637            int userId) {
9638        final PackageRemovedInfo info = new PackageRemovedInfo();
9639        info.removedPackage = packageName;
9640        info.removedUsers = new int[] {userId};
9641        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9642        info.sendBroadcast(false, false, false);
9643    }
9644
9645    /**
9646     * Returns true if application is not found or there was an error. Otherwise it returns
9647     * the hidden state of the package for the given user.
9648     */
9649    @Override
9650    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9651        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9652        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9653                false, "getApplicationHidden for user " + userId);
9654        PackageSetting pkgSetting;
9655        long callingId = Binder.clearCallingIdentity();
9656        try {
9657            // writer
9658            synchronized (mPackages) {
9659                pkgSetting = mSettings.mPackages.get(packageName);
9660                if (pkgSetting == null) {
9661                    return true;
9662                }
9663                return pkgSetting.getHidden(userId);
9664            }
9665        } finally {
9666            Binder.restoreCallingIdentity(callingId);
9667        }
9668    }
9669
9670    /**
9671     * @hide
9672     */
9673    @Override
9674    public int installExistingPackageAsUser(String packageName, int userId) {
9675        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9676                null);
9677        PackageSetting pkgSetting;
9678        final int uid = Binder.getCallingUid();
9679        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9680                + userId);
9681        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9682            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9683        }
9684
9685        long callingId = Binder.clearCallingIdentity();
9686        try {
9687            boolean sendAdded = false;
9688
9689            // writer
9690            synchronized (mPackages) {
9691                pkgSetting = mSettings.mPackages.get(packageName);
9692                if (pkgSetting == null) {
9693                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9694                }
9695                if (!pkgSetting.getInstalled(userId)) {
9696                    pkgSetting.setInstalled(true, userId);
9697                    pkgSetting.setHidden(false, userId);
9698                    mSettings.writePackageRestrictionsLPr(userId);
9699                    sendAdded = true;
9700                }
9701            }
9702
9703            if (sendAdded) {
9704                sendPackageAddedForUser(packageName, pkgSetting, userId);
9705            }
9706        } finally {
9707            Binder.restoreCallingIdentity(callingId);
9708        }
9709
9710        return PackageManager.INSTALL_SUCCEEDED;
9711    }
9712
9713    boolean isUserRestricted(int userId, String restrictionKey) {
9714        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9715        if (restrictions.getBoolean(restrictionKey, false)) {
9716            Log.w(TAG, "User is restricted: " + restrictionKey);
9717            return true;
9718        }
9719        return false;
9720    }
9721
9722    @Override
9723    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9724        mContext.enforceCallingOrSelfPermission(
9725                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9726                "Only package verification agents can verify applications");
9727
9728        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9729        final PackageVerificationResponse response = new PackageVerificationResponse(
9730                verificationCode, Binder.getCallingUid());
9731        msg.arg1 = id;
9732        msg.obj = response;
9733        mHandler.sendMessage(msg);
9734    }
9735
9736    @Override
9737    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9738            long millisecondsToDelay) {
9739        mContext.enforceCallingOrSelfPermission(
9740                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9741                "Only package verification agents can extend verification timeouts");
9742
9743        final PackageVerificationState state = mPendingVerification.get(id);
9744        final PackageVerificationResponse response = new PackageVerificationResponse(
9745                verificationCodeAtTimeout, Binder.getCallingUid());
9746
9747        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9748            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9749        }
9750        if (millisecondsToDelay < 0) {
9751            millisecondsToDelay = 0;
9752        }
9753        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9754                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9755            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9756        }
9757
9758        if ((state != null) && !state.timeoutExtended()) {
9759            state.extendTimeout();
9760
9761            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9762            msg.arg1 = id;
9763            msg.obj = response;
9764            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9765        }
9766    }
9767
9768    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9769            int verificationCode, UserHandle user) {
9770        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9771        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9772        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9773        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9774        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9775
9776        mContext.sendBroadcastAsUser(intent, user,
9777                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9778    }
9779
9780    private ComponentName matchComponentForVerifier(String packageName,
9781            List<ResolveInfo> receivers) {
9782        ActivityInfo targetReceiver = null;
9783
9784        final int NR = receivers.size();
9785        for (int i = 0; i < NR; i++) {
9786            final ResolveInfo info = receivers.get(i);
9787            if (info.activityInfo == null) {
9788                continue;
9789            }
9790
9791            if (packageName.equals(info.activityInfo.packageName)) {
9792                targetReceiver = info.activityInfo;
9793                break;
9794            }
9795        }
9796
9797        if (targetReceiver == null) {
9798            return null;
9799        }
9800
9801        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9802    }
9803
9804    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9805            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9806        if (pkgInfo.verifiers.length == 0) {
9807            return null;
9808        }
9809
9810        final int N = pkgInfo.verifiers.length;
9811        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9812        for (int i = 0; i < N; i++) {
9813            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9814
9815            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9816                    receivers);
9817            if (comp == null) {
9818                continue;
9819            }
9820
9821            final int verifierUid = getUidForVerifier(verifierInfo);
9822            if (verifierUid == -1) {
9823                continue;
9824            }
9825
9826            if (DEBUG_VERIFY) {
9827                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9828                        + " with the correct signature");
9829            }
9830            sufficientVerifiers.add(comp);
9831            verificationState.addSufficientVerifier(verifierUid);
9832        }
9833
9834        return sufficientVerifiers;
9835    }
9836
9837    private int getUidForVerifier(VerifierInfo verifierInfo) {
9838        synchronized (mPackages) {
9839            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9840            if (pkg == null) {
9841                return -1;
9842            } else if (pkg.mSignatures.length != 1) {
9843                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9844                        + " has more than one signature; ignoring");
9845                return -1;
9846            }
9847
9848            /*
9849             * If the public key of the package's signature does not match
9850             * our expected public key, then this is a different package and
9851             * we should skip.
9852             */
9853
9854            final byte[] expectedPublicKey;
9855            try {
9856                final Signature verifierSig = pkg.mSignatures[0];
9857                final PublicKey publicKey = verifierSig.getPublicKey();
9858                expectedPublicKey = publicKey.getEncoded();
9859            } catch (CertificateException e) {
9860                return -1;
9861            }
9862
9863            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9864
9865            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9866                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9867                        + " does not have the expected public key; ignoring");
9868                return -1;
9869            }
9870
9871            return pkg.applicationInfo.uid;
9872        }
9873    }
9874
9875    @Override
9876    public void finishPackageInstall(int token) {
9877        enforceSystemOrRoot("Only the system is allowed to finish installs");
9878
9879        if (DEBUG_INSTALL) {
9880            Slog.v(TAG, "BM finishing package install for " + token);
9881        }
9882
9883        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9884        mHandler.sendMessage(msg);
9885    }
9886
9887    /**
9888     * Get the verification agent timeout.
9889     *
9890     * @return verification timeout in milliseconds
9891     */
9892    private long getVerificationTimeout() {
9893        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9894                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9895                DEFAULT_VERIFICATION_TIMEOUT);
9896    }
9897
9898    /**
9899     * Get the default verification agent response code.
9900     *
9901     * @return default verification response code
9902     */
9903    private int getDefaultVerificationResponse() {
9904        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9905                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9906                DEFAULT_VERIFICATION_RESPONSE);
9907    }
9908
9909    /**
9910     * Check whether or not package verification has been enabled.
9911     *
9912     * @return true if verification should be performed
9913     */
9914    private boolean isVerificationEnabled(int userId, int installFlags) {
9915        if (!DEFAULT_VERIFY_ENABLE) {
9916            return false;
9917        }
9918
9919        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9920
9921        // Check if installing from ADB
9922        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9923            // Do not run verification in a test harness environment
9924            if (ActivityManager.isRunningInTestHarness()) {
9925                return false;
9926            }
9927            if (ensureVerifyAppsEnabled) {
9928                return true;
9929            }
9930            // Check if the developer does not want package verification for ADB installs
9931            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9932                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9933                return false;
9934            }
9935        }
9936
9937        if (ensureVerifyAppsEnabled) {
9938            return true;
9939        }
9940
9941        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9942                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9943    }
9944
9945    @Override
9946    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9947            throws RemoteException {
9948        mContext.enforceCallingOrSelfPermission(
9949                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9950                "Only intentfilter verification agents can verify applications");
9951
9952        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9953        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9954                Binder.getCallingUid(), verificationCode, failedDomains);
9955        msg.arg1 = id;
9956        msg.obj = response;
9957        mHandler.sendMessage(msg);
9958    }
9959
9960    @Override
9961    public int getIntentVerificationStatus(String packageName, int userId) {
9962        synchronized (mPackages) {
9963            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9964        }
9965    }
9966
9967    @Override
9968    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9969        mContext.enforceCallingOrSelfPermission(
9970                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9971
9972        boolean result = false;
9973        synchronized (mPackages) {
9974            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9975        }
9976        if (result) {
9977            scheduleWritePackageRestrictionsLocked(userId);
9978        }
9979        return result;
9980    }
9981
9982    @Override
9983    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9984        synchronized (mPackages) {
9985            return mSettings.getIntentFilterVerificationsLPr(packageName);
9986        }
9987    }
9988
9989    @Override
9990    public List<IntentFilter> getAllIntentFilters(String packageName) {
9991        if (TextUtils.isEmpty(packageName)) {
9992            return Collections.<IntentFilter>emptyList();
9993        }
9994        synchronized (mPackages) {
9995            PackageParser.Package pkg = mPackages.get(packageName);
9996            if (pkg == null || pkg.activities == null) {
9997                return Collections.<IntentFilter>emptyList();
9998            }
9999            final int count = pkg.activities.size();
10000            ArrayList<IntentFilter> result = new ArrayList<>();
10001            for (int n=0; n<count; n++) {
10002                PackageParser.Activity activity = pkg.activities.get(n);
10003                if (activity.intents != null || activity.intents.size() > 0) {
10004                    result.addAll(activity.intents);
10005                }
10006            }
10007            return result;
10008        }
10009    }
10010
10011    @Override
10012    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10013        mContext.enforceCallingOrSelfPermission(
10014                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10015
10016        synchronized (mPackages) {
10017            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10018            if (packageName != null) {
10019                result |= updateIntentVerificationStatus(packageName,
10020                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10021                        userId);
10022                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10023                        packageName, userId);
10024            }
10025            return result;
10026        }
10027    }
10028
10029    @Override
10030    public String getDefaultBrowserPackageName(int userId) {
10031        synchronized (mPackages) {
10032            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10033        }
10034    }
10035
10036    /**
10037     * Get the "allow unknown sources" setting.
10038     *
10039     * @return the current "allow unknown sources" setting
10040     */
10041    private int getUnknownSourcesSettings() {
10042        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10043                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10044                -1);
10045    }
10046
10047    @Override
10048    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10049        final int uid = Binder.getCallingUid();
10050        // writer
10051        synchronized (mPackages) {
10052            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10053            if (targetPackageSetting == null) {
10054                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10055            }
10056
10057            PackageSetting installerPackageSetting;
10058            if (installerPackageName != null) {
10059                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10060                if (installerPackageSetting == null) {
10061                    throw new IllegalArgumentException("Unknown installer package: "
10062                            + installerPackageName);
10063                }
10064            } else {
10065                installerPackageSetting = null;
10066            }
10067
10068            Signature[] callerSignature;
10069            Object obj = mSettings.getUserIdLPr(uid);
10070            if (obj != null) {
10071                if (obj instanceof SharedUserSetting) {
10072                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10073                } else if (obj instanceof PackageSetting) {
10074                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10075                } else {
10076                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10077                }
10078            } else {
10079                throw new SecurityException("Unknown calling uid " + uid);
10080            }
10081
10082            // Verify: can't set installerPackageName to a package that is
10083            // not signed with the same cert as the caller.
10084            if (installerPackageSetting != null) {
10085                if (compareSignatures(callerSignature,
10086                        installerPackageSetting.signatures.mSignatures)
10087                        != PackageManager.SIGNATURE_MATCH) {
10088                    throw new SecurityException(
10089                            "Caller does not have same cert as new installer package "
10090                            + installerPackageName);
10091                }
10092            }
10093
10094            // Verify: if target already has an installer package, it must
10095            // be signed with the same cert as the caller.
10096            if (targetPackageSetting.installerPackageName != null) {
10097                PackageSetting setting = mSettings.mPackages.get(
10098                        targetPackageSetting.installerPackageName);
10099                // If the currently set package isn't valid, then it's always
10100                // okay to change it.
10101                if (setting != null) {
10102                    if (compareSignatures(callerSignature,
10103                            setting.signatures.mSignatures)
10104                            != PackageManager.SIGNATURE_MATCH) {
10105                        throw new SecurityException(
10106                                "Caller does not have same cert as old installer package "
10107                                + targetPackageSetting.installerPackageName);
10108                    }
10109                }
10110            }
10111
10112            // Okay!
10113            targetPackageSetting.installerPackageName = installerPackageName;
10114            scheduleWriteSettingsLocked();
10115        }
10116    }
10117
10118    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10119        // Queue up an async operation since the package installation may take a little while.
10120        mHandler.post(new Runnable() {
10121            public void run() {
10122                mHandler.removeCallbacks(this);
10123                 // Result object to be returned
10124                PackageInstalledInfo res = new PackageInstalledInfo();
10125                res.returnCode = currentStatus;
10126                res.uid = -1;
10127                res.pkg = null;
10128                res.removedInfo = new PackageRemovedInfo();
10129                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10130                    args.doPreInstall(res.returnCode);
10131                    synchronized (mInstallLock) {
10132                        installPackageLI(args, res);
10133                    }
10134                    args.doPostInstall(res.returnCode, res.uid);
10135                }
10136
10137                // A restore should be performed at this point if (a) the install
10138                // succeeded, (b) the operation is not an update, and (c) the new
10139                // package has not opted out of backup participation.
10140                final boolean update = res.removedInfo.removedPackage != null;
10141                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10142                boolean doRestore = !update
10143                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10144
10145                // Set up the post-install work request bookkeeping.  This will be used
10146                // and cleaned up by the post-install event handling regardless of whether
10147                // there's a restore pass performed.  Token values are >= 1.
10148                int token;
10149                if (mNextInstallToken < 0) mNextInstallToken = 1;
10150                token = mNextInstallToken++;
10151
10152                PostInstallData data = new PostInstallData(args, res);
10153                mRunningInstalls.put(token, data);
10154                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10155
10156                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10157                    // Pass responsibility to the Backup Manager.  It will perform a
10158                    // restore if appropriate, then pass responsibility back to the
10159                    // Package Manager to run the post-install observer callbacks
10160                    // and broadcasts.
10161                    IBackupManager bm = IBackupManager.Stub.asInterface(
10162                            ServiceManager.getService(Context.BACKUP_SERVICE));
10163                    if (bm != null) {
10164                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10165                                + " to BM for possible restore");
10166                        try {
10167                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10168                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10169                            } else {
10170                                doRestore = false;
10171                            }
10172                        } catch (RemoteException e) {
10173                            // can't happen; the backup manager is local
10174                        } catch (Exception e) {
10175                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10176                            doRestore = false;
10177                        }
10178                    } else {
10179                        Slog.e(TAG, "Backup Manager not found!");
10180                        doRestore = false;
10181                    }
10182                }
10183
10184                if (!doRestore) {
10185                    // No restore possible, or the Backup Manager was mysteriously not
10186                    // available -- just fire the post-install work request directly.
10187                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10188                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10189                    mHandler.sendMessage(msg);
10190                }
10191            }
10192        });
10193    }
10194
10195    private abstract class HandlerParams {
10196        private static final int MAX_RETRIES = 4;
10197
10198        /**
10199         * Number of times startCopy() has been attempted and had a non-fatal
10200         * error.
10201         */
10202        private int mRetries = 0;
10203
10204        /** User handle for the user requesting the information or installation. */
10205        private final UserHandle mUser;
10206
10207        HandlerParams(UserHandle user) {
10208            mUser = user;
10209        }
10210
10211        UserHandle getUser() {
10212            return mUser;
10213        }
10214
10215        final boolean startCopy() {
10216            boolean res;
10217            try {
10218                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10219
10220                if (++mRetries > MAX_RETRIES) {
10221                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10222                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10223                    handleServiceError();
10224                    return false;
10225                } else {
10226                    handleStartCopy();
10227                    res = true;
10228                }
10229            } catch (RemoteException e) {
10230                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10231                mHandler.sendEmptyMessage(MCS_RECONNECT);
10232                res = false;
10233            }
10234            handleReturnCode();
10235            return res;
10236        }
10237
10238        final void serviceError() {
10239            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10240            handleServiceError();
10241            handleReturnCode();
10242        }
10243
10244        abstract void handleStartCopy() throws RemoteException;
10245        abstract void handleServiceError();
10246        abstract void handleReturnCode();
10247    }
10248
10249    class MeasureParams extends HandlerParams {
10250        private final PackageStats mStats;
10251        private boolean mSuccess;
10252
10253        private final IPackageStatsObserver mObserver;
10254
10255        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10256            super(new UserHandle(stats.userHandle));
10257            mObserver = observer;
10258            mStats = stats;
10259        }
10260
10261        @Override
10262        public String toString() {
10263            return "MeasureParams{"
10264                + Integer.toHexString(System.identityHashCode(this))
10265                + " " + mStats.packageName + "}";
10266        }
10267
10268        @Override
10269        void handleStartCopy() throws RemoteException {
10270            synchronized (mInstallLock) {
10271                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10272            }
10273
10274            if (mSuccess) {
10275                final boolean mounted;
10276                if (Environment.isExternalStorageEmulated()) {
10277                    mounted = true;
10278                } else {
10279                    final String status = Environment.getExternalStorageState();
10280                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10281                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10282                }
10283
10284                if (mounted) {
10285                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10286
10287                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10288                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10289
10290                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10291                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10292
10293                    // Always subtract cache size, since it's a subdirectory
10294                    mStats.externalDataSize -= mStats.externalCacheSize;
10295
10296                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10297                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10298
10299                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10300                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10301                }
10302            }
10303        }
10304
10305        @Override
10306        void handleReturnCode() {
10307            if (mObserver != null) {
10308                try {
10309                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10310                } catch (RemoteException e) {
10311                    Slog.i(TAG, "Observer no longer exists.");
10312                }
10313            }
10314        }
10315
10316        @Override
10317        void handleServiceError() {
10318            Slog.e(TAG, "Could not measure application " + mStats.packageName
10319                            + " external storage");
10320        }
10321    }
10322
10323    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10324            throws RemoteException {
10325        long result = 0;
10326        for (File path : paths) {
10327            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10328        }
10329        return result;
10330    }
10331
10332    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10333        for (File path : paths) {
10334            try {
10335                mcs.clearDirectory(path.getAbsolutePath());
10336            } catch (RemoteException e) {
10337            }
10338        }
10339    }
10340
10341    static class OriginInfo {
10342        /**
10343         * Location where install is coming from, before it has been
10344         * copied/renamed into place. This could be a single monolithic APK
10345         * file, or a cluster directory. This location may be untrusted.
10346         */
10347        final File file;
10348        final String cid;
10349
10350        /**
10351         * Flag indicating that {@link #file} or {@link #cid} has already been
10352         * staged, meaning downstream users don't need to defensively copy the
10353         * contents.
10354         */
10355        final boolean staged;
10356
10357        /**
10358         * Flag indicating that {@link #file} or {@link #cid} is an already
10359         * installed app that is being moved.
10360         */
10361        final boolean existing;
10362
10363        final String resolvedPath;
10364        final File resolvedFile;
10365
10366        static OriginInfo fromNothing() {
10367            return new OriginInfo(null, null, false, false);
10368        }
10369
10370        static OriginInfo fromUntrustedFile(File file) {
10371            return new OriginInfo(file, null, false, false);
10372        }
10373
10374        static OriginInfo fromExistingFile(File file) {
10375            return new OriginInfo(file, null, false, true);
10376        }
10377
10378        static OriginInfo fromStagedFile(File file) {
10379            return new OriginInfo(file, null, true, false);
10380        }
10381
10382        static OriginInfo fromStagedContainer(String cid) {
10383            return new OriginInfo(null, cid, true, false);
10384        }
10385
10386        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10387            this.file = file;
10388            this.cid = cid;
10389            this.staged = staged;
10390            this.existing = existing;
10391
10392            if (cid != null) {
10393                resolvedPath = PackageHelper.getSdDir(cid);
10394                resolvedFile = new File(resolvedPath);
10395            } else if (file != null) {
10396                resolvedPath = file.getAbsolutePath();
10397                resolvedFile = file;
10398            } else {
10399                resolvedPath = null;
10400                resolvedFile = null;
10401            }
10402        }
10403    }
10404
10405    class MoveInfo {
10406        final int moveId;
10407        final String fromUuid;
10408        final String toUuid;
10409        final String packageName;
10410        final String dataAppName;
10411        final int appId;
10412        final String seinfo;
10413
10414        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10415                String dataAppName, int appId, String seinfo) {
10416            this.moveId = moveId;
10417            this.fromUuid = fromUuid;
10418            this.toUuid = toUuid;
10419            this.packageName = packageName;
10420            this.dataAppName = dataAppName;
10421            this.appId = appId;
10422            this.seinfo = seinfo;
10423        }
10424    }
10425
10426    class InstallParams extends HandlerParams {
10427        final OriginInfo origin;
10428        final MoveInfo move;
10429        final IPackageInstallObserver2 observer;
10430        int installFlags;
10431        final String installerPackageName;
10432        final String volumeUuid;
10433        final VerificationParams verificationParams;
10434        private InstallArgs mArgs;
10435        private int mRet;
10436        final String packageAbiOverride;
10437        final String[] grantedRuntimePermissions;
10438
10439
10440        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10441                int installFlags, String installerPackageName, String volumeUuid,
10442                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10443                String[] grantedPermissions) {
10444            super(user);
10445            this.origin = origin;
10446            this.move = move;
10447            this.observer = observer;
10448            this.installFlags = installFlags;
10449            this.installerPackageName = installerPackageName;
10450            this.volumeUuid = volumeUuid;
10451            this.verificationParams = verificationParams;
10452            this.packageAbiOverride = packageAbiOverride;
10453            this.grantedRuntimePermissions = grantedPermissions;
10454        }
10455
10456        @Override
10457        public String toString() {
10458            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10459                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10460        }
10461
10462        public ManifestDigest getManifestDigest() {
10463            if (verificationParams == null) {
10464                return null;
10465            }
10466            return verificationParams.getManifestDigest();
10467        }
10468
10469        private int installLocationPolicy(PackageInfoLite pkgLite) {
10470            String packageName = pkgLite.packageName;
10471            int installLocation = pkgLite.installLocation;
10472            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10473            // reader
10474            synchronized (mPackages) {
10475                PackageParser.Package pkg = mPackages.get(packageName);
10476                if (pkg != null) {
10477                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10478                        // Check for downgrading.
10479                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10480                            try {
10481                                checkDowngrade(pkg, pkgLite);
10482                            } catch (PackageManagerException e) {
10483                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10484                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10485                            }
10486                        }
10487                        // Check for updated system application.
10488                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10489                            if (onSd) {
10490                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10491                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10492                            }
10493                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10494                        } else {
10495                            if (onSd) {
10496                                // Install flag overrides everything.
10497                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10498                            }
10499                            // If current upgrade specifies particular preference
10500                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10501                                // Application explicitly specified internal.
10502                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10503                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10504                                // App explictly prefers external. Let policy decide
10505                            } else {
10506                                // Prefer previous location
10507                                if (isExternal(pkg)) {
10508                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10509                                }
10510                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10511                            }
10512                        }
10513                    } else {
10514                        // Invalid install. Return error code
10515                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10516                    }
10517                }
10518            }
10519            // All the special cases have been taken care of.
10520            // Return result based on recommended install location.
10521            if (onSd) {
10522                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10523            }
10524            return pkgLite.recommendedInstallLocation;
10525        }
10526
10527        /*
10528         * Invoke remote method to get package information and install
10529         * location values. Override install location based on default
10530         * policy if needed and then create install arguments based
10531         * on the install location.
10532         */
10533        public void handleStartCopy() throws RemoteException {
10534            int ret = PackageManager.INSTALL_SUCCEEDED;
10535
10536            // If we're already staged, we've firmly committed to an install location
10537            if (origin.staged) {
10538                if (origin.file != null) {
10539                    installFlags |= PackageManager.INSTALL_INTERNAL;
10540                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10541                } else if (origin.cid != null) {
10542                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10543                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10544                } else {
10545                    throw new IllegalStateException("Invalid stage location");
10546                }
10547            }
10548
10549            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10550            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10551
10552            PackageInfoLite pkgLite = null;
10553
10554            if (onInt && onSd) {
10555                // Check if both bits are set.
10556                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10557                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10558            } else {
10559                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10560                        packageAbiOverride);
10561
10562                /*
10563                 * If we have too little free space, try to free cache
10564                 * before giving up.
10565                 */
10566                if (!origin.staged && pkgLite.recommendedInstallLocation
10567                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10568                    // TODO: focus freeing disk space on the target device
10569                    final StorageManager storage = StorageManager.from(mContext);
10570                    final long lowThreshold = storage.getStorageLowBytes(
10571                            Environment.getDataDirectory());
10572
10573                    final long sizeBytes = mContainerService.calculateInstalledSize(
10574                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10575
10576                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10577                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10578                                installFlags, packageAbiOverride);
10579                    }
10580
10581                    /*
10582                     * The cache free must have deleted the file we
10583                     * downloaded to install.
10584                     *
10585                     * TODO: fix the "freeCache" call to not delete
10586                     *       the file we care about.
10587                     */
10588                    if (pkgLite.recommendedInstallLocation
10589                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10590                        pkgLite.recommendedInstallLocation
10591                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10592                    }
10593                }
10594            }
10595
10596            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10597                int loc = pkgLite.recommendedInstallLocation;
10598                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10599                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10600                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10601                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10602                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10603                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10604                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10605                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10606                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10607                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10608                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10609                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10610                } else {
10611                    // Override with defaults if needed.
10612                    loc = installLocationPolicy(pkgLite);
10613                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10614                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10615                    } else if (!onSd && !onInt) {
10616                        // Override install location with flags
10617                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10618                            // Set the flag to install on external media.
10619                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10620                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10621                        } else {
10622                            // Make sure the flag for installing on external
10623                            // media is unset
10624                            installFlags |= PackageManager.INSTALL_INTERNAL;
10625                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10626                        }
10627                    }
10628                }
10629            }
10630
10631            final InstallArgs args = createInstallArgs(this);
10632            mArgs = args;
10633
10634            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10635                 /*
10636                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10637                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10638                 */
10639                int userIdentifier = getUser().getIdentifier();
10640                if (userIdentifier == UserHandle.USER_ALL
10641                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10642                    userIdentifier = UserHandle.USER_OWNER;
10643                }
10644
10645                /*
10646                 * Determine if we have any installed package verifiers. If we
10647                 * do, then we'll defer to them to verify the packages.
10648                 */
10649                final int requiredUid = mRequiredVerifierPackage == null ? -1
10650                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10651                if (!origin.existing && requiredUid != -1
10652                        && isVerificationEnabled(userIdentifier, installFlags)) {
10653                    final Intent verification = new Intent(
10654                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10655                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10656                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10657                            PACKAGE_MIME_TYPE);
10658                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10659
10660                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10661                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10662                            0 /* TODO: Which userId? */);
10663
10664                    if (DEBUG_VERIFY) {
10665                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10666                                + verification.toString() + " with " + pkgLite.verifiers.length
10667                                + " optional verifiers");
10668                    }
10669
10670                    final int verificationId = mPendingVerificationToken++;
10671
10672                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10673
10674                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10675                            installerPackageName);
10676
10677                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10678                            installFlags);
10679
10680                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10681                            pkgLite.packageName);
10682
10683                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10684                            pkgLite.versionCode);
10685
10686                    if (verificationParams != null) {
10687                        if (verificationParams.getVerificationURI() != null) {
10688                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10689                                 verificationParams.getVerificationURI());
10690                        }
10691                        if (verificationParams.getOriginatingURI() != null) {
10692                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10693                                  verificationParams.getOriginatingURI());
10694                        }
10695                        if (verificationParams.getReferrer() != null) {
10696                            verification.putExtra(Intent.EXTRA_REFERRER,
10697                                  verificationParams.getReferrer());
10698                        }
10699                        if (verificationParams.getOriginatingUid() >= 0) {
10700                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10701                                  verificationParams.getOriginatingUid());
10702                        }
10703                        if (verificationParams.getInstallerUid() >= 0) {
10704                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10705                                  verificationParams.getInstallerUid());
10706                        }
10707                    }
10708
10709                    final PackageVerificationState verificationState = new PackageVerificationState(
10710                            requiredUid, args);
10711
10712                    mPendingVerification.append(verificationId, verificationState);
10713
10714                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10715                            receivers, verificationState);
10716
10717                    // Apps installed for "all" users use the device owner to verify the app
10718                    UserHandle verifierUser = getUser();
10719                    if (verifierUser == UserHandle.ALL) {
10720                        verifierUser = UserHandle.OWNER;
10721                    }
10722
10723                    /*
10724                     * If any sufficient verifiers were listed in the package
10725                     * manifest, attempt to ask them.
10726                     */
10727                    if (sufficientVerifiers != null) {
10728                        final int N = sufficientVerifiers.size();
10729                        if (N == 0) {
10730                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10731                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10732                        } else {
10733                            for (int i = 0; i < N; i++) {
10734                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10735
10736                                final Intent sufficientIntent = new Intent(verification);
10737                                sufficientIntent.setComponent(verifierComponent);
10738                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10739                            }
10740                        }
10741                    }
10742
10743                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10744                            mRequiredVerifierPackage, receivers);
10745                    if (ret == PackageManager.INSTALL_SUCCEEDED
10746                            && mRequiredVerifierPackage != null) {
10747                        /*
10748                         * Send the intent to the required verification agent,
10749                         * but only start the verification timeout after the
10750                         * target BroadcastReceivers have run.
10751                         */
10752                        verification.setComponent(requiredVerifierComponent);
10753                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10754                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10755                                new BroadcastReceiver() {
10756                                    @Override
10757                                    public void onReceive(Context context, Intent intent) {
10758                                        final Message msg = mHandler
10759                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10760                                        msg.arg1 = verificationId;
10761                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10762                                    }
10763                                }, null, 0, null, null);
10764
10765                        /*
10766                         * We don't want the copy to proceed until verification
10767                         * succeeds, so null out this field.
10768                         */
10769                        mArgs = null;
10770                    }
10771                } else {
10772                    /*
10773                     * No package verification is enabled, so immediately start
10774                     * the remote call to initiate copy using temporary file.
10775                     */
10776                    ret = args.copyApk(mContainerService, true);
10777                }
10778            }
10779
10780            mRet = ret;
10781        }
10782
10783        @Override
10784        void handleReturnCode() {
10785            // If mArgs is null, then MCS couldn't be reached. When it
10786            // reconnects, it will try again to install. At that point, this
10787            // will succeed.
10788            if (mArgs != null) {
10789                processPendingInstall(mArgs, mRet);
10790            }
10791        }
10792
10793        @Override
10794        void handleServiceError() {
10795            mArgs = createInstallArgs(this);
10796            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10797        }
10798
10799        public boolean isForwardLocked() {
10800            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10801        }
10802    }
10803
10804    /**
10805     * Used during creation of InstallArgs
10806     *
10807     * @param installFlags package installation flags
10808     * @return true if should be installed on external storage
10809     */
10810    private static boolean installOnExternalAsec(int installFlags) {
10811        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10812            return false;
10813        }
10814        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10815            return true;
10816        }
10817        return false;
10818    }
10819
10820    /**
10821     * Used during creation of InstallArgs
10822     *
10823     * @param installFlags package installation flags
10824     * @return true if should be installed as forward locked
10825     */
10826    private static boolean installForwardLocked(int installFlags) {
10827        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10828    }
10829
10830    private InstallArgs createInstallArgs(InstallParams params) {
10831        if (params.move != null) {
10832            return new MoveInstallArgs(params);
10833        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10834            return new AsecInstallArgs(params);
10835        } else {
10836            return new FileInstallArgs(params);
10837        }
10838    }
10839
10840    /**
10841     * Create args that describe an existing installed package. Typically used
10842     * when cleaning up old installs, or used as a move source.
10843     */
10844    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10845            String resourcePath, String[] instructionSets) {
10846        final boolean isInAsec;
10847        if (installOnExternalAsec(installFlags)) {
10848            /* Apps on SD card are always in ASEC containers. */
10849            isInAsec = true;
10850        } else if (installForwardLocked(installFlags)
10851                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10852            /*
10853             * Forward-locked apps are only in ASEC containers if they're the
10854             * new style
10855             */
10856            isInAsec = true;
10857        } else {
10858            isInAsec = false;
10859        }
10860
10861        if (isInAsec) {
10862            return new AsecInstallArgs(codePath, instructionSets,
10863                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10864        } else {
10865            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10866        }
10867    }
10868
10869    static abstract class InstallArgs {
10870        /** @see InstallParams#origin */
10871        final OriginInfo origin;
10872        /** @see InstallParams#move */
10873        final MoveInfo move;
10874
10875        final IPackageInstallObserver2 observer;
10876        // Always refers to PackageManager flags only
10877        final int installFlags;
10878        final String installerPackageName;
10879        final String volumeUuid;
10880        final ManifestDigest manifestDigest;
10881        final UserHandle user;
10882        final String abiOverride;
10883        final String[] installGrantPermissions;
10884
10885        // The list of instruction sets supported by this app. This is currently
10886        // only used during the rmdex() phase to clean up resources. We can get rid of this
10887        // if we move dex files under the common app path.
10888        /* nullable */ String[] instructionSets;
10889
10890        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10891                int installFlags, String installerPackageName, String volumeUuid,
10892                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10893                String abiOverride, String[] installGrantPermissions) {
10894            this.origin = origin;
10895            this.move = move;
10896            this.installFlags = installFlags;
10897            this.observer = observer;
10898            this.installerPackageName = installerPackageName;
10899            this.volumeUuid = volumeUuid;
10900            this.manifestDigest = manifestDigest;
10901            this.user = user;
10902            this.instructionSets = instructionSets;
10903            this.abiOverride = abiOverride;
10904            this.installGrantPermissions = installGrantPermissions;
10905        }
10906
10907        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10908        abstract int doPreInstall(int status);
10909
10910        /**
10911         * Rename package into final resting place. All paths on the given
10912         * scanned package should be updated to reflect the rename.
10913         */
10914        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10915        abstract int doPostInstall(int status, int uid);
10916
10917        /** @see PackageSettingBase#codePathString */
10918        abstract String getCodePath();
10919        /** @see PackageSettingBase#resourcePathString */
10920        abstract String getResourcePath();
10921
10922        // Need installer lock especially for dex file removal.
10923        abstract void cleanUpResourcesLI();
10924        abstract boolean doPostDeleteLI(boolean delete);
10925
10926        /**
10927         * Called before the source arguments are copied. This is used mostly
10928         * for MoveParams when it needs to read the source file to put it in the
10929         * destination.
10930         */
10931        int doPreCopy() {
10932            return PackageManager.INSTALL_SUCCEEDED;
10933        }
10934
10935        /**
10936         * Called after the source arguments are copied. This is used mostly for
10937         * MoveParams when it needs to read the source file to put it in the
10938         * destination.
10939         *
10940         * @return
10941         */
10942        int doPostCopy(int uid) {
10943            return PackageManager.INSTALL_SUCCEEDED;
10944        }
10945
10946        protected boolean isFwdLocked() {
10947            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10948        }
10949
10950        protected boolean isExternalAsec() {
10951            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10952        }
10953
10954        UserHandle getUser() {
10955            return user;
10956        }
10957    }
10958
10959    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10960        if (!allCodePaths.isEmpty()) {
10961            if (instructionSets == null) {
10962                throw new IllegalStateException("instructionSet == null");
10963            }
10964            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10965            for (String codePath : allCodePaths) {
10966                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10967                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10968                    if (retCode < 0) {
10969                        Slog.w(TAG, "Couldn't remove dex file for package: "
10970                                + " at location " + codePath + ", retcode=" + retCode);
10971                        // we don't consider this to be a failure of the core package deletion
10972                    }
10973                }
10974            }
10975        }
10976    }
10977
10978    /**
10979     * Logic to handle installation of non-ASEC applications, including copying
10980     * and renaming logic.
10981     */
10982    class FileInstallArgs extends InstallArgs {
10983        private File codeFile;
10984        private File resourceFile;
10985
10986        // Example topology:
10987        // /data/app/com.example/base.apk
10988        // /data/app/com.example/split_foo.apk
10989        // /data/app/com.example/lib/arm/libfoo.so
10990        // /data/app/com.example/lib/arm64/libfoo.so
10991        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10992
10993        /** New install */
10994        FileInstallArgs(InstallParams params) {
10995            super(params.origin, params.move, params.observer, params.installFlags,
10996                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10997                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
10998                    params.grantedRuntimePermissions);
10999            if (isFwdLocked()) {
11000                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11001            }
11002        }
11003
11004        /** Existing install */
11005        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11006            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11007                    null, null);
11008            this.codeFile = (codePath != null) ? new File(codePath) : null;
11009            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11010        }
11011
11012        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11013            if (origin.staged) {
11014                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11015                codeFile = origin.file;
11016                resourceFile = origin.file;
11017                return PackageManager.INSTALL_SUCCEEDED;
11018            }
11019
11020            try {
11021                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11022                codeFile = tempDir;
11023                resourceFile = tempDir;
11024            } catch (IOException e) {
11025                Slog.w(TAG, "Failed to create copy file: " + e);
11026                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11027            }
11028
11029            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11030                @Override
11031                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11032                    if (!FileUtils.isValidExtFilename(name)) {
11033                        throw new IllegalArgumentException("Invalid filename: " + name);
11034                    }
11035                    try {
11036                        final File file = new File(codeFile, name);
11037                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11038                                O_RDWR | O_CREAT, 0644);
11039                        Os.chmod(file.getAbsolutePath(), 0644);
11040                        return new ParcelFileDescriptor(fd);
11041                    } catch (ErrnoException e) {
11042                        throw new RemoteException("Failed to open: " + e.getMessage());
11043                    }
11044                }
11045            };
11046
11047            int ret = PackageManager.INSTALL_SUCCEEDED;
11048            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11049            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11050                Slog.e(TAG, "Failed to copy package");
11051                return ret;
11052            }
11053
11054            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11055            NativeLibraryHelper.Handle handle = null;
11056            try {
11057                handle = NativeLibraryHelper.Handle.create(codeFile);
11058                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11059                        abiOverride);
11060            } catch (IOException e) {
11061                Slog.e(TAG, "Copying native libraries failed", e);
11062                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11063            } finally {
11064                IoUtils.closeQuietly(handle);
11065            }
11066
11067            return ret;
11068        }
11069
11070        int doPreInstall(int status) {
11071            if (status != PackageManager.INSTALL_SUCCEEDED) {
11072                cleanUp();
11073            }
11074            return status;
11075        }
11076
11077        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11078            if (status != PackageManager.INSTALL_SUCCEEDED) {
11079                cleanUp();
11080                return false;
11081            }
11082
11083            final File targetDir = codeFile.getParentFile();
11084            final File beforeCodeFile = codeFile;
11085            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11086
11087            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11088            try {
11089                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11090            } catch (ErrnoException e) {
11091                Slog.w(TAG, "Failed to rename", e);
11092                return false;
11093            }
11094
11095            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11096                Slog.w(TAG, "Failed to restorecon");
11097                return false;
11098            }
11099
11100            // Reflect the rename internally
11101            codeFile = afterCodeFile;
11102            resourceFile = afterCodeFile;
11103
11104            // Reflect the rename in scanned details
11105            pkg.codePath = afterCodeFile.getAbsolutePath();
11106            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11107                    pkg.baseCodePath);
11108            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11109                    pkg.splitCodePaths);
11110
11111            // Reflect the rename in app info
11112            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11113            pkg.applicationInfo.setCodePath(pkg.codePath);
11114            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11115            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11116            pkg.applicationInfo.setResourcePath(pkg.codePath);
11117            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11118            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11119
11120            return true;
11121        }
11122
11123        int doPostInstall(int status, int uid) {
11124            if (status != PackageManager.INSTALL_SUCCEEDED) {
11125                cleanUp();
11126            }
11127            return status;
11128        }
11129
11130        @Override
11131        String getCodePath() {
11132            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11133        }
11134
11135        @Override
11136        String getResourcePath() {
11137            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11138        }
11139
11140        private boolean cleanUp() {
11141            if (codeFile == null || !codeFile.exists()) {
11142                return false;
11143            }
11144
11145            if (codeFile.isDirectory()) {
11146                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11147            } else {
11148                codeFile.delete();
11149            }
11150
11151            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11152                resourceFile.delete();
11153            }
11154
11155            return true;
11156        }
11157
11158        void cleanUpResourcesLI() {
11159            // Try enumerating all code paths before deleting
11160            List<String> allCodePaths = Collections.EMPTY_LIST;
11161            if (codeFile != null && codeFile.exists()) {
11162                try {
11163                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11164                    allCodePaths = pkg.getAllCodePaths();
11165                } catch (PackageParserException e) {
11166                    // Ignored; we tried our best
11167                }
11168            }
11169
11170            cleanUp();
11171            removeDexFiles(allCodePaths, instructionSets);
11172        }
11173
11174        boolean doPostDeleteLI(boolean delete) {
11175            // XXX err, shouldn't we respect the delete flag?
11176            cleanUpResourcesLI();
11177            return true;
11178        }
11179    }
11180
11181    private boolean isAsecExternal(String cid) {
11182        final String asecPath = PackageHelper.getSdFilesystem(cid);
11183        return !asecPath.startsWith(mAsecInternalPath);
11184    }
11185
11186    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11187            PackageManagerException {
11188        if (copyRet < 0) {
11189            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11190                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11191                throw new PackageManagerException(copyRet, message);
11192            }
11193        }
11194    }
11195
11196    /**
11197     * Extract the MountService "container ID" from the full code path of an
11198     * .apk.
11199     */
11200    static String cidFromCodePath(String fullCodePath) {
11201        int eidx = fullCodePath.lastIndexOf("/");
11202        String subStr1 = fullCodePath.substring(0, eidx);
11203        int sidx = subStr1.lastIndexOf("/");
11204        return subStr1.substring(sidx+1, eidx);
11205    }
11206
11207    /**
11208     * Logic to handle installation of ASEC applications, including copying and
11209     * renaming logic.
11210     */
11211    class AsecInstallArgs extends InstallArgs {
11212        static final String RES_FILE_NAME = "pkg.apk";
11213        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11214
11215        String cid;
11216        String packagePath;
11217        String resourcePath;
11218
11219        /** New install */
11220        AsecInstallArgs(InstallParams params) {
11221            super(params.origin, params.move, params.observer, params.installFlags,
11222                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11223                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11224                    params.grantedRuntimePermissions);
11225        }
11226
11227        /** Existing install */
11228        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11229                        boolean isExternal, boolean isForwardLocked) {
11230            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11231                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11232                    instructionSets, null, null);
11233            // Hackily pretend we're still looking at a full code path
11234            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11235                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11236            }
11237
11238            // Extract cid from fullCodePath
11239            int eidx = fullCodePath.lastIndexOf("/");
11240            String subStr1 = fullCodePath.substring(0, eidx);
11241            int sidx = subStr1.lastIndexOf("/");
11242            cid = subStr1.substring(sidx+1, eidx);
11243            setMountPath(subStr1);
11244        }
11245
11246        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11247            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11248                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11249                    instructionSets, null, null);
11250            this.cid = cid;
11251            setMountPath(PackageHelper.getSdDir(cid));
11252        }
11253
11254        void createCopyFile() {
11255            cid = mInstallerService.allocateExternalStageCidLegacy();
11256        }
11257
11258        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11259            if (origin.staged) {
11260                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11261                cid = origin.cid;
11262                setMountPath(PackageHelper.getSdDir(cid));
11263                return PackageManager.INSTALL_SUCCEEDED;
11264            }
11265
11266            if (temp) {
11267                createCopyFile();
11268            } else {
11269                /*
11270                 * Pre-emptively destroy the container since it's destroyed if
11271                 * copying fails due to it existing anyway.
11272                 */
11273                PackageHelper.destroySdDir(cid);
11274            }
11275
11276            final String newMountPath = imcs.copyPackageToContainer(
11277                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11278                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11279
11280            if (newMountPath != null) {
11281                setMountPath(newMountPath);
11282                return PackageManager.INSTALL_SUCCEEDED;
11283            } else {
11284                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11285            }
11286        }
11287
11288        @Override
11289        String getCodePath() {
11290            return packagePath;
11291        }
11292
11293        @Override
11294        String getResourcePath() {
11295            return resourcePath;
11296        }
11297
11298        int doPreInstall(int status) {
11299            if (status != PackageManager.INSTALL_SUCCEEDED) {
11300                // Destroy container
11301                PackageHelper.destroySdDir(cid);
11302            } else {
11303                boolean mounted = PackageHelper.isContainerMounted(cid);
11304                if (!mounted) {
11305                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11306                            Process.SYSTEM_UID);
11307                    if (newMountPath != null) {
11308                        setMountPath(newMountPath);
11309                    } else {
11310                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11311                    }
11312                }
11313            }
11314            return status;
11315        }
11316
11317        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11318            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11319            String newMountPath = null;
11320            if (PackageHelper.isContainerMounted(cid)) {
11321                // Unmount the container
11322                if (!PackageHelper.unMountSdDir(cid)) {
11323                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11324                    return false;
11325                }
11326            }
11327            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11328                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11329                        " which might be stale. Will try to clean up.");
11330                // Clean up the stale container and proceed to recreate.
11331                if (!PackageHelper.destroySdDir(newCacheId)) {
11332                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11333                    return false;
11334                }
11335                // Successfully cleaned up stale container. Try to rename again.
11336                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11337                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11338                            + " inspite of cleaning it up.");
11339                    return false;
11340                }
11341            }
11342            if (!PackageHelper.isContainerMounted(newCacheId)) {
11343                Slog.w(TAG, "Mounting container " + newCacheId);
11344                newMountPath = PackageHelper.mountSdDir(newCacheId,
11345                        getEncryptKey(), Process.SYSTEM_UID);
11346            } else {
11347                newMountPath = PackageHelper.getSdDir(newCacheId);
11348            }
11349            if (newMountPath == null) {
11350                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11351                return false;
11352            }
11353            Log.i(TAG, "Succesfully renamed " + cid +
11354                    " to " + newCacheId +
11355                    " at new path: " + newMountPath);
11356            cid = newCacheId;
11357
11358            final File beforeCodeFile = new File(packagePath);
11359            setMountPath(newMountPath);
11360            final File afterCodeFile = new File(packagePath);
11361
11362            // Reflect the rename in scanned details
11363            pkg.codePath = afterCodeFile.getAbsolutePath();
11364            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11365                    pkg.baseCodePath);
11366            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11367                    pkg.splitCodePaths);
11368
11369            // Reflect the rename in app info
11370            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11371            pkg.applicationInfo.setCodePath(pkg.codePath);
11372            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11373            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11374            pkg.applicationInfo.setResourcePath(pkg.codePath);
11375            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11376            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11377
11378            return true;
11379        }
11380
11381        private void setMountPath(String mountPath) {
11382            final File mountFile = new File(mountPath);
11383
11384            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11385            if (monolithicFile.exists()) {
11386                packagePath = monolithicFile.getAbsolutePath();
11387                if (isFwdLocked()) {
11388                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11389                } else {
11390                    resourcePath = packagePath;
11391                }
11392            } else {
11393                packagePath = mountFile.getAbsolutePath();
11394                resourcePath = packagePath;
11395            }
11396        }
11397
11398        int doPostInstall(int status, int uid) {
11399            if (status != PackageManager.INSTALL_SUCCEEDED) {
11400                cleanUp();
11401            } else {
11402                final int groupOwner;
11403                final String protectedFile;
11404                if (isFwdLocked()) {
11405                    groupOwner = UserHandle.getSharedAppGid(uid);
11406                    protectedFile = RES_FILE_NAME;
11407                } else {
11408                    groupOwner = -1;
11409                    protectedFile = null;
11410                }
11411
11412                if (uid < Process.FIRST_APPLICATION_UID
11413                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11414                    Slog.e(TAG, "Failed to finalize " + cid);
11415                    PackageHelper.destroySdDir(cid);
11416                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11417                }
11418
11419                boolean mounted = PackageHelper.isContainerMounted(cid);
11420                if (!mounted) {
11421                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11422                }
11423            }
11424            return status;
11425        }
11426
11427        private void cleanUp() {
11428            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11429
11430            // Destroy secure container
11431            PackageHelper.destroySdDir(cid);
11432        }
11433
11434        private List<String> getAllCodePaths() {
11435            final File codeFile = new File(getCodePath());
11436            if (codeFile != null && codeFile.exists()) {
11437                try {
11438                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11439                    return pkg.getAllCodePaths();
11440                } catch (PackageParserException e) {
11441                    // Ignored; we tried our best
11442                }
11443            }
11444            return Collections.EMPTY_LIST;
11445        }
11446
11447        void cleanUpResourcesLI() {
11448            // Enumerate all code paths before deleting
11449            cleanUpResourcesLI(getAllCodePaths());
11450        }
11451
11452        private void cleanUpResourcesLI(List<String> allCodePaths) {
11453            cleanUp();
11454            removeDexFiles(allCodePaths, instructionSets);
11455        }
11456
11457        String getPackageName() {
11458            return getAsecPackageName(cid);
11459        }
11460
11461        boolean doPostDeleteLI(boolean delete) {
11462            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11463            final List<String> allCodePaths = getAllCodePaths();
11464            boolean mounted = PackageHelper.isContainerMounted(cid);
11465            if (mounted) {
11466                // Unmount first
11467                if (PackageHelper.unMountSdDir(cid)) {
11468                    mounted = false;
11469                }
11470            }
11471            if (!mounted && delete) {
11472                cleanUpResourcesLI(allCodePaths);
11473            }
11474            return !mounted;
11475        }
11476
11477        @Override
11478        int doPreCopy() {
11479            if (isFwdLocked()) {
11480                if (!PackageHelper.fixSdPermissions(cid,
11481                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11482                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11483                }
11484            }
11485
11486            return PackageManager.INSTALL_SUCCEEDED;
11487        }
11488
11489        @Override
11490        int doPostCopy(int uid) {
11491            if (isFwdLocked()) {
11492                if (uid < Process.FIRST_APPLICATION_UID
11493                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11494                                RES_FILE_NAME)) {
11495                    Slog.e(TAG, "Failed to finalize " + cid);
11496                    PackageHelper.destroySdDir(cid);
11497                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11498                }
11499            }
11500
11501            return PackageManager.INSTALL_SUCCEEDED;
11502        }
11503    }
11504
11505    /**
11506     * Logic to handle movement of existing installed applications.
11507     */
11508    class MoveInstallArgs extends InstallArgs {
11509        private File codeFile;
11510        private File resourceFile;
11511
11512        /** New install */
11513        MoveInstallArgs(InstallParams params) {
11514            super(params.origin, params.move, params.observer, params.installFlags,
11515                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11516                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11517                    params.grantedRuntimePermissions);
11518        }
11519
11520        int copyApk(IMediaContainerService imcs, boolean temp) {
11521            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11522                    + move.fromUuid + " to " + move.toUuid);
11523            synchronized (mInstaller) {
11524                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11525                        move.dataAppName, move.appId, move.seinfo) != 0) {
11526                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11527                }
11528            }
11529
11530            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11531            resourceFile = codeFile;
11532            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11533
11534            return PackageManager.INSTALL_SUCCEEDED;
11535        }
11536
11537        int doPreInstall(int status) {
11538            if (status != PackageManager.INSTALL_SUCCEEDED) {
11539                cleanUp(move.toUuid);
11540            }
11541            return status;
11542        }
11543
11544        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11545            if (status != PackageManager.INSTALL_SUCCEEDED) {
11546                cleanUp(move.toUuid);
11547                return false;
11548            }
11549
11550            // Reflect the move in app info
11551            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11552            pkg.applicationInfo.setCodePath(pkg.codePath);
11553            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11554            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11555            pkg.applicationInfo.setResourcePath(pkg.codePath);
11556            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11557            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11558
11559            return true;
11560        }
11561
11562        int doPostInstall(int status, int uid) {
11563            if (status == PackageManager.INSTALL_SUCCEEDED) {
11564                cleanUp(move.fromUuid);
11565            } else {
11566                cleanUp(move.toUuid);
11567            }
11568            return status;
11569        }
11570
11571        @Override
11572        String getCodePath() {
11573            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11574        }
11575
11576        @Override
11577        String getResourcePath() {
11578            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11579        }
11580
11581        private boolean cleanUp(String volumeUuid) {
11582            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11583                    move.dataAppName);
11584            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11585            synchronized (mInstallLock) {
11586                // Clean up both app data and code
11587                removeDataDirsLI(volumeUuid, move.packageName);
11588                if (codeFile.isDirectory()) {
11589                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11590                } else {
11591                    codeFile.delete();
11592                }
11593            }
11594            return true;
11595        }
11596
11597        void cleanUpResourcesLI() {
11598            throw new UnsupportedOperationException();
11599        }
11600
11601        boolean doPostDeleteLI(boolean delete) {
11602            throw new UnsupportedOperationException();
11603        }
11604    }
11605
11606    static String getAsecPackageName(String packageCid) {
11607        int idx = packageCid.lastIndexOf("-");
11608        if (idx == -1) {
11609            return packageCid;
11610        }
11611        return packageCid.substring(0, idx);
11612    }
11613
11614    // Utility method used to create code paths based on package name and available index.
11615    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11616        String idxStr = "";
11617        int idx = 1;
11618        // Fall back to default value of idx=1 if prefix is not
11619        // part of oldCodePath
11620        if (oldCodePath != null) {
11621            String subStr = oldCodePath;
11622            // Drop the suffix right away
11623            if (suffix != null && subStr.endsWith(suffix)) {
11624                subStr = subStr.substring(0, subStr.length() - suffix.length());
11625            }
11626            // If oldCodePath already contains prefix find out the
11627            // ending index to either increment or decrement.
11628            int sidx = subStr.lastIndexOf(prefix);
11629            if (sidx != -1) {
11630                subStr = subStr.substring(sidx + prefix.length());
11631                if (subStr != null) {
11632                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11633                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11634                    }
11635                    try {
11636                        idx = Integer.parseInt(subStr);
11637                        if (idx <= 1) {
11638                            idx++;
11639                        } else {
11640                            idx--;
11641                        }
11642                    } catch(NumberFormatException e) {
11643                    }
11644                }
11645            }
11646        }
11647        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11648        return prefix + idxStr;
11649    }
11650
11651    private File getNextCodePath(File targetDir, String packageName) {
11652        int suffix = 1;
11653        File result;
11654        do {
11655            result = new File(targetDir, packageName + "-" + suffix);
11656            suffix++;
11657        } while (result.exists());
11658        return result;
11659    }
11660
11661    // Utility method that returns the relative package path with respect
11662    // to the installation directory. Like say for /data/data/com.test-1.apk
11663    // string com.test-1 is returned.
11664    static String deriveCodePathName(String codePath) {
11665        if (codePath == null) {
11666            return null;
11667        }
11668        final File codeFile = new File(codePath);
11669        final String name = codeFile.getName();
11670        if (codeFile.isDirectory()) {
11671            return name;
11672        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11673            final int lastDot = name.lastIndexOf('.');
11674            return name.substring(0, lastDot);
11675        } else {
11676            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11677            return null;
11678        }
11679    }
11680
11681    class PackageInstalledInfo {
11682        String name;
11683        int uid;
11684        // The set of users that originally had this package installed.
11685        int[] origUsers;
11686        // The set of users that now have this package installed.
11687        int[] newUsers;
11688        PackageParser.Package pkg;
11689        int returnCode;
11690        String returnMsg;
11691        PackageRemovedInfo removedInfo;
11692
11693        public void setError(int code, String msg) {
11694            returnCode = code;
11695            returnMsg = msg;
11696            Slog.w(TAG, msg);
11697        }
11698
11699        public void setError(String msg, PackageParserException e) {
11700            returnCode = e.error;
11701            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11702            Slog.w(TAG, msg, e);
11703        }
11704
11705        public void setError(String msg, PackageManagerException e) {
11706            returnCode = e.error;
11707            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11708            Slog.w(TAG, msg, e);
11709        }
11710
11711        // In some error cases we want to convey more info back to the observer
11712        String origPackage;
11713        String origPermission;
11714    }
11715
11716    /*
11717     * Install a non-existing package.
11718     */
11719    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11720            UserHandle user, String installerPackageName, String volumeUuid,
11721            PackageInstalledInfo res) {
11722        // Remember this for later, in case we need to rollback this install
11723        String pkgName = pkg.packageName;
11724
11725        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11726        final boolean dataDirExists = Environment
11727                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11728        synchronized(mPackages) {
11729            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11730                // A package with the same name is already installed, though
11731                // it has been renamed to an older name.  The package we
11732                // are trying to install should be installed as an update to
11733                // the existing one, but that has not been requested, so bail.
11734                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11735                        + " without first uninstalling package running as "
11736                        + mSettings.mRenamedPackages.get(pkgName));
11737                return;
11738            }
11739            if (mPackages.containsKey(pkgName)) {
11740                // Don't allow installation over an existing package with the same name.
11741                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11742                        + " without first uninstalling.");
11743                return;
11744            }
11745        }
11746
11747        try {
11748            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11749                    System.currentTimeMillis(), user);
11750
11751            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11752            // delete the partially installed application. the data directory will have to be
11753            // restored if it was already existing
11754            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11755                // remove package from internal structures.  Note that we want deletePackageX to
11756                // delete the package data and cache directories that it created in
11757                // scanPackageLocked, unless those directories existed before we even tried to
11758                // install.
11759                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11760                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11761                                res.removedInfo, true);
11762            }
11763
11764        } catch (PackageManagerException e) {
11765            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11766        }
11767    }
11768
11769    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11770        // Can't rotate keys during boot or if sharedUser.
11771        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11772                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11773            return false;
11774        }
11775        // app is using upgradeKeySets; make sure all are valid
11776        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11777        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11778        for (int i = 0; i < upgradeKeySets.length; i++) {
11779            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11780                Slog.wtf(TAG, "Package "
11781                         + (oldPs.name != null ? oldPs.name : "<null>")
11782                         + " contains upgrade-key-set reference to unknown key-set: "
11783                         + upgradeKeySets[i]
11784                         + " reverting to signatures check.");
11785                return false;
11786            }
11787        }
11788        return true;
11789    }
11790
11791    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11792        // Upgrade keysets are being used.  Determine if new package has a superset of the
11793        // required keys.
11794        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11795        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11796        for (int i = 0; i < upgradeKeySets.length; i++) {
11797            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11798            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11799                return true;
11800            }
11801        }
11802        return false;
11803    }
11804
11805    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11806            UserHandle user, String installerPackageName, String volumeUuid,
11807            PackageInstalledInfo res) {
11808        final PackageParser.Package oldPackage;
11809        final String pkgName = pkg.packageName;
11810        final int[] allUsers;
11811        final boolean[] perUserInstalled;
11812
11813        // First find the old package info and check signatures
11814        synchronized(mPackages) {
11815            oldPackage = mPackages.get(pkgName);
11816            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11817            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11818            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11819                if(!checkUpgradeKeySetLP(ps, pkg)) {
11820                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11821                            "New package not signed by keys specified by upgrade-keysets: "
11822                            + pkgName);
11823                    return;
11824                }
11825            } else {
11826                // default to original signature matching
11827                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11828                    != PackageManager.SIGNATURE_MATCH) {
11829                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11830                            "New package has a different signature: " + pkgName);
11831                    return;
11832                }
11833            }
11834
11835            // In case of rollback, remember per-user/profile install state
11836            allUsers = sUserManager.getUserIds();
11837            perUserInstalled = new boolean[allUsers.length];
11838            for (int i = 0; i < allUsers.length; i++) {
11839                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11840            }
11841        }
11842
11843        boolean sysPkg = (isSystemApp(oldPackage));
11844        if (sysPkg) {
11845            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11846                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11847        } else {
11848            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11849                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11850        }
11851    }
11852
11853    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11854            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11855            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11856            String volumeUuid, PackageInstalledInfo res) {
11857        String pkgName = deletedPackage.packageName;
11858        boolean deletedPkg = true;
11859        boolean updatedSettings = false;
11860
11861        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11862                + deletedPackage);
11863        long origUpdateTime;
11864        if (pkg.mExtras != null) {
11865            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11866        } else {
11867            origUpdateTime = 0;
11868        }
11869
11870        // First delete the existing package while retaining the data directory
11871        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11872                res.removedInfo, true)) {
11873            // If the existing package wasn't successfully deleted
11874            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11875            deletedPkg = false;
11876        } else {
11877            // Successfully deleted the old package; proceed with replace.
11878
11879            // If deleted package lived in a container, give users a chance to
11880            // relinquish resources before killing.
11881            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11882                if (DEBUG_INSTALL) {
11883                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11884                }
11885                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11886                final ArrayList<String> pkgList = new ArrayList<String>(1);
11887                pkgList.add(deletedPackage.applicationInfo.packageName);
11888                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11889            }
11890
11891            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11892            try {
11893                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11894                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11895                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11896                        perUserInstalled, res, user);
11897                updatedSettings = true;
11898            } catch (PackageManagerException e) {
11899                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11900            }
11901        }
11902
11903        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11904            // remove package from internal structures.  Note that we want deletePackageX to
11905            // delete the package data and cache directories that it created in
11906            // scanPackageLocked, unless those directories existed before we even tried to
11907            // install.
11908            if(updatedSettings) {
11909                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11910                deletePackageLI(
11911                        pkgName, null, true, allUsers, perUserInstalled,
11912                        PackageManager.DELETE_KEEP_DATA,
11913                                res.removedInfo, true);
11914            }
11915            // Since we failed to install the new package we need to restore the old
11916            // package that we deleted.
11917            if (deletedPkg) {
11918                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11919                File restoreFile = new File(deletedPackage.codePath);
11920                // Parse old package
11921                boolean oldExternal = isExternal(deletedPackage);
11922                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11923                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11924                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11925                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11926                try {
11927                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11928                } catch (PackageManagerException e) {
11929                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11930                            + e.getMessage());
11931                    return;
11932                }
11933                // Restore of old package succeeded. Update permissions.
11934                // writer
11935                synchronized (mPackages) {
11936                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11937                            UPDATE_PERMISSIONS_ALL);
11938                    // can downgrade to reader
11939                    mSettings.writeLPr();
11940                }
11941                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11942            }
11943        }
11944    }
11945
11946    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11947            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11948            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11949            String volumeUuid, PackageInstalledInfo res) {
11950        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11951                + ", old=" + deletedPackage);
11952        boolean disabledSystem = false;
11953        boolean updatedSettings = false;
11954        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11955        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11956                != 0) {
11957            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11958        }
11959        String packageName = deletedPackage.packageName;
11960        if (packageName == null) {
11961            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11962                    "Attempt to delete null packageName.");
11963            return;
11964        }
11965        PackageParser.Package oldPkg;
11966        PackageSetting oldPkgSetting;
11967        // reader
11968        synchronized (mPackages) {
11969            oldPkg = mPackages.get(packageName);
11970            oldPkgSetting = mSettings.mPackages.get(packageName);
11971            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11972                    (oldPkgSetting == null)) {
11973                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11974                        "Couldn't find package:" + packageName + " information");
11975                return;
11976            }
11977        }
11978
11979        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
11980
11981        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11982        res.removedInfo.removedPackage = packageName;
11983        // Remove existing system package
11984        removePackageLI(oldPkgSetting, true);
11985        // writer
11986        synchronized (mPackages) {
11987            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11988            if (!disabledSystem && deletedPackage != null) {
11989                // We didn't need to disable the .apk as a current system package,
11990                // which means we are replacing another update that is already
11991                // installed.  We need to make sure to delete the older one's .apk.
11992                res.removedInfo.args = createInstallArgsForExisting(0,
11993                        deletedPackage.applicationInfo.getCodePath(),
11994                        deletedPackage.applicationInfo.getResourcePath(),
11995                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11996            } else {
11997                res.removedInfo.args = null;
11998            }
11999        }
12000
12001        // Successfully disabled the old package. Now proceed with re-installation
12002        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12003
12004        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12005        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12006
12007        PackageParser.Package newPackage = null;
12008        try {
12009            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
12010            if (newPackage.mExtras != null) {
12011                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12012                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12013                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12014
12015                // is the update attempting to change shared user? that isn't going to work...
12016                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12017                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12018                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12019                            + " to " + newPkgSetting.sharedUser);
12020                    updatedSettings = true;
12021                }
12022            }
12023
12024            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12025                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12026                        perUserInstalled, res, user);
12027                updatedSettings = true;
12028            }
12029
12030        } catch (PackageManagerException e) {
12031            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12032        }
12033
12034        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12035            // Re installation failed. Restore old information
12036            // Remove new pkg information
12037            if (newPackage != null) {
12038                removeInstalledPackageLI(newPackage, true);
12039            }
12040            // Add back the old system package
12041            try {
12042                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12043            } catch (PackageManagerException e) {
12044                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12045            }
12046            // Restore the old system information in Settings
12047            synchronized (mPackages) {
12048                if (disabledSystem) {
12049                    mSettings.enableSystemPackageLPw(packageName);
12050                }
12051                if (updatedSettings) {
12052                    mSettings.setInstallerPackageName(packageName,
12053                            oldPkgSetting.installerPackageName);
12054                }
12055                mSettings.writeLPr();
12056            }
12057        }
12058    }
12059
12060    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12061            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12062            UserHandle user) {
12063        String pkgName = newPackage.packageName;
12064        synchronized (mPackages) {
12065            //write settings. the installStatus will be incomplete at this stage.
12066            //note that the new package setting would have already been
12067            //added to mPackages. It hasn't been persisted yet.
12068            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12069            mSettings.writeLPr();
12070        }
12071
12072        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12073
12074        synchronized (mPackages) {
12075            updatePermissionsLPw(newPackage.packageName, newPackage,
12076                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12077                            ? UPDATE_PERMISSIONS_ALL : 0));
12078            // For system-bundled packages, we assume that installing an upgraded version
12079            // of the package implies that the user actually wants to run that new code,
12080            // so we enable the package.
12081            PackageSetting ps = mSettings.mPackages.get(pkgName);
12082            if (ps != null) {
12083                if (isSystemApp(newPackage)) {
12084                    // NB: implicit assumption that system package upgrades apply to all users
12085                    if (DEBUG_INSTALL) {
12086                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12087                    }
12088                    if (res.origUsers != null) {
12089                        for (int userHandle : res.origUsers) {
12090                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12091                                    userHandle, installerPackageName);
12092                        }
12093                    }
12094                    // Also convey the prior install/uninstall state
12095                    if (allUsers != null && perUserInstalled != null) {
12096                        for (int i = 0; i < allUsers.length; i++) {
12097                            if (DEBUG_INSTALL) {
12098                                Slog.d(TAG, "    user " + allUsers[i]
12099                                        + " => " + perUserInstalled[i]);
12100                            }
12101                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12102                        }
12103                        // these install state changes will be persisted in the
12104                        // upcoming call to mSettings.writeLPr().
12105                    }
12106                }
12107                // It's implied that when a user requests installation, they want the app to be
12108                // installed and enabled.
12109                int userId = user.getIdentifier();
12110                if (userId != UserHandle.USER_ALL) {
12111                    ps.setInstalled(true, userId);
12112                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12113                }
12114            }
12115            res.name = pkgName;
12116            res.uid = newPackage.applicationInfo.uid;
12117            res.pkg = newPackage;
12118            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12119            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12120            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12121            //to update install status
12122            mSettings.writeLPr();
12123        }
12124    }
12125
12126    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12127        final int installFlags = args.installFlags;
12128        final String installerPackageName = args.installerPackageName;
12129        final String volumeUuid = args.volumeUuid;
12130        final File tmpPackageFile = new File(args.getCodePath());
12131        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12132        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12133                || (args.volumeUuid != null));
12134        boolean replace = false;
12135        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12136        if (args.move != null) {
12137            // moving a complete application; perfom an initial scan on the new install location
12138            scanFlags |= SCAN_INITIAL;
12139        }
12140        // Result object to be returned
12141        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12142
12143        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12144        // Retrieve PackageSettings and parse package
12145        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12146                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12147                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12148        PackageParser pp = new PackageParser();
12149        pp.setSeparateProcesses(mSeparateProcesses);
12150        pp.setDisplayMetrics(mMetrics);
12151
12152        final PackageParser.Package pkg;
12153        try {
12154            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12155        } catch (PackageParserException e) {
12156            res.setError("Failed parse during installPackageLI", e);
12157            return;
12158        }
12159
12160        // Mark that we have an install time CPU ABI override.
12161        pkg.cpuAbiOverride = args.abiOverride;
12162
12163        String pkgName = res.name = pkg.packageName;
12164        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12165            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12166                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12167                return;
12168            }
12169        }
12170
12171        try {
12172            pp.collectCertificates(pkg, parseFlags);
12173            pp.collectManifestDigest(pkg);
12174        } catch (PackageParserException e) {
12175            res.setError("Failed collect during installPackageLI", e);
12176            return;
12177        }
12178
12179        /* If the installer passed in a manifest digest, compare it now. */
12180        if (args.manifestDigest != null) {
12181            if (DEBUG_INSTALL) {
12182                final String parsedManifest = pkg.manifestDigest == null ? "null"
12183                        : pkg.manifestDigest.toString();
12184                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12185                        + parsedManifest);
12186            }
12187
12188            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12189                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12190                return;
12191            }
12192        } else if (DEBUG_INSTALL) {
12193            final String parsedManifest = pkg.manifestDigest == null
12194                    ? "null" : pkg.manifestDigest.toString();
12195            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12196        }
12197
12198        // Get rid of all references to package scan path via parser.
12199        pp = null;
12200        String oldCodePath = null;
12201        boolean systemApp = false;
12202        synchronized (mPackages) {
12203            // Check if installing already existing package
12204            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12205                String oldName = mSettings.mRenamedPackages.get(pkgName);
12206                if (pkg.mOriginalPackages != null
12207                        && pkg.mOriginalPackages.contains(oldName)
12208                        && mPackages.containsKey(oldName)) {
12209                    // This package is derived from an original package,
12210                    // and this device has been updating from that original
12211                    // name.  We must continue using the original name, so
12212                    // rename the new package here.
12213                    pkg.setPackageName(oldName);
12214                    pkgName = pkg.packageName;
12215                    replace = true;
12216                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12217                            + oldName + " pkgName=" + pkgName);
12218                } else if (mPackages.containsKey(pkgName)) {
12219                    // This package, under its official name, already exists
12220                    // on the device; we should replace it.
12221                    replace = true;
12222                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12223                }
12224
12225                // Prevent apps opting out from runtime permissions
12226                if (replace) {
12227                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12228                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12229                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12230                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12231                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12232                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12233                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12234                                        + " doesn't support runtime permissions but the old"
12235                                        + " target SDK " + oldTargetSdk + " does.");
12236                        return;
12237                    }
12238                }
12239            }
12240
12241            PackageSetting ps = mSettings.mPackages.get(pkgName);
12242            if (ps != null) {
12243                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12244
12245                // Quick sanity check that we're signed correctly if updating;
12246                // we'll check this again later when scanning, but we want to
12247                // bail early here before tripping over redefined permissions.
12248                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12249                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12250                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12251                                + pkg.packageName + " upgrade keys do not match the "
12252                                + "previously installed version");
12253                        return;
12254                    }
12255                } else {
12256                    try {
12257                        verifySignaturesLP(ps, pkg);
12258                    } catch (PackageManagerException e) {
12259                        res.setError(e.error, e.getMessage());
12260                        return;
12261                    }
12262                }
12263
12264                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12265                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12266                    systemApp = (ps.pkg.applicationInfo.flags &
12267                            ApplicationInfo.FLAG_SYSTEM) != 0;
12268                }
12269                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12270            }
12271
12272            // Check whether the newly-scanned package wants to define an already-defined perm
12273            int N = pkg.permissions.size();
12274            for (int i = N-1; i >= 0; i--) {
12275                PackageParser.Permission perm = pkg.permissions.get(i);
12276                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12277                if (bp != null) {
12278                    // If the defining package is signed with our cert, it's okay.  This
12279                    // also includes the "updating the same package" case, of course.
12280                    // "updating same package" could also involve key-rotation.
12281                    final boolean sigsOk;
12282                    if (bp.sourcePackage.equals(pkg.packageName)
12283                            && (bp.packageSetting instanceof PackageSetting)
12284                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12285                                    scanFlags))) {
12286                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12287                    } else {
12288                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12289                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12290                    }
12291                    if (!sigsOk) {
12292                        // If the owning package is the system itself, we log but allow
12293                        // install to proceed; we fail the install on all other permission
12294                        // redefinitions.
12295                        if (!bp.sourcePackage.equals("android")) {
12296                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12297                                    + pkg.packageName + " attempting to redeclare permission "
12298                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12299                            res.origPermission = perm.info.name;
12300                            res.origPackage = bp.sourcePackage;
12301                            return;
12302                        } else {
12303                            Slog.w(TAG, "Package " + pkg.packageName
12304                                    + " attempting to redeclare system permission "
12305                                    + perm.info.name + "; ignoring new declaration");
12306                            pkg.permissions.remove(i);
12307                        }
12308                    }
12309                }
12310            }
12311
12312        }
12313
12314        if (systemApp && onExternal) {
12315            // Disable updates to system apps on sdcard
12316            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12317                    "Cannot install updates to system apps on sdcard");
12318            return;
12319        }
12320
12321        if (args.move != null) {
12322            // We did an in-place move, so dex is ready to roll
12323            scanFlags |= SCAN_NO_DEX;
12324            scanFlags |= SCAN_MOVE;
12325
12326            synchronized (mPackages) {
12327                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12328                if (ps == null) {
12329                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12330                            "Missing settings for moved package " + pkgName);
12331                }
12332
12333                // We moved the entire application as-is, so bring over the
12334                // previously derived ABI information.
12335                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12336                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12337            }
12338
12339        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12340            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12341            scanFlags |= SCAN_NO_DEX;
12342
12343            try {
12344                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12345                        true /* extract libs */);
12346            } catch (PackageManagerException pme) {
12347                Slog.e(TAG, "Error deriving application ABI", pme);
12348                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12349                return;
12350            }
12351
12352            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12353            int result = mPackageDexOptimizer
12354                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12355                            false /* defer */, false /* inclDependencies */,
12356                            true /*bootComplete*/);
12357            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12358                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12359                return;
12360            }
12361        }
12362
12363        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12364            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12365            return;
12366        }
12367
12368        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12369
12370        if (replace) {
12371            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12372                    installerPackageName, volumeUuid, res);
12373        } else {
12374            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12375                    args.user, installerPackageName, volumeUuid, res);
12376        }
12377        synchronized (mPackages) {
12378            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12379            if (ps != null) {
12380                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12381            }
12382        }
12383    }
12384
12385    private void startIntentFilterVerifications(int userId, boolean replacing,
12386            PackageParser.Package pkg) {
12387        if (mIntentFilterVerifierComponent == null) {
12388            Slog.w(TAG, "No IntentFilter verification will not be done as "
12389                    + "there is no IntentFilterVerifier available!");
12390            return;
12391        }
12392
12393        final int verifierUid = getPackageUid(
12394                mIntentFilterVerifierComponent.getPackageName(),
12395                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12396
12397        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12398        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12399        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12400        mHandler.sendMessage(msg);
12401    }
12402
12403    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12404            PackageParser.Package pkg) {
12405        int size = pkg.activities.size();
12406        if (size == 0) {
12407            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12408                    "No activity, so no need to verify any IntentFilter!");
12409            return;
12410        }
12411
12412        final boolean hasDomainURLs = hasDomainURLs(pkg);
12413        if (!hasDomainURLs) {
12414            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12415                    "No domain URLs, so no need to verify any IntentFilter!");
12416            return;
12417        }
12418
12419        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12420                + " if any IntentFilter from the " + size
12421                + " Activities needs verification ...");
12422
12423        int count = 0;
12424        final String packageName = pkg.packageName;
12425
12426        synchronized (mPackages) {
12427            // If this is a new install and we see that we've already run verification for this
12428            // package, we have nothing to do: it means the state was restored from backup.
12429            if (!replacing) {
12430                IntentFilterVerificationInfo ivi =
12431                        mSettings.getIntentFilterVerificationLPr(packageName);
12432                if (ivi != null) {
12433                    if (DEBUG_DOMAIN_VERIFICATION) {
12434                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12435                                + ivi.getStatusString());
12436                    }
12437                    return;
12438                }
12439            }
12440
12441            // If any filters need to be verified, then all need to be.
12442            boolean needToVerify = false;
12443            for (PackageParser.Activity a : pkg.activities) {
12444                for (ActivityIntentInfo filter : a.intents) {
12445                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12446                        if (DEBUG_DOMAIN_VERIFICATION) {
12447                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12448                        }
12449                        needToVerify = true;
12450                        break;
12451                    }
12452                }
12453            }
12454
12455            if (needToVerify) {
12456                final int verificationId = mIntentFilterVerificationToken++;
12457                for (PackageParser.Activity a : pkg.activities) {
12458                    for (ActivityIntentInfo filter : a.intents) {
12459                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12460                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12461                                    "Verification needed for IntentFilter:" + filter.toString());
12462                            mIntentFilterVerifier.addOneIntentFilterVerification(
12463                                    verifierUid, userId, verificationId, filter, packageName);
12464                            count++;
12465                        }
12466                    }
12467                }
12468            }
12469        }
12470
12471        if (count > 0) {
12472            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12473                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12474                    +  " for userId:" + userId);
12475            mIntentFilterVerifier.startVerifications(userId);
12476        } else {
12477            if (DEBUG_DOMAIN_VERIFICATION) {
12478                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12479            }
12480        }
12481    }
12482
12483    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12484        final ComponentName cn  = filter.activity.getComponentName();
12485        final String packageName = cn.getPackageName();
12486
12487        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12488                packageName);
12489        if (ivi == null) {
12490            return true;
12491        }
12492        int status = ivi.getStatus();
12493        switch (status) {
12494            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12495            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12496                return true;
12497
12498            default:
12499                // Nothing to do
12500                return false;
12501        }
12502    }
12503
12504    private static boolean isMultiArch(PackageSetting ps) {
12505        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12506    }
12507
12508    private static boolean isMultiArch(ApplicationInfo info) {
12509        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12510    }
12511
12512    private static boolean isExternal(PackageParser.Package pkg) {
12513        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12514    }
12515
12516    private static boolean isExternal(PackageSetting ps) {
12517        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12518    }
12519
12520    private static boolean isExternal(ApplicationInfo info) {
12521        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12522    }
12523
12524    private static boolean isSystemApp(PackageParser.Package pkg) {
12525        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12526    }
12527
12528    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12529        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12530    }
12531
12532    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12533        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12534    }
12535
12536    private static boolean isSystemApp(PackageSetting ps) {
12537        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12538    }
12539
12540    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12541        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12542    }
12543
12544    private int packageFlagsToInstallFlags(PackageSetting ps) {
12545        int installFlags = 0;
12546        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12547            // This existing package was an external ASEC install when we have
12548            // the external flag without a UUID
12549            installFlags |= PackageManager.INSTALL_EXTERNAL;
12550        }
12551        if (ps.isForwardLocked()) {
12552            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12553        }
12554        return installFlags;
12555    }
12556
12557    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12558        if (isExternal(pkg)) {
12559            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12560                return mSettings.getExternalVersion();
12561            } else {
12562                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12563            }
12564        } else {
12565            return mSettings.getInternalVersion();
12566        }
12567    }
12568
12569    private void deleteTempPackageFiles() {
12570        final FilenameFilter filter = new FilenameFilter() {
12571            public boolean accept(File dir, String name) {
12572                return name.startsWith("vmdl") && name.endsWith(".tmp");
12573            }
12574        };
12575        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12576            file.delete();
12577        }
12578    }
12579
12580    @Override
12581    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12582            int flags) {
12583        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12584                flags);
12585    }
12586
12587    @Override
12588    public void deletePackage(final String packageName,
12589            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12590        mContext.enforceCallingOrSelfPermission(
12591                android.Manifest.permission.DELETE_PACKAGES, null);
12592        Preconditions.checkNotNull(packageName);
12593        Preconditions.checkNotNull(observer);
12594        final int uid = Binder.getCallingUid();
12595        if (UserHandle.getUserId(uid) != userId) {
12596            mContext.enforceCallingPermission(
12597                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12598                    "deletePackage for user " + userId);
12599        }
12600        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12601            try {
12602                observer.onPackageDeleted(packageName,
12603                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12604            } catch (RemoteException re) {
12605            }
12606            return;
12607        }
12608
12609        boolean uninstallBlocked = false;
12610        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12611            int[] users = sUserManager.getUserIds();
12612            for (int i = 0; i < users.length; ++i) {
12613                if (getBlockUninstallForUser(packageName, users[i])) {
12614                    uninstallBlocked = true;
12615                    break;
12616                }
12617            }
12618        } else {
12619            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12620        }
12621        if (uninstallBlocked) {
12622            try {
12623                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12624                        null);
12625            } catch (RemoteException re) {
12626            }
12627            return;
12628        }
12629
12630        if (DEBUG_REMOVE) {
12631            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12632        }
12633        // Queue up an async operation since the package deletion may take a little while.
12634        mHandler.post(new Runnable() {
12635            public void run() {
12636                mHandler.removeCallbacks(this);
12637                final int returnCode = deletePackageX(packageName, userId, flags);
12638                if (observer != null) {
12639                    try {
12640                        observer.onPackageDeleted(packageName, returnCode, null);
12641                    } catch (RemoteException e) {
12642                        Log.i(TAG, "Observer no longer exists.");
12643                    } //end catch
12644                } //end if
12645            } //end run
12646        });
12647    }
12648
12649    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12650        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12651                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12652        try {
12653            if (dpm != null) {
12654                if (dpm.isDeviceOwner(packageName)) {
12655                    return true;
12656                }
12657                int[] users;
12658                if (userId == UserHandle.USER_ALL) {
12659                    users = sUserManager.getUserIds();
12660                } else {
12661                    users = new int[]{userId};
12662                }
12663                for (int i = 0; i < users.length; ++i) {
12664                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12665                        return true;
12666                    }
12667                }
12668            }
12669        } catch (RemoteException e) {
12670        }
12671        return false;
12672    }
12673
12674    /**
12675     *  This method is an internal method that could be get invoked either
12676     *  to delete an installed package or to clean up a failed installation.
12677     *  After deleting an installed package, a broadcast is sent to notify any
12678     *  listeners that the package has been installed. For cleaning up a failed
12679     *  installation, the broadcast is not necessary since the package's
12680     *  installation wouldn't have sent the initial broadcast either
12681     *  The key steps in deleting a package are
12682     *  deleting the package information in internal structures like mPackages,
12683     *  deleting the packages base directories through installd
12684     *  updating mSettings to reflect current status
12685     *  persisting settings for later use
12686     *  sending a broadcast if necessary
12687     */
12688    private int deletePackageX(String packageName, int userId, int flags) {
12689        final PackageRemovedInfo info = new PackageRemovedInfo();
12690        final boolean res;
12691
12692        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12693                ? UserHandle.ALL : new UserHandle(userId);
12694
12695        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12696            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12697            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12698        }
12699
12700        boolean removedForAllUsers = false;
12701        boolean systemUpdate = false;
12702
12703        // for the uninstall-updates case and restricted profiles, remember the per-
12704        // userhandle installed state
12705        int[] allUsers;
12706        boolean[] perUserInstalled;
12707        synchronized (mPackages) {
12708            PackageSetting ps = mSettings.mPackages.get(packageName);
12709            allUsers = sUserManager.getUserIds();
12710            perUserInstalled = new boolean[allUsers.length];
12711            for (int i = 0; i < allUsers.length; i++) {
12712                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12713            }
12714        }
12715
12716        synchronized (mInstallLock) {
12717            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12718            res = deletePackageLI(packageName, removeForUser,
12719                    true, allUsers, perUserInstalled,
12720                    flags | REMOVE_CHATTY, info, true);
12721            systemUpdate = info.isRemovedPackageSystemUpdate;
12722            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12723                removedForAllUsers = true;
12724            }
12725            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12726                    + " removedForAllUsers=" + removedForAllUsers);
12727        }
12728
12729        if (res) {
12730            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12731
12732            // If the removed package was a system update, the old system package
12733            // was re-enabled; we need to broadcast this information
12734            if (systemUpdate) {
12735                Bundle extras = new Bundle(1);
12736                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12737                        ? info.removedAppId : info.uid);
12738                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12739
12740                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12741                        extras, null, null, null);
12742                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12743                        extras, null, null, null);
12744                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12745                        null, packageName, null, null);
12746            }
12747        }
12748        // Force a gc here.
12749        Runtime.getRuntime().gc();
12750        // Delete the resources here after sending the broadcast to let
12751        // other processes clean up before deleting resources.
12752        if (info.args != null) {
12753            synchronized (mInstallLock) {
12754                info.args.doPostDeleteLI(true);
12755            }
12756        }
12757
12758        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12759    }
12760
12761    class PackageRemovedInfo {
12762        String removedPackage;
12763        int uid = -1;
12764        int removedAppId = -1;
12765        int[] removedUsers = null;
12766        boolean isRemovedPackageSystemUpdate = false;
12767        // Clean up resources deleted packages.
12768        InstallArgs args = null;
12769
12770        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12771            Bundle extras = new Bundle(1);
12772            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12773            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12774            if (replacing) {
12775                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12776            }
12777            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12778            if (removedPackage != null) {
12779                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12780                        extras, null, null, removedUsers);
12781                if (fullRemove && !replacing) {
12782                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12783                            extras, null, null, removedUsers);
12784                }
12785            }
12786            if (removedAppId >= 0) {
12787                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12788                        removedUsers);
12789            }
12790        }
12791    }
12792
12793    /*
12794     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12795     * flag is not set, the data directory is removed as well.
12796     * make sure this flag is set for partially installed apps. If not its meaningless to
12797     * delete a partially installed application.
12798     */
12799    private void removePackageDataLI(PackageSetting ps,
12800            int[] allUserHandles, boolean[] perUserInstalled,
12801            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12802        String packageName = ps.name;
12803        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12804        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12805        // Retrieve object to delete permissions for shared user later on
12806        final PackageSetting deletedPs;
12807        // reader
12808        synchronized (mPackages) {
12809            deletedPs = mSettings.mPackages.get(packageName);
12810            if (outInfo != null) {
12811                outInfo.removedPackage = packageName;
12812                outInfo.removedUsers = deletedPs != null
12813                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12814                        : null;
12815            }
12816        }
12817        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12818            removeDataDirsLI(ps.volumeUuid, packageName);
12819            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12820        }
12821        // writer
12822        synchronized (mPackages) {
12823            if (deletedPs != null) {
12824                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12825                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12826                    clearDefaultBrowserIfNeeded(packageName);
12827                    if (outInfo != null) {
12828                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12829                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12830                    }
12831                    updatePermissionsLPw(deletedPs.name, null, 0);
12832                    if (deletedPs.sharedUser != null) {
12833                        // Remove permissions associated with package. Since runtime
12834                        // permissions are per user we have to kill the removed package
12835                        // or packages running under the shared user of the removed
12836                        // package if revoking the permissions requested only by the removed
12837                        // package is successful and this causes a change in gids.
12838                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12839                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12840                                    userId);
12841                            if (userIdToKill == UserHandle.USER_ALL
12842                                    || userIdToKill >= UserHandle.USER_OWNER) {
12843                                // If gids changed for this user, kill all affected packages.
12844                                mHandler.post(new Runnable() {
12845                                    @Override
12846                                    public void run() {
12847                                        // This has to happen with no lock held.
12848                                        killApplication(deletedPs.name, deletedPs.appId,
12849                                                KILL_APP_REASON_GIDS_CHANGED);
12850                                    }
12851                                });
12852                                break;
12853                            }
12854                        }
12855                    }
12856                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12857                }
12858                // make sure to preserve per-user disabled state if this removal was just
12859                // a downgrade of a system app to the factory package
12860                if (allUserHandles != null && perUserInstalled != null) {
12861                    if (DEBUG_REMOVE) {
12862                        Slog.d(TAG, "Propagating install state across downgrade");
12863                    }
12864                    for (int i = 0; i < allUserHandles.length; i++) {
12865                        if (DEBUG_REMOVE) {
12866                            Slog.d(TAG, "    user " + allUserHandles[i]
12867                                    + " => " + perUserInstalled[i]);
12868                        }
12869                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12870                    }
12871                }
12872            }
12873            // can downgrade to reader
12874            if (writeSettings) {
12875                // Save settings now
12876                mSettings.writeLPr();
12877            }
12878        }
12879        if (outInfo != null) {
12880            // A user ID was deleted here. Go through all users and remove it
12881            // from KeyStore.
12882            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12883        }
12884    }
12885
12886    static boolean locationIsPrivileged(File path) {
12887        try {
12888            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12889                    .getCanonicalPath();
12890            return path.getCanonicalPath().startsWith(privilegedAppDir);
12891        } catch (IOException e) {
12892            Slog.e(TAG, "Unable to access code path " + path);
12893        }
12894        return false;
12895    }
12896
12897    /*
12898     * Tries to delete system package.
12899     */
12900    private boolean deleteSystemPackageLI(PackageSetting newPs,
12901            int[] allUserHandles, boolean[] perUserInstalled,
12902            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12903        final boolean applyUserRestrictions
12904                = (allUserHandles != null) && (perUserInstalled != null);
12905        PackageSetting disabledPs = null;
12906        // Confirm if the system package has been updated
12907        // An updated system app can be deleted. This will also have to restore
12908        // the system pkg from system partition
12909        // reader
12910        synchronized (mPackages) {
12911            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12912        }
12913        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12914                + " disabledPs=" + disabledPs);
12915        if (disabledPs == null) {
12916            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12917            return false;
12918        } else if (DEBUG_REMOVE) {
12919            Slog.d(TAG, "Deleting system pkg from data partition");
12920        }
12921        if (DEBUG_REMOVE) {
12922            if (applyUserRestrictions) {
12923                Slog.d(TAG, "Remembering install states:");
12924                for (int i = 0; i < allUserHandles.length; i++) {
12925                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12926                }
12927            }
12928        }
12929        // Delete the updated package
12930        outInfo.isRemovedPackageSystemUpdate = true;
12931        if (disabledPs.versionCode < newPs.versionCode) {
12932            // Delete data for downgrades
12933            flags &= ~PackageManager.DELETE_KEEP_DATA;
12934        } else {
12935            // Preserve data by setting flag
12936            flags |= PackageManager.DELETE_KEEP_DATA;
12937        }
12938        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12939                allUserHandles, perUserInstalled, outInfo, writeSettings);
12940        if (!ret) {
12941            return false;
12942        }
12943        // writer
12944        synchronized (mPackages) {
12945            // Reinstate the old system package
12946            mSettings.enableSystemPackageLPw(newPs.name);
12947            // Remove any native libraries from the upgraded package.
12948            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12949        }
12950        // Install the system package
12951        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12952        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12953        if (locationIsPrivileged(disabledPs.codePath)) {
12954            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12955        }
12956
12957        final PackageParser.Package newPkg;
12958        try {
12959            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12960        } catch (PackageManagerException e) {
12961            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12962            return false;
12963        }
12964
12965        // writer
12966        synchronized (mPackages) {
12967            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12968
12969            // Propagate the permissions state as we do not want to drop on the floor
12970            // runtime permissions. The update permissions method below will take
12971            // care of removing obsolete permissions and grant install permissions.
12972            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
12973            updatePermissionsLPw(newPkg.packageName, newPkg,
12974                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12975
12976            if (applyUserRestrictions) {
12977                if (DEBUG_REMOVE) {
12978                    Slog.d(TAG, "Propagating install state across reinstall");
12979                }
12980                for (int i = 0; i < allUserHandles.length; i++) {
12981                    if (DEBUG_REMOVE) {
12982                        Slog.d(TAG, "    user " + allUserHandles[i]
12983                                + " => " + perUserInstalled[i]);
12984                    }
12985                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12986
12987                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
12988                }
12989                // Regardless of writeSettings we need to ensure that this restriction
12990                // state propagation is persisted
12991                mSettings.writeAllUsersPackageRestrictionsLPr();
12992            }
12993            // can downgrade to reader here
12994            if (writeSettings) {
12995                mSettings.writeLPr();
12996            }
12997        }
12998        return true;
12999    }
13000
13001    private boolean deleteInstalledPackageLI(PackageSetting ps,
13002            boolean deleteCodeAndResources, int flags,
13003            int[] allUserHandles, boolean[] perUserInstalled,
13004            PackageRemovedInfo outInfo, boolean writeSettings) {
13005        if (outInfo != null) {
13006            outInfo.uid = ps.appId;
13007        }
13008
13009        // Delete package data from internal structures and also remove data if flag is set
13010        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13011
13012        // Delete application code and resources
13013        if (deleteCodeAndResources && (outInfo != null)) {
13014            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13015                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13016            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13017        }
13018        return true;
13019    }
13020
13021    @Override
13022    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13023            int userId) {
13024        mContext.enforceCallingOrSelfPermission(
13025                android.Manifest.permission.DELETE_PACKAGES, null);
13026        synchronized (mPackages) {
13027            PackageSetting ps = mSettings.mPackages.get(packageName);
13028            if (ps == null) {
13029                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13030                return false;
13031            }
13032            if (!ps.getInstalled(userId)) {
13033                // Can't block uninstall for an app that is not installed or enabled.
13034                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13035                return false;
13036            }
13037            ps.setBlockUninstall(blockUninstall, userId);
13038            mSettings.writePackageRestrictionsLPr(userId);
13039        }
13040        return true;
13041    }
13042
13043    @Override
13044    public boolean getBlockUninstallForUser(String packageName, int userId) {
13045        synchronized (mPackages) {
13046            PackageSetting ps = mSettings.mPackages.get(packageName);
13047            if (ps == null) {
13048                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13049                return false;
13050            }
13051            return ps.getBlockUninstall(userId);
13052        }
13053    }
13054
13055    /*
13056     * This method handles package deletion in general
13057     */
13058    private boolean deletePackageLI(String packageName, UserHandle user,
13059            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13060            int flags, PackageRemovedInfo outInfo,
13061            boolean writeSettings) {
13062        if (packageName == null) {
13063            Slog.w(TAG, "Attempt to delete null packageName.");
13064            return false;
13065        }
13066        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13067        PackageSetting ps;
13068        boolean dataOnly = false;
13069        int removeUser = -1;
13070        int appId = -1;
13071        synchronized (mPackages) {
13072            ps = mSettings.mPackages.get(packageName);
13073            if (ps == null) {
13074                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13075                return false;
13076            }
13077            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13078                    && user.getIdentifier() != UserHandle.USER_ALL) {
13079                // The caller is asking that the package only be deleted for a single
13080                // user.  To do this, we just mark its uninstalled state and delete
13081                // its data.  If this is a system app, we only allow this to happen if
13082                // they have set the special DELETE_SYSTEM_APP which requests different
13083                // semantics than normal for uninstalling system apps.
13084                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13085                final int userId = user.getIdentifier();
13086                ps.setUserState(userId,
13087                        COMPONENT_ENABLED_STATE_DEFAULT,
13088                        false, //installed
13089                        true,  //stopped
13090                        true,  //notLaunched
13091                        false, //hidden
13092                        null, null, null,
13093                        false, // blockUninstall
13094                        ps.readUserState(userId).domainVerificationStatus, 0);
13095                if (!isSystemApp(ps)) {
13096                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13097                        // Other user still have this package installed, so all
13098                        // we need to do is clear this user's data and save that
13099                        // it is uninstalled.
13100                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13101                        removeUser = user.getIdentifier();
13102                        appId = ps.appId;
13103                        scheduleWritePackageRestrictionsLocked(removeUser);
13104                    } else {
13105                        // We need to set it back to 'installed' so the uninstall
13106                        // broadcasts will be sent correctly.
13107                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13108                        ps.setInstalled(true, user.getIdentifier());
13109                    }
13110                } else {
13111                    // This is a system app, so we assume that the
13112                    // other users still have this package installed, so all
13113                    // we need to do is clear this user's data and save that
13114                    // it is uninstalled.
13115                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13116                    removeUser = user.getIdentifier();
13117                    appId = ps.appId;
13118                    scheduleWritePackageRestrictionsLocked(removeUser);
13119                }
13120            }
13121        }
13122
13123        if (removeUser >= 0) {
13124            // From above, we determined that we are deleting this only
13125            // for a single user.  Continue the work here.
13126            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13127            if (outInfo != null) {
13128                outInfo.removedPackage = packageName;
13129                outInfo.removedAppId = appId;
13130                outInfo.removedUsers = new int[] {removeUser};
13131            }
13132            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13133            removeKeystoreDataIfNeeded(removeUser, appId);
13134            schedulePackageCleaning(packageName, removeUser, false);
13135            synchronized (mPackages) {
13136                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13137                    scheduleWritePackageRestrictionsLocked(removeUser);
13138                }
13139                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13140            }
13141            return true;
13142        }
13143
13144        if (dataOnly) {
13145            // Delete application data first
13146            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13147            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13148            return true;
13149        }
13150
13151        boolean ret = false;
13152        if (isSystemApp(ps)) {
13153            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13154            // When an updated system application is deleted we delete the existing resources as well and
13155            // fall back to existing code in system partition
13156            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13157                    flags, outInfo, writeSettings);
13158        } else {
13159            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13160            // Kill application pre-emptively especially for apps on sd.
13161            killApplication(packageName, ps.appId, "uninstall pkg");
13162            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13163                    allUserHandles, perUserInstalled,
13164                    outInfo, writeSettings);
13165        }
13166
13167        return ret;
13168    }
13169
13170    private final class ClearStorageConnection implements ServiceConnection {
13171        IMediaContainerService mContainerService;
13172
13173        @Override
13174        public void onServiceConnected(ComponentName name, IBinder service) {
13175            synchronized (this) {
13176                mContainerService = IMediaContainerService.Stub.asInterface(service);
13177                notifyAll();
13178            }
13179        }
13180
13181        @Override
13182        public void onServiceDisconnected(ComponentName name) {
13183        }
13184    }
13185
13186    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13187        final boolean mounted;
13188        if (Environment.isExternalStorageEmulated()) {
13189            mounted = true;
13190        } else {
13191            final String status = Environment.getExternalStorageState();
13192
13193            mounted = status.equals(Environment.MEDIA_MOUNTED)
13194                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13195        }
13196
13197        if (!mounted) {
13198            return;
13199        }
13200
13201        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13202        int[] users;
13203        if (userId == UserHandle.USER_ALL) {
13204            users = sUserManager.getUserIds();
13205        } else {
13206            users = new int[] { userId };
13207        }
13208        final ClearStorageConnection conn = new ClearStorageConnection();
13209        if (mContext.bindServiceAsUser(
13210                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13211            try {
13212                for (int curUser : users) {
13213                    long timeout = SystemClock.uptimeMillis() + 5000;
13214                    synchronized (conn) {
13215                        long now = SystemClock.uptimeMillis();
13216                        while (conn.mContainerService == null && now < timeout) {
13217                            try {
13218                                conn.wait(timeout - now);
13219                            } catch (InterruptedException e) {
13220                            }
13221                        }
13222                    }
13223                    if (conn.mContainerService == null) {
13224                        return;
13225                    }
13226
13227                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13228                    clearDirectory(conn.mContainerService,
13229                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13230                    if (allData) {
13231                        clearDirectory(conn.mContainerService,
13232                                userEnv.buildExternalStorageAppDataDirs(packageName));
13233                        clearDirectory(conn.mContainerService,
13234                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13235                    }
13236                }
13237            } finally {
13238                mContext.unbindService(conn);
13239            }
13240        }
13241    }
13242
13243    @Override
13244    public void clearApplicationUserData(final String packageName,
13245            final IPackageDataObserver observer, final int userId) {
13246        mContext.enforceCallingOrSelfPermission(
13247                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13248        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13249        // Queue up an async operation since the package deletion may take a little while.
13250        mHandler.post(new Runnable() {
13251            public void run() {
13252                mHandler.removeCallbacks(this);
13253                final boolean succeeded;
13254                synchronized (mInstallLock) {
13255                    succeeded = clearApplicationUserDataLI(packageName, userId);
13256                }
13257                clearExternalStorageDataSync(packageName, userId, true);
13258                if (succeeded) {
13259                    // invoke DeviceStorageMonitor's update method to clear any notifications
13260                    DeviceStorageMonitorInternal
13261                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13262                    if (dsm != null) {
13263                        dsm.checkMemory();
13264                    }
13265                }
13266                if(observer != null) {
13267                    try {
13268                        observer.onRemoveCompleted(packageName, succeeded);
13269                    } catch (RemoteException e) {
13270                        Log.i(TAG, "Observer no longer exists.");
13271                    }
13272                } //end if observer
13273            } //end run
13274        });
13275    }
13276
13277    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13278        if (packageName == null) {
13279            Slog.w(TAG, "Attempt to delete null packageName.");
13280            return false;
13281        }
13282
13283        // Try finding details about the requested package
13284        PackageParser.Package pkg;
13285        synchronized (mPackages) {
13286            pkg = mPackages.get(packageName);
13287            if (pkg == null) {
13288                final PackageSetting ps = mSettings.mPackages.get(packageName);
13289                if (ps != null) {
13290                    pkg = ps.pkg;
13291                }
13292            }
13293
13294            if (pkg == null) {
13295                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13296                return false;
13297            }
13298
13299            PackageSetting ps = (PackageSetting) pkg.mExtras;
13300            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13301        }
13302
13303        // Always delete data directories for package, even if we found no other
13304        // record of app. This helps users recover from UID mismatches without
13305        // resorting to a full data wipe.
13306        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13307        if (retCode < 0) {
13308            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13309            return false;
13310        }
13311
13312        final int appId = pkg.applicationInfo.uid;
13313        removeKeystoreDataIfNeeded(userId, appId);
13314
13315        // Create a native library symlink only if we have native libraries
13316        // and if the native libraries are 32 bit libraries. We do not provide
13317        // this symlink for 64 bit libraries.
13318        if (pkg.applicationInfo.primaryCpuAbi != null &&
13319                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13320            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13321            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13322                    nativeLibPath, userId) < 0) {
13323                Slog.w(TAG, "Failed linking native library dir");
13324                return false;
13325            }
13326        }
13327
13328        return true;
13329    }
13330
13331    /**
13332     * Reverts user permission state changes (permissions and flags) in
13333     * all packages for a given user.
13334     *
13335     * @param userId The device user for which to do a reset.
13336     */
13337    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13338        final int packageCount = mPackages.size();
13339        for (int i = 0; i < packageCount; i++) {
13340            PackageParser.Package pkg = mPackages.valueAt(i);
13341            PackageSetting ps = (PackageSetting) pkg.mExtras;
13342            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13343        }
13344    }
13345
13346    /**
13347     * Reverts user permission state changes (permissions and flags).
13348     *
13349     * @param ps The package for which to reset.
13350     * @param userId The device user for which to do a reset.
13351     */
13352    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13353            final PackageSetting ps, final int userId) {
13354        if (ps.pkg == null) {
13355            return;
13356        }
13357
13358        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13359                | FLAG_PERMISSION_USER_FIXED
13360                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13361
13362        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13363                | FLAG_PERMISSION_POLICY_FIXED;
13364
13365        boolean writeInstallPermissions = false;
13366        boolean writeRuntimePermissions = false;
13367
13368        final int permissionCount = ps.pkg.requestedPermissions.size();
13369        for (int i = 0; i < permissionCount; i++) {
13370            String permission = ps.pkg.requestedPermissions.get(i);
13371
13372            BasePermission bp = mSettings.mPermissions.get(permission);
13373            if (bp == null) {
13374                continue;
13375            }
13376
13377            // If shared user we just reset the state to which only this app contributed.
13378            if (ps.sharedUser != null) {
13379                boolean used = false;
13380                final int packageCount = ps.sharedUser.packages.size();
13381                for (int j = 0; j < packageCount; j++) {
13382                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13383                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13384                            && pkg.pkg.requestedPermissions.contains(permission)) {
13385                        used = true;
13386                        break;
13387                    }
13388                }
13389                if (used) {
13390                    continue;
13391                }
13392            }
13393
13394            PermissionsState permissionsState = ps.getPermissionsState();
13395
13396            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13397
13398            // Always clear the user settable flags.
13399            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13400                    bp.name) != null;
13401            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13402                if (hasInstallState) {
13403                    writeInstallPermissions = true;
13404                } else {
13405                    writeRuntimePermissions = true;
13406                }
13407            }
13408
13409            // Below is only runtime permission handling.
13410            if (!bp.isRuntime()) {
13411                continue;
13412            }
13413
13414            // Never clobber system or policy.
13415            if ((oldFlags & policyOrSystemFlags) != 0) {
13416                continue;
13417            }
13418
13419            // If this permission was granted by default, make sure it is.
13420            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13421                if (permissionsState.grantRuntimePermission(bp, userId)
13422                        != PERMISSION_OPERATION_FAILURE) {
13423                    writeRuntimePermissions = true;
13424                }
13425            } else {
13426                // Otherwise, reset the permission.
13427                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13428                switch (revokeResult) {
13429                    case PERMISSION_OPERATION_SUCCESS: {
13430                        writeRuntimePermissions = true;
13431                    } break;
13432
13433                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13434                        writeRuntimePermissions = true;
13435                        final int appId = ps.appId;
13436                        mHandler.post(new Runnable() {
13437                            @Override
13438                            public void run() {
13439                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13440                            }
13441                        });
13442                    } break;
13443                }
13444            }
13445        }
13446
13447        // Synchronously write as we are taking permissions away.
13448        if (writeRuntimePermissions) {
13449            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13450        }
13451
13452        // Synchronously write as we are taking permissions away.
13453        if (writeInstallPermissions) {
13454            mSettings.writeLPr();
13455        }
13456    }
13457
13458    /**
13459     * Remove entries from the keystore daemon. Will only remove it if the
13460     * {@code appId} is valid.
13461     */
13462    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13463        if (appId < 0) {
13464            return;
13465        }
13466
13467        final KeyStore keyStore = KeyStore.getInstance();
13468        if (keyStore != null) {
13469            if (userId == UserHandle.USER_ALL) {
13470                for (final int individual : sUserManager.getUserIds()) {
13471                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13472                }
13473            } else {
13474                keyStore.clearUid(UserHandle.getUid(userId, appId));
13475            }
13476        } else {
13477            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13478        }
13479    }
13480
13481    @Override
13482    public void deleteApplicationCacheFiles(final String packageName,
13483            final IPackageDataObserver observer) {
13484        mContext.enforceCallingOrSelfPermission(
13485                android.Manifest.permission.DELETE_CACHE_FILES, null);
13486        // Queue up an async operation since the package deletion may take a little while.
13487        final int userId = UserHandle.getCallingUserId();
13488        mHandler.post(new Runnable() {
13489            public void run() {
13490                mHandler.removeCallbacks(this);
13491                final boolean succeded;
13492                synchronized (mInstallLock) {
13493                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13494                }
13495                clearExternalStorageDataSync(packageName, userId, false);
13496                if (observer != null) {
13497                    try {
13498                        observer.onRemoveCompleted(packageName, succeded);
13499                    } catch (RemoteException e) {
13500                        Log.i(TAG, "Observer no longer exists.");
13501                    }
13502                } //end if observer
13503            } //end run
13504        });
13505    }
13506
13507    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13508        if (packageName == null) {
13509            Slog.w(TAG, "Attempt to delete null packageName.");
13510            return false;
13511        }
13512        PackageParser.Package p;
13513        synchronized (mPackages) {
13514            p = mPackages.get(packageName);
13515        }
13516        if (p == null) {
13517            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13518            return false;
13519        }
13520        final ApplicationInfo applicationInfo = p.applicationInfo;
13521        if (applicationInfo == null) {
13522            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13523            return false;
13524        }
13525        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13526        if (retCode < 0) {
13527            Slog.w(TAG, "Couldn't remove cache files for package: "
13528                       + packageName + " u" + userId);
13529            return false;
13530        }
13531        return true;
13532    }
13533
13534    @Override
13535    public void getPackageSizeInfo(final String packageName, int userHandle,
13536            final IPackageStatsObserver observer) {
13537        mContext.enforceCallingOrSelfPermission(
13538                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13539        if (packageName == null) {
13540            throw new IllegalArgumentException("Attempt to get size of null packageName");
13541        }
13542
13543        PackageStats stats = new PackageStats(packageName, userHandle);
13544
13545        /*
13546         * Queue up an async operation since the package measurement may take a
13547         * little while.
13548         */
13549        Message msg = mHandler.obtainMessage(INIT_COPY);
13550        msg.obj = new MeasureParams(stats, observer);
13551        mHandler.sendMessage(msg);
13552    }
13553
13554    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13555            PackageStats pStats) {
13556        if (packageName == null) {
13557            Slog.w(TAG, "Attempt to get size of null packageName.");
13558            return false;
13559        }
13560        PackageParser.Package p;
13561        boolean dataOnly = false;
13562        String libDirRoot = null;
13563        String asecPath = null;
13564        PackageSetting ps = null;
13565        synchronized (mPackages) {
13566            p = mPackages.get(packageName);
13567            ps = mSettings.mPackages.get(packageName);
13568            if(p == null) {
13569                dataOnly = true;
13570                if((ps == null) || (ps.pkg == null)) {
13571                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13572                    return false;
13573                }
13574                p = ps.pkg;
13575            }
13576            if (ps != null) {
13577                libDirRoot = ps.legacyNativeLibraryPathString;
13578            }
13579            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13580                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13581                if (secureContainerId != null) {
13582                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13583                }
13584            }
13585        }
13586        String publicSrcDir = null;
13587        if(!dataOnly) {
13588            final ApplicationInfo applicationInfo = p.applicationInfo;
13589            if (applicationInfo == null) {
13590                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13591                return false;
13592            }
13593            if (p.isForwardLocked()) {
13594                publicSrcDir = applicationInfo.getBaseResourcePath();
13595            }
13596        }
13597        // TODO: extend to measure size of split APKs
13598        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13599        // not just the first level.
13600        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13601        // just the primary.
13602        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13603        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13604                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13605        if (res < 0) {
13606            return false;
13607        }
13608
13609        // Fix-up for forward-locked applications in ASEC containers.
13610        if (!isExternal(p)) {
13611            pStats.codeSize += pStats.externalCodeSize;
13612            pStats.externalCodeSize = 0L;
13613        }
13614
13615        return true;
13616    }
13617
13618
13619    @Override
13620    public void addPackageToPreferred(String packageName) {
13621        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13622    }
13623
13624    @Override
13625    public void removePackageFromPreferred(String packageName) {
13626        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13627    }
13628
13629    @Override
13630    public List<PackageInfo> getPreferredPackages(int flags) {
13631        return new ArrayList<PackageInfo>();
13632    }
13633
13634    private int getUidTargetSdkVersionLockedLPr(int uid) {
13635        Object obj = mSettings.getUserIdLPr(uid);
13636        if (obj instanceof SharedUserSetting) {
13637            final SharedUserSetting sus = (SharedUserSetting) obj;
13638            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13639            final Iterator<PackageSetting> it = sus.packages.iterator();
13640            while (it.hasNext()) {
13641                final PackageSetting ps = it.next();
13642                if (ps.pkg != null) {
13643                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13644                    if (v < vers) vers = v;
13645                }
13646            }
13647            return vers;
13648        } else if (obj instanceof PackageSetting) {
13649            final PackageSetting ps = (PackageSetting) obj;
13650            if (ps.pkg != null) {
13651                return ps.pkg.applicationInfo.targetSdkVersion;
13652            }
13653        }
13654        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13655    }
13656
13657    @Override
13658    public void addPreferredActivity(IntentFilter filter, int match,
13659            ComponentName[] set, ComponentName activity, int userId) {
13660        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13661                "Adding preferred");
13662    }
13663
13664    private void addPreferredActivityInternal(IntentFilter filter, int match,
13665            ComponentName[] set, ComponentName activity, boolean always, int userId,
13666            String opname) {
13667        // writer
13668        int callingUid = Binder.getCallingUid();
13669        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13670        if (filter.countActions() == 0) {
13671            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13672            return;
13673        }
13674        synchronized (mPackages) {
13675            if (mContext.checkCallingOrSelfPermission(
13676                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13677                    != PackageManager.PERMISSION_GRANTED) {
13678                if (getUidTargetSdkVersionLockedLPr(callingUid)
13679                        < Build.VERSION_CODES.FROYO) {
13680                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13681                            + callingUid);
13682                    return;
13683                }
13684                mContext.enforceCallingOrSelfPermission(
13685                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13686            }
13687
13688            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13689            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13690                    + userId + ":");
13691            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13692            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13693            scheduleWritePackageRestrictionsLocked(userId);
13694        }
13695    }
13696
13697    @Override
13698    public void replacePreferredActivity(IntentFilter filter, int match,
13699            ComponentName[] set, ComponentName activity, int userId) {
13700        if (filter.countActions() != 1) {
13701            throw new IllegalArgumentException(
13702                    "replacePreferredActivity expects filter to have only 1 action.");
13703        }
13704        if (filter.countDataAuthorities() != 0
13705                || filter.countDataPaths() != 0
13706                || filter.countDataSchemes() > 1
13707                || filter.countDataTypes() != 0) {
13708            throw new IllegalArgumentException(
13709                    "replacePreferredActivity expects filter to have no data authorities, " +
13710                    "paths, or types; and at most one scheme.");
13711        }
13712
13713        final int callingUid = Binder.getCallingUid();
13714        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13715        synchronized (mPackages) {
13716            if (mContext.checkCallingOrSelfPermission(
13717                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13718                    != PackageManager.PERMISSION_GRANTED) {
13719                if (getUidTargetSdkVersionLockedLPr(callingUid)
13720                        < Build.VERSION_CODES.FROYO) {
13721                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13722                            + Binder.getCallingUid());
13723                    return;
13724                }
13725                mContext.enforceCallingOrSelfPermission(
13726                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13727            }
13728
13729            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13730            if (pir != null) {
13731                // Get all of the existing entries that exactly match this filter.
13732                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13733                if (existing != null && existing.size() == 1) {
13734                    PreferredActivity cur = existing.get(0);
13735                    if (DEBUG_PREFERRED) {
13736                        Slog.i(TAG, "Checking replace of preferred:");
13737                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13738                        if (!cur.mPref.mAlways) {
13739                            Slog.i(TAG, "  -- CUR; not mAlways!");
13740                        } else {
13741                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13742                            Slog.i(TAG, "  -- CUR: mSet="
13743                                    + Arrays.toString(cur.mPref.mSetComponents));
13744                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13745                            Slog.i(TAG, "  -- NEW: mMatch="
13746                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13747                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13748                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13749                        }
13750                    }
13751                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13752                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13753                            && cur.mPref.sameSet(set)) {
13754                        // Setting the preferred activity to what it happens to be already
13755                        if (DEBUG_PREFERRED) {
13756                            Slog.i(TAG, "Replacing with same preferred activity "
13757                                    + cur.mPref.mShortComponent + " for user "
13758                                    + userId + ":");
13759                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13760                        }
13761                        return;
13762                    }
13763                }
13764
13765                if (existing != null) {
13766                    if (DEBUG_PREFERRED) {
13767                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13768                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13769                    }
13770                    for (int i = 0; i < existing.size(); i++) {
13771                        PreferredActivity pa = existing.get(i);
13772                        if (DEBUG_PREFERRED) {
13773                            Slog.i(TAG, "Removing existing preferred activity "
13774                                    + pa.mPref.mComponent + ":");
13775                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13776                        }
13777                        pir.removeFilter(pa);
13778                    }
13779                }
13780            }
13781            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13782                    "Replacing preferred");
13783        }
13784    }
13785
13786    @Override
13787    public void clearPackagePreferredActivities(String packageName) {
13788        final int uid = Binder.getCallingUid();
13789        // writer
13790        synchronized (mPackages) {
13791            PackageParser.Package pkg = mPackages.get(packageName);
13792            if (pkg == null || pkg.applicationInfo.uid != uid) {
13793                if (mContext.checkCallingOrSelfPermission(
13794                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13795                        != PackageManager.PERMISSION_GRANTED) {
13796                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13797                            < Build.VERSION_CODES.FROYO) {
13798                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13799                                + Binder.getCallingUid());
13800                        return;
13801                    }
13802                    mContext.enforceCallingOrSelfPermission(
13803                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13804                }
13805            }
13806
13807            int user = UserHandle.getCallingUserId();
13808            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13809                scheduleWritePackageRestrictionsLocked(user);
13810            }
13811        }
13812    }
13813
13814    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13815    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13816        ArrayList<PreferredActivity> removed = null;
13817        boolean changed = false;
13818        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13819            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13820            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13821            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13822                continue;
13823            }
13824            Iterator<PreferredActivity> it = pir.filterIterator();
13825            while (it.hasNext()) {
13826                PreferredActivity pa = it.next();
13827                // Mark entry for removal only if it matches the package name
13828                // and the entry is of type "always".
13829                if (packageName == null ||
13830                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13831                                && pa.mPref.mAlways)) {
13832                    if (removed == null) {
13833                        removed = new ArrayList<PreferredActivity>();
13834                    }
13835                    removed.add(pa);
13836                }
13837            }
13838            if (removed != null) {
13839                for (int j=0; j<removed.size(); j++) {
13840                    PreferredActivity pa = removed.get(j);
13841                    pir.removeFilter(pa);
13842                }
13843                changed = true;
13844            }
13845        }
13846        return changed;
13847    }
13848
13849    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13850    private void clearIntentFilterVerificationsLPw(int userId) {
13851        final int packageCount = mPackages.size();
13852        for (int i = 0; i < packageCount; i++) {
13853            PackageParser.Package pkg = mPackages.valueAt(i);
13854            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13855        }
13856    }
13857
13858    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13859    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13860        if (userId == UserHandle.USER_ALL) {
13861            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13862                    sUserManager.getUserIds())) {
13863                for (int oneUserId : sUserManager.getUserIds()) {
13864                    scheduleWritePackageRestrictionsLocked(oneUserId);
13865                }
13866            }
13867        } else {
13868            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13869                scheduleWritePackageRestrictionsLocked(userId);
13870            }
13871        }
13872    }
13873
13874    void clearDefaultBrowserIfNeeded(String packageName) {
13875        for (int oneUserId : sUserManager.getUserIds()) {
13876            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13877            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13878            if (packageName.equals(defaultBrowserPackageName)) {
13879                setDefaultBrowserPackageName(null, oneUserId);
13880            }
13881        }
13882    }
13883
13884    @Override
13885    public void resetApplicationPreferences(int userId) {
13886        mContext.enforceCallingOrSelfPermission(
13887                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13888        // writer
13889        synchronized (mPackages) {
13890            final long identity = Binder.clearCallingIdentity();
13891            try {
13892                clearPackagePreferredActivitiesLPw(null, userId);
13893                mSettings.applyDefaultPreferredAppsLPw(this, userId);
13894                // TODO: We have to reset the default SMS and Phone. This requires
13895                // significant refactoring to keep all default apps in the package
13896                // manager (cleaner but more work) or have the services provide
13897                // callbacks to the package manager to request a default app reset.
13898                applyFactoryDefaultBrowserLPw(userId);
13899                clearIntentFilterVerificationsLPw(userId);
13900                primeDomainVerificationsLPw(userId);
13901                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
13902                scheduleWritePackageRestrictionsLocked(userId);
13903            } finally {
13904                Binder.restoreCallingIdentity(identity);
13905            }
13906        }
13907    }
13908
13909    @Override
13910    public int getPreferredActivities(List<IntentFilter> outFilters,
13911            List<ComponentName> outActivities, String packageName) {
13912
13913        int num = 0;
13914        final int userId = UserHandle.getCallingUserId();
13915        // reader
13916        synchronized (mPackages) {
13917            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13918            if (pir != null) {
13919                final Iterator<PreferredActivity> it = pir.filterIterator();
13920                while (it.hasNext()) {
13921                    final PreferredActivity pa = it.next();
13922                    if (packageName == null
13923                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13924                                    && pa.mPref.mAlways)) {
13925                        if (outFilters != null) {
13926                            outFilters.add(new IntentFilter(pa));
13927                        }
13928                        if (outActivities != null) {
13929                            outActivities.add(pa.mPref.mComponent);
13930                        }
13931                    }
13932                }
13933            }
13934        }
13935
13936        return num;
13937    }
13938
13939    @Override
13940    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13941            int userId) {
13942        int callingUid = Binder.getCallingUid();
13943        if (callingUid != Process.SYSTEM_UID) {
13944            throw new SecurityException(
13945                    "addPersistentPreferredActivity can only be run by the system");
13946        }
13947        if (filter.countActions() == 0) {
13948            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13949            return;
13950        }
13951        synchronized (mPackages) {
13952            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13953                    " :");
13954            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13955            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13956                    new PersistentPreferredActivity(filter, activity));
13957            scheduleWritePackageRestrictionsLocked(userId);
13958        }
13959    }
13960
13961    @Override
13962    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13963        int callingUid = Binder.getCallingUid();
13964        if (callingUid != Process.SYSTEM_UID) {
13965            throw new SecurityException(
13966                    "clearPackagePersistentPreferredActivities can only be run by the system");
13967        }
13968        ArrayList<PersistentPreferredActivity> removed = null;
13969        boolean changed = false;
13970        synchronized (mPackages) {
13971            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13972                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13973                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13974                        .valueAt(i);
13975                if (userId != thisUserId) {
13976                    continue;
13977                }
13978                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13979                while (it.hasNext()) {
13980                    PersistentPreferredActivity ppa = it.next();
13981                    // Mark entry for removal only if it matches the package name.
13982                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13983                        if (removed == null) {
13984                            removed = new ArrayList<PersistentPreferredActivity>();
13985                        }
13986                        removed.add(ppa);
13987                    }
13988                }
13989                if (removed != null) {
13990                    for (int j=0; j<removed.size(); j++) {
13991                        PersistentPreferredActivity ppa = removed.get(j);
13992                        ppir.removeFilter(ppa);
13993                    }
13994                    changed = true;
13995                }
13996            }
13997
13998            if (changed) {
13999                scheduleWritePackageRestrictionsLocked(userId);
14000            }
14001        }
14002    }
14003
14004    /**
14005     * Common machinery for picking apart a restored XML blob and passing
14006     * it to a caller-supplied functor to be applied to the running system.
14007     */
14008    private void restoreFromXml(XmlPullParser parser, int userId,
14009            String expectedStartTag, BlobXmlRestorer functor)
14010            throws IOException, XmlPullParserException {
14011        int type;
14012        while ((type = parser.next()) != XmlPullParser.START_TAG
14013                && type != XmlPullParser.END_DOCUMENT) {
14014        }
14015        if (type != XmlPullParser.START_TAG) {
14016            // oops didn't find a start tag?!
14017            if (DEBUG_BACKUP) {
14018                Slog.e(TAG, "Didn't find start tag during restore");
14019            }
14020            return;
14021        }
14022
14023        // this is supposed to be TAG_PREFERRED_BACKUP
14024        if (!expectedStartTag.equals(parser.getName())) {
14025            if (DEBUG_BACKUP) {
14026                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14027            }
14028            return;
14029        }
14030
14031        // skip interfering stuff, then we're aligned with the backing implementation
14032        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14033        functor.apply(parser, userId);
14034    }
14035
14036    private interface BlobXmlRestorer {
14037        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14038    }
14039
14040    /**
14041     * Non-Binder method, support for the backup/restore mechanism: write the
14042     * full set of preferred activities in its canonical XML format.  Returns the
14043     * XML output as a byte array, or null if there is none.
14044     */
14045    @Override
14046    public byte[] getPreferredActivityBackup(int userId) {
14047        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14048            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14049        }
14050
14051        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14052        try {
14053            final XmlSerializer serializer = new FastXmlSerializer();
14054            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14055            serializer.startDocument(null, true);
14056            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14057
14058            synchronized (mPackages) {
14059                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14060            }
14061
14062            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14063            serializer.endDocument();
14064            serializer.flush();
14065        } catch (Exception e) {
14066            if (DEBUG_BACKUP) {
14067                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14068            }
14069            return null;
14070        }
14071
14072        return dataStream.toByteArray();
14073    }
14074
14075    @Override
14076    public void restorePreferredActivities(byte[] backup, int userId) {
14077        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14078            throw new SecurityException("Only the system may call restorePreferredActivities()");
14079        }
14080
14081        try {
14082            final XmlPullParser parser = Xml.newPullParser();
14083            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14084            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14085                    new BlobXmlRestorer() {
14086                        @Override
14087                        public void apply(XmlPullParser parser, int userId)
14088                                throws XmlPullParserException, IOException {
14089                            synchronized (mPackages) {
14090                                mSettings.readPreferredActivitiesLPw(parser, userId);
14091                            }
14092                        }
14093                    } );
14094        } catch (Exception e) {
14095            if (DEBUG_BACKUP) {
14096                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14097            }
14098        }
14099    }
14100
14101    /**
14102     * Non-Binder method, support for the backup/restore mechanism: write the
14103     * default browser (etc) settings in its canonical XML format.  Returns the default
14104     * browser XML representation as a byte array, or null if there is none.
14105     */
14106    @Override
14107    public byte[] getDefaultAppsBackup(int userId) {
14108        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14109            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14110        }
14111
14112        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14113        try {
14114            final XmlSerializer serializer = new FastXmlSerializer();
14115            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14116            serializer.startDocument(null, true);
14117            serializer.startTag(null, TAG_DEFAULT_APPS);
14118
14119            synchronized (mPackages) {
14120                mSettings.writeDefaultAppsLPr(serializer, userId);
14121            }
14122
14123            serializer.endTag(null, TAG_DEFAULT_APPS);
14124            serializer.endDocument();
14125            serializer.flush();
14126        } catch (Exception e) {
14127            if (DEBUG_BACKUP) {
14128                Slog.e(TAG, "Unable to write default apps for backup", e);
14129            }
14130            return null;
14131        }
14132
14133        return dataStream.toByteArray();
14134    }
14135
14136    @Override
14137    public void restoreDefaultApps(byte[] backup, int userId) {
14138        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14139            throw new SecurityException("Only the system may call restoreDefaultApps()");
14140        }
14141
14142        try {
14143            final XmlPullParser parser = Xml.newPullParser();
14144            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14145            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14146                    new BlobXmlRestorer() {
14147                        @Override
14148                        public void apply(XmlPullParser parser, int userId)
14149                                throws XmlPullParserException, IOException {
14150                            synchronized (mPackages) {
14151                                mSettings.readDefaultAppsLPw(parser, userId);
14152                            }
14153                        }
14154                    } );
14155        } catch (Exception e) {
14156            if (DEBUG_BACKUP) {
14157                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14158            }
14159        }
14160    }
14161
14162    @Override
14163    public byte[] getIntentFilterVerificationBackup(int userId) {
14164        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14165            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14166        }
14167
14168        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14169        try {
14170            final XmlSerializer serializer = new FastXmlSerializer();
14171            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14172            serializer.startDocument(null, true);
14173            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14174
14175            synchronized (mPackages) {
14176                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14177            }
14178
14179            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14180            serializer.endDocument();
14181            serializer.flush();
14182        } catch (Exception e) {
14183            if (DEBUG_BACKUP) {
14184                Slog.e(TAG, "Unable to write default apps for backup", e);
14185            }
14186            return null;
14187        }
14188
14189        return dataStream.toByteArray();
14190    }
14191
14192    @Override
14193    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14194        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14195            throw new SecurityException("Only the system may call restorePreferredActivities()");
14196        }
14197
14198        try {
14199            final XmlPullParser parser = Xml.newPullParser();
14200            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14201            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14202                    new BlobXmlRestorer() {
14203                        @Override
14204                        public void apply(XmlPullParser parser, int userId)
14205                                throws XmlPullParserException, IOException {
14206                            synchronized (mPackages) {
14207                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14208                                mSettings.writeLPr();
14209                            }
14210                        }
14211                    } );
14212        } catch (Exception e) {
14213            if (DEBUG_BACKUP) {
14214                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14215            }
14216        }
14217    }
14218
14219    @Override
14220    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14221            int sourceUserId, int targetUserId, int flags) {
14222        mContext.enforceCallingOrSelfPermission(
14223                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14224        int callingUid = Binder.getCallingUid();
14225        enforceOwnerRights(ownerPackage, callingUid);
14226        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14227        if (intentFilter.countActions() == 0) {
14228            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14229            return;
14230        }
14231        synchronized (mPackages) {
14232            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14233                    ownerPackage, targetUserId, flags);
14234            CrossProfileIntentResolver resolver =
14235                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14236            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14237            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14238            if (existing != null) {
14239                int size = existing.size();
14240                for (int i = 0; i < size; i++) {
14241                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14242                        return;
14243                    }
14244                }
14245            }
14246            resolver.addFilter(newFilter);
14247            scheduleWritePackageRestrictionsLocked(sourceUserId);
14248        }
14249    }
14250
14251    @Override
14252    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14253        mContext.enforceCallingOrSelfPermission(
14254                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14255        int callingUid = Binder.getCallingUid();
14256        enforceOwnerRights(ownerPackage, callingUid);
14257        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14258        synchronized (mPackages) {
14259            CrossProfileIntentResolver resolver =
14260                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14261            ArraySet<CrossProfileIntentFilter> set =
14262                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14263            for (CrossProfileIntentFilter filter : set) {
14264                if (filter.getOwnerPackage().equals(ownerPackage)) {
14265                    resolver.removeFilter(filter);
14266                }
14267            }
14268            scheduleWritePackageRestrictionsLocked(sourceUserId);
14269        }
14270    }
14271
14272    // Enforcing that callingUid is owning pkg on userId
14273    private void enforceOwnerRights(String pkg, int callingUid) {
14274        // The system owns everything.
14275        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14276            return;
14277        }
14278        int callingUserId = UserHandle.getUserId(callingUid);
14279        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14280        if (pi == null) {
14281            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14282                    + callingUserId);
14283        }
14284        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14285            throw new SecurityException("Calling uid " + callingUid
14286                    + " does not own package " + pkg);
14287        }
14288    }
14289
14290    @Override
14291    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14292        Intent intent = new Intent(Intent.ACTION_MAIN);
14293        intent.addCategory(Intent.CATEGORY_HOME);
14294
14295        final int callingUserId = UserHandle.getCallingUserId();
14296        List<ResolveInfo> list = queryIntentActivities(intent, null,
14297                PackageManager.GET_META_DATA, callingUserId);
14298        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14299                true, false, false, callingUserId);
14300
14301        allHomeCandidates.clear();
14302        if (list != null) {
14303            for (ResolveInfo ri : list) {
14304                allHomeCandidates.add(ri);
14305            }
14306        }
14307        return (preferred == null || preferred.activityInfo == null)
14308                ? null
14309                : new ComponentName(preferred.activityInfo.packageName,
14310                        preferred.activityInfo.name);
14311    }
14312
14313    @Override
14314    public void setApplicationEnabledSetting(String appPackageName,
14315            int newState, int flags, int userId, String callingPackage) {
14316        if (!sUserManager.exists(userId)) return;
14317        if (callingPackage == null) {
14318            callingPackage = Integer.toString(Binder.getCallingUid());
14319        }
14320        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14321    }
14322
14323    @Override
14324    public void setComponentEnabledSetting(ComponentName componentName,
14325            int newState, int flags, int userId) {
14326        if (!sUserManager.exists(userId)) return;
14327        setEnabledSetting(componentName.getPackageName(),
14328                componentName.getClassName(), newState, flags, userId, null);
14329    }
14330
14331    private void setEnabledSetting(final String packageName, String className, int newState,
14332            final int flags, int userId, String callingPackage) {
14333        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14334              || newState == COMPONENT_ENABLED_STATE_ENABLED
14335              || newState == COMPONENT_ENABLED_STATE_DISABLED
14336              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14337              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14338            throw new IllegalArgumentException("Invalid new component state: "
14339                    + newState);
14340        }
14341        PackageSetting pkgSetting;
14342        final int uid = Binder.getCallingUid();
14343        final int permission = mContext.checkCallingOrSelfPermission(
14344                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14345        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14346        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14347        boolean sendNow = false;
14348        boolean isApp = (className == null);
14349        String componentName = isApp ? packageName : className;
14350        int packageUid = -1;
14351        ArrayList<String> components;
14352
14353        // writer
14354        synchronized (mPackages) {
14355            pkgSetting = mSettings.mPackages.get(packageName);
14356            if (pkgSetting == null) {
14357                if (className == null) {
14358                    throw new IllegalArgumentException(
14359                            "Unknown package: " + packageName);
14360                }
14361                throw new IllegalArgumentException(
14362                        "Unknown component: " + packageName
14363                        + "/" + className);
14364            }
14365            // Allow root and verify that userId is not being specified by a different user
14366            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14367                throw new SecurityException(
14368                        "Permission Denial: attempt to change component state from pid="
14369                        + Binder.getCallingPid()
14370                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14371            }
14372            if (className == null) {
14373                // We're dealing with an application/package level state change
14374                if (pkgSetting.getEnabled(userId) == newState) {
14375                    // Nothing to do
14376                    return;
14377                }
14378                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14379                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14380                    // Don't care about who enables an app.
14381                    callingPackage = null;
14382                }
14383                pkgSetting.setEnabled(newState, userId, callingPackage);
14384                // pkgSetting.pkg.mSetEnabled = newState;
14385            } else {
14386                // We're dealing with a component level state change
14387                // First, verify that this is a valid class name.
14388                PackageParser.Package pkg = pkgSetting.pkg;
14389                if (pkg == null || !pkg.hasComponentClassName(className)) {
14390                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14391                        throw new IllegalArgumentException("Component class " + className
14392                                + " does not exist in " + packageName);
14393                    } else {
14394                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14395                                + className + " does not exist in " + packageName);
14396                    }
14397                }
14398                switch (newState) {
14399                case COMPONENT_ENABLED_STATE_ENABLED:
14400                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14401                        return;
14402                    }
14403                    break;
14404                case COMPONENT_ENABLED_STATE_DISABLED:
14405                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14406                        return;
14407                    }
14408                    break;
14409                case COMPONENT_ENABLED_STATE_DEFAULT:
14410                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14411                        return;
14412                    }
14413                    break;
14414                default:
14415                    Slog.e(TAG, "Invalid new component state: " + newState);
14416                    return;
14417                }
14418            }
14419            scheduleWritePackageRestrictionsLocked(userId);
14420            components = mPendingBroadcasts.get(userId, packageName);
14421            final boolean newPackage = components == null;
14422            if (newPackage) {
14423                components = new ArrayList<String>();
14424            }
14425            if (!components.contains(componentName)) {
14426                components.add(componentName);
14427            }
14428            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14429                sendNow = true;
14430                // Purge entry from pending broadcast list if another one exists already
14431                // since we are sending one right away.
14432                mPendingBroadcasts.remove(userId, packageName);
14433            } else {
14434                if (newPackage) {
14435                    mPendingBroadcasts.put(userId, packageName, components);
14436                }
14437                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14438                    // Schedule a message
14439                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14440                }
14441            }
14442        }
14443
14444        long callingId = Binder.clearCallingIdentity();
14445        try {
14446            if (sendNow) {
14447                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14448                sendPackageChangedBroadcast(packageName,
14449                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14450            }
14451        } finally {
14452            Binder.restoreCallingIdentity(callingId);
14453        }
14454    }
14455
14456    private void sendPackageChangedBroadcast(String packageName,
14457            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14458        if (DEBUG_INSTALL)
14459            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14460                    + componentNames);
14461        Bundle extras = new Bundle(4);
14462        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14463        String nameList[] = new String[componentNames.size()];
14464        componentNames.toArray(nameList);
14465        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14466        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14467        extras.putInt(Intent.EXTRA_UID, packageUid);
14468        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14469                new int[] {UserHandle.getUserId(packageUid)});
14470    }
14471
14472    @Override
14473    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14474        if (!sUserManager.exists(userId)) return;
14475        final int uid = Binder.getCallingUid();
14476        final int permission = mContext.checkCallingOrSelfPermission(
14477                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14478        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14479        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14480        // writer
14481        synchronized (mPackages) {
14482            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14483                    allowedByPermission, uid, userId)) {
14484                scheduleWritePackageRestrictionsLocked(userId);
14485            }
14486        }
14487    }
14488
14489    @Override
14490    public String getInstallerPackageName(String packageName) {
14491        // reader
14492        synchronized (mPackages) {
14493            return mSettings.getInstallerPackageNameLPr(packageName);
14494        }
14495    }
14496
14497    @Override
14498    public int getApplicationEnabledSetting(String packageName, int userId) {
14499        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14500        int uid = Binder.getCallingUid();
14501        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14502        // reader
14503        synchronized (mPackages) {
14504            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14505        }
14506    }
14507
14508    @Override
14509    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14510        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14511        int uid = Binder.getCallingUid();
14512        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14513        // reader
14514        synchronized (mPackages) {
14515            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14516        }
14517    }
14518
14519    @Override
14520    public void enterSafeMode() {
14521        enforceSystemOrRoot("Only the system can request entering safe mode");
14522
14523        if (!mSystemReady) {
14524            mSafeMode = true;
14525        }
14526    }
14527
14528    @Override
14529    public void systemReady() {
14530        mSystemReady = true;
14531
14532        // Read the compatibilty setting when the system is ready.
14533        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14534                mContext.getContentResolver(),
14535                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14536        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14537        if (DEBUG_SETTINGS) {
14538            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14539        }
14540
14541        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14542
14543        synchronized (mPackages) {
14544            // Verify that all of the preferred activity components actually
14545            // exist.  It is possible for applications to be updated and at
14546            // that point remove a previously declared activity component that
14547            // had been set as a preferred activity.  We try to clean this up
14548            // the next time we encounter that preferred activity, but it is
14549            // possible for the user flow to never be able to return to that
14550            // situation so here we do a sanity check to make sure we haven't
14551            // left any junk around.
14552            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14553            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14554                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14555                removed.clear();
14556                for (PreferredActivity pa : pir.filterSet()) {
14557                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14558                        removed.add(pa);
14559                    }
14560                }
14561                if (removed.size() > 0) {
14562                    for (int r=0; r<removed.size(); r++) {
14563                        PreferredActivity pa = removed.get(r);
14564                        Slog.w(TAG, "Removing dangling preferred activity: "
14565                                + pa.mPref.mComponent);
14566                        pir.removeFilter(pa);
14567                    }
14568                    mSettings.writePackageRestrictionsLPr(
14569                            mSettings.mPreferredActivities.keyAt(i));
14570                }
14571            }
14572
14573            for (int userId : UserManagerService.getInstance().getUserIds()) {
14574                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14575                    grantPermissionsUserIds = ArrayUtils.appendInt(
14576                            grantPermissionsUserIds, userId);
14577                }
14578            }
14579        }
14580        sUserManager.systemReady();
14581
14582        // If we upgraded grant all default permissions before kicking off.
14583        for (int userId : grantPermissionsUserIds) {
14584            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14585        }
14586
14587        // Kick off any messages waiting for system ready
14588        if (mPostSystemReadyMessages != null) {
14589            for (Message msg : mPostSystemReadyMessages) {
14590                msg.sendToTarget();
14591            }
14592            mPostSystemReadyMessages = null;
14593        }
14594
14595        // Watch for external volumes that come and go over time
14596        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14597        storage.registerListener(mStorageListener);
14598
14599        mInstallerService.systemReady();
14600        mPackageDexOptimizer.systemReady();
14601
14602        MountServiceInternal mountServiceInternal = LocalServices.getService(
14603                MountServiceInternal.class);
14604        mountServiceInternal.addExternalStoragePolicy(
14605                new MountServiceInternal.ExternalStorageMountPolicy() {
14606            @Override
14607            public int getMountMode(int uid, String packageName) {
14608                if (Process.isIsolated(uid)) {
14609                    return Zygote.MOUNT_EXTERNAL_NONE;
14610                }
14611                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14612                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14613                }
14614                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14615                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14616                }
14617                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14618                    return Zygote.MOUNT_EXTERNAL_READ;
14619                }
14620                return Zygote.MOUNT_EXTERNAL_WRITE;
14621            }
14622
14623            @Override
14624            public boolean hasExternalStorage(int uid, String packageName) {
14625                return true;
14626            }
14627        });
14628    }
14629
14630    @Override
14631    public boolean isSafeMode() {
14632        return mSafeMode;
14633    }
14634
14635    @Override
14636    public boolean hasSystemUidErrors() {
14637        return mHasSystemUidErrors;
14638    }
14639
14640    static String arrayToString(int[] array) {
14641        StringBuffer buf = new StringBuffer(128);
14642        buf.append('[');
14643        if (array != null) {
14644            for (int i=0; i<array.length; i++) {
14645                if (i > 0) buf.append(", ");
14646                buf.append(array[i]);
14647            }
14648        }
14649        buf.append(']');
14650        return buf.toString();
14651    }
14652
14653    static class DumpState {
14654        public static final int DUMP_LIBS = 1 << 0;
14655        public static final int DUMP_FEATURES = 1 << 1;
14656        public static final int DUMP_RESOLVERS = 1 << 2;
14657        public static final int DUMP_PERMISSIONS = 1 << 3;
14658        public static final int DUMP_PACKAGES = 1 << 4;
14659        public static final int DUMP_SHARED_USERS = 1 << 5;
14660        public static final int DUMP_MESSAGES = 1 << 6;
14661        public static final int DUMP_PROVIDERS = 1 << 7;
14662        public static final int DUMP_VERIFIERS = 1 << 8;
14663        public static final int DUMP_PREFERRED = 1 << 9;
14664        public static final int DUMP_PREFERRED_XML = 1 << 10;
14665        public static final int DUMP_KEYSETS = 1 << 11;
14666        public static final int DUMP_VERSION = 1 << 12;
14667        public static final int DUMP_INSTALLS = 1 << 13;
14668        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14669        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14670
14671        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14672
14673        private int mTypes;
14674
14675        private int mOptions;
14676
14677        private boolean mTitlePrinted;
14678
14679        private SharedUserSetting mSharedUser;
14680
14681        public boolean isDumping(int type) {
14682            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14683                return true;
14684            }
14685
14686            return (mTypes & type) != 0;
14687        }
14688
14689        public void setDump(int type) {
14690            mTypes |= type;
14691        }
14692
14693        public boolean isOptionEnabled(int option) {
14694            return (mOptions & option) != 0;
14695        }
14696
14697        public void setOptionEnabled(int option) {
14698            mOptions |= option;
14699        }
14700
14701        public boolean onTitlePrinted() {
14702            final boolean printed = mTitlePrinted;
14703            mTitlePrinted = true;
14704            return printed;
14705        }
14706
14707        public boolean getTitlePrinted() {
14708            return mTitlePrinted;
14709        }
14710
14711        public void setTitlePrinted(boolean enabled) {
14712            mTitlePrinted = enabled;
14713        }
14714
14715        public SharedUserSetting getSharedUser() {
14716            return mSharedUser;
14717        }
14718
14719        public void setSharedUser(SharedUserSetting user) {
14720            mSharedUser = user;
14721        }
14722    }
14723
14724    @Override
14725    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14726        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14727                != PackageManager.PERMISSION_GRANTED) {
14728            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14729                    + Binder.getCallingPid()
14730                    + ", uid=" + Binder.getCallingUid()
14731                    + " without permission "
14732                    + android.Manifest.permission.DUMP);
14733            return;
14734        }
14735
14736        DumpState dumpState = new DumpState();
14737        boolean fullPreferred = false;
14738        boolean checkin = false;
14739
14740        String packageName = null;
14741        ArraySet<String> permissionNames = null;
14742
14743        int opti = 0;
14744        while (opti < args.length) {
14745            String opt = args[opti];
14746            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14747                break;
14748            }
14749            opti++;
14750
14751            if ("-a".equals(opt)) {
14752                // Right now we only know how to print all.
14753            } else if ("-h".equals(opt)) {
14754                pw.println("Package manager dump options:");
14755                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14756                pw.println("    --checkin: dump for a checkin");
14757                pw.println("    -f: print details of intent filters");
14758                pw.println("    -h: print this help");
14759                pw.println("  cmd may be one of:");
14760                pw.println("    l[ibraries]: list known shared libraries");
14761                pw.println("    f[ibraries]: list device features");
14762                pw.println("    k[eysets]: print known keysets");
14763                pw.println("    r[esolvers]: dump intent resolvers");
14764                pw.println("    perm[issions]: dump permissions");
14765                pw.println("    permission [name ...]: dump declaration and use of given permission");
14766                pw.println("    pref[erred]: print preferred package settings");
14767                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14768                pw.println("    prov[iders]: dump content providers");
14769                pw.println("    p[ackages]: dump installed packages");
14770                pw.println("    s[hared-users]: dump shared user IDs");
14771                pw.println("    m[essages]: print collected runtime messages");
14772                pw.println("    v[erifiers]: print package verifier info");
14773                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14774                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14775                pw.println("    version: print database version info");
14776                pw.println("    write: write current settings now");
14777                pw.println("    installs: details about install sessions");
14778                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
14779                pw.println("    <package.name>: info about given package");
14780                return;
14781            } else if ("--checkin".equals(opt)) {
14782                checkin = true;
14783            } else if ("-f".equals(opt)) {
14784                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14785            } else {
14786                pw.println("Unknown argument: " + opt + "; use -h for help");
14787            }
14788        }
14789
14790        // Is the caller requesting to dump a particular piece of data?
14791        if (opti < args.length) {
14792            String cmd = args[opti];
14793            opti++;
14794            // Is this a package name?
14795            if ("android".equals(cmd) || cmd.contains(".")) {
14796                packageName = cmd;
14797                // When dumping a single package, we always dump all of its
14798                // filter information since the amount of data will be reasonable.
14799                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14800            } else if ("check-permission".equals(cmd)) {
14801                if (opti >= args.length) {
14802                    pw.println("Error: check-permission missing permission argument");
14803                    return;
14804                }
14805                String perm = args[opti];
14806                opti++;
14807                if (opti >= args.length) {
14808                    pw.println("Error: check-permission missing package argument");
14809                    return;
14810                }
14811                String pkg = args[opti];
14812                opti++;
14813                int user = UserHandle.getUserId(Binder.getCallingUid());
14814                if (opti < args.length) {
14815                    try {
14816                        user = Integer.parseInt(args[opti]);
14817                    } catch (NumberFormatException e) {
14818                        pw.println("Error: check-permission user argument is not a number: "
14819                                + args[opti]);
14820                        return;
14821                    }
14822                }
14823                pw.println(checkPermission(perm, pkg, user));
14824                return;
14825            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14826                dumpState.setDump(DumpState.DUMP_LIBS);
14827            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14828                dumpState.setDump(DumpState.DUMP_FEATURES);
14829            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14830                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14831            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14832                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14833            } else if ("permission".equals(cmd)) {
14834                if (opti >= args.length) {
14835                    pw.println("Error: permission requires permission name");
14836                    return;
14837                }
14838                permissionNames = new ArraySet<>();
14839                while (opti < args.length) {
14840                    permissionNames.add(args[opti]);
14841                    opti++;
14842                }
14843                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14844                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14845            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14846                dumpState.setDump(DumpState.DUMP_PREFERRED);
14847            } else if ("preferred-xml".equals(cmd)) {
14848                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14849                if (opti < args.length && "--full".equals(args[opti])) {
14850                    fullPreferred = true;
14851                    opti++;
14852                }
14853            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14854                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14855            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14856                dumpState.setDump(DumpState.DUMP_PACKAGES);
14857            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14858                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14859            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14860                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14861            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14862                dumpState.setDump(DumpState.DUMP_MESSAGES);
14863            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14864                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14865            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14866                    || "intent-filter-verifiers".equals(cmd)) {
14867                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14868            } else if ("version".equals(cmd)) {
14869                dumpState.setDump(DumpState.DUMP_VERSION);
14870            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14871                dumpState.setDump(DumpState.DUMP_KEYSETS);
14872            } else if ("installs".equals(cmd)) {
14873                dumpState.setDump(DumpState.DUMP_INSTALLS);
14874            } else if ("write".equals(cmd)) {
14875                synchronized (mPackages) {
14876                    mSettings.writeLPr();
14877                    pw.println("Settings written.");
14878                    return;
14879                }
14880            }
14881        }
14882
14883        if (checkin) {
14884            pw.println("vers,1");
14885        }
14886
14887        // reader
14888        synchronized (mPackages) {
14889            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14890                if (!checkin) {
14891                    if (dumpState.onTitlePrinted())
14892                        pw.println();
14893                    pw.println("Database versions:");
14894                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14895                }
14896            }
14897
14898            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14899                if (!checkin) {
14900                    if (dumpState.onTitlePrinted())
14901                        pw.println();
14902                    pw.println("Verifiers:");
14903                    pw.print("  Required: ");
14904                    pw.print(mRequiredVerifierPackage);
14905                    pw.print(" (uid=");
14906                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14907                    pw.println(")");
14908                } else if (mRequiredVerifierPackage != null) {
14909                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14910                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14911                }
14912            }
14913
14914            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14915                    packageName == null) {
14916                if (mIntentFilterVerifierComponent != null) {
14917                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14918                    if (!checkin) {
14919                        if (dumpState.onTitlePrinted())
14920                            pw.println();
14921                        pw.println("Intent Filter Verifier:");
14922                        pw.print("  Using: ");
14923                        pw.print(verifierPackageName);
14924                        pw.print(" (uid=");
14925                        pw.print(getPackageUid(verifierPackageName, 0));
14926                        pw.println(")");
14927                    } else if (verifierPackageName != null) {
14928                        pw.print("ifv,"); pw.print(verifierPackageName);
14929                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14930                    }
14931                } else {
14932                    pw.println();
14933                    pw.println("No Intent Filter Verifier available!");
14934                }
14935            }
14936
14937            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14938                boolean printedHeader = false;
14939                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14940                while (it.hasNext()) {
14941                    String name = it.next();
14942                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14943                    if (!checkin) {
14944                        if (!printedHeader) {
14945                            if (dumpState.onTitlePrinted())
14946                                pw.println();
14947                            pw.println("Libraries:");
14948                            printedHeader = true;
14949                        }
14950                        pw.print("  ");
14951                    } else {
14952                        pw.print("lib,");
14953                    }
14954                    pw.print(name);
14955                    if (!checkin) {
14956                        pw.print(" -> ");
14957                    }
14958                    if (ent.path != null) {
14959                        if (!checkin) {
14960                            pw.print("(jar) ");
14961                            pw.print(ent.path);
14962                        } else {
14963                            pw.print(",jar,");
14964                            pw.print(ent.path);
14965                        }
14966                    } else {
14967                        if (!checkin) {
14968                            pw.print("(apk) ");
14969                            pw.print(ent.apk);
14970                        } else {
14971                            pw.print(",apk,");
14972                            pw.print(ent.apk);
14973                        }
14974                    }
14975                    pw.println();
14976                }
14977            }
14978
14979            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14980                if (dumpState.onTitlePrinted())
14981                    pw.println();
14982                if (!checkin) {
14983                    pw.println("Features:");
14984                }
14985                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14986                while (it.hasNext()) {
14987                    String name = it.next();
14988                    if (!checkin) {
14989                        pw.print("  ");
14990                    } else {
14991                        pw.print("feat,");
14992                    }
14993                    pw.println(name);
14994                }
14995            }
14996
14997            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14998                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14999                        : "Activity Resolver Table:", "  ", packageName,
15000                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15001                    dumpState.setTitlePrinted(true);
15002                }
15003                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15004                        : "Receiver Resolver Table:", "  ", packageName,
15005                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15006                    dumpState.setTitlePrinted(true);
15007                }
15008                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15009                        : "Service Resolver Table:", "  ", packageName,
15010                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15011                    dumpState.setTitlePrinted(true);
15012                }
15013                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15014                        : "Provider Resolver Table:", "  ", packageName,
15015                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15016                    dumpState.setTitlePrinted(true);
15017                }
15018            }
15019
15020            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15021                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15022                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15023                    int user = mSettings.mPreferredActivities.keyAt(i);
15024                    if (pir.dump(pw,
15025                            dumpState.getTitlePrinted()
15026                                ? "\nPreferred Activities User " + user + ":"
15027                                : "Preferred Activities User " + user + ":", "  ",
15028                            packageName, true, false)) {
15029                        dumpState.setTitlePrinted(true);
15030                    }
15031                }
15032            }
15033
15034            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15035                pw.flush();
15036                FileOutputStream fout = new FileOutputStream(fd);
15037                BufferedOutputStream str = new BufferedOutputStream(fout);
15038                XmlSerializer serializer = new FastXmlSerializer();
15039                try {
15040                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15041                    serializer.startDocument(null, true);
15042                    serializer.setFeature(
15043                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15044                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15045                    serializer.endDocument();
15046                    serializer.flush();
15047                } catch (IllegalArgumentException e) {
15048                    pw.println("Failed writing: " + e);
15049                } catch (IllegalStateException e) {
15050                    pw.println("Failed writing: " + e);
15051                } catch (IOException e) {
15052                    pw.println("Failed writing: " + e);
15053                }
15054            }
15055
15056            if (!checkin
15057                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15058                    && packageName == null) {
15059                pw.println();
15060                int count = mSettings.mPackages.size();
15061                if (count == 0) {
15062                    pw.println("No applications!");
15063                    pw.println();
15064                } else {
15065                    final String prefix = "  ";
15066                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15067                    if (allPackageSettings.size() == 0) {
15068                        pw.println("No domain preferred apps!");
15069                        pw.println();
15070                    } else {
15071                        pw.println("App verification status:");
15072                        pw.println();
15073                        count = 0;
15074                        for (PackageSetting ps : allPackageSettings) {
15075                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15076                            if (ivi == null || ivi.getPackageName() == null) continue;
15077                            pw.println(prefix + "Package: " + ivi.getPackageName());
15078                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15079                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15080                            pw.println();
15081                            count++;
15082                        }
15083                        if (count == 0) {
15084                            pw.println(prefix + "No app verification established.");
15085                            pw.println();
15086                        }
15087                        for (int userId : sUserManager.getUserIds()) {
15088                            pw.println("App linkages for user " + userId + ":");
15089                            pw.println();
15090                            count = 0;
15091                            for (PackageSetting ps : allPackageSettings) {
15092                                final long status = ps.getDomainVerificationStatusForUser(userId);
15093                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15094                                    continue;
15095                                }
15096                                pw.println(prefix + "Package: " + ps.name);
15097                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15098                                String statusStr = IntentFilterVerificationInfo.
15099                                        getStatusStringFromValue(status);
15100                                pw.println(prefix + "Status:  " + statusStr);
15101                                pw.println();
15102                                count++;
15103                            }
15104                            if (count == 0) {
15105                                pw.println(prefix + "No configured app linkages.");
15106                                pw.println();
15107                            }
15108                        }
15109                    }
15110                }
15111            }
15112
15113            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15114                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15115                if (packageName == null && permissionNames == null) {
15116                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15117                        if (iperm == 0) {
15118                            if (dumpState.onTitlePrinted())
15119                                pw.println();
15120                            pw.println("AppOp Permissions:");
15121                        }
15122                        pw.print("  AppOp Permission ");
15123                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15124                        pw.println(":");
15125                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15126                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15127                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15128                        }
15129                    }
15130                }
15131            }
15132
15133            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15134                boolean printedSomething = false;
15135                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15136                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15137                        continue;
15138                    }
15139                    if (!printedSomething) {
15140                        if (dumpState.onTitlePrinted())
15141                            pw.println();
15142                        pw.println("Registered ContentProviders:");
15143                        printedSomething = true;
15144                    }
15145                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15146                    pw.print("    "); pw.println(p.toString());
15147                }
15148                printedSomething = false;
15149                for (Map.Entry<String, PackageParser.Provider> entry :
15150                        mProvidersByAuthority.entrySet()) {
15151                    PackageParser.Provider p = entry.getValue();
15152                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15153                        continue;
15154                    }
15155                    if (!printedSomething) {
15156                        if (dumpState.onTitlePrinted())
15157                            pw.println();
15158                        pw.println("ContentProvider Authorities:");
15159                        printedSomething = true;
15160                    }
15161                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15162                    pw.print("    "); pw.println(p.toString());
15163                    if (p.info != null && p.info.applicationInfo != null) {
15164                        final String appInfo = p.info.applicationInfo.toString();
15165                        pw.print("      applicationInfo="); pw.println(appInfo);
15166                    }
15167                }
15168            }
15169
15170            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15171                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15172            }
15173
15174            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15175                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15176            }
15177
15178            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15179                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15180            }
15181
15182            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15183                // XXX should handle packageName != null by dumping only install data that
15184                // the given package is involved with.
15185                if (dumpState.onTitlePrinted()) pw.println();
15186                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15187            }
15188
15189            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15190                if (dumpState.onTitlePrinted()) pw.println();
15191                mSettings.dumpReadMessagesLPr(pw, dumpState);
15192
15193                pw.println();
15194                pw.println("Package warning messages:");
15195                BufferedReader in = null;
15196                String line = null;
15197                try {
15198                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15199                    while ((line = in.readLine()) != null) {
15200                        if (line.contains("ignored: updated version")) continue;
15201                        pw.println(line);
15202                    }
15203                } catch (IOException ignored) {
15204                } finally {
15205                    IoUtils.closeQuietly(in);
15206                }
15207            }
15208
15209            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15210                BufferedReader in = null;
15211                String line = null;
15212                try {
15213                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15214                    while ((line = in.readLine()) != null) {
15215                        if (line.contains("ignored: updated version")) continue;
15216                        pw.print("msg,");
15217                        pw.println(line);
15218                    }
15219                } catch (IOException ignored) {
15220                } finally {
15221                    IoUtils.closeQuietly(in);
15222                }
15223            }
15224        }
15225    }
15226
15227    private String dumpDomainString(String packageName) {
15228        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15229        List<IntentFilter> filters = getAllIntentFilters(packageName);
15230
15231        ArraySet<String> result = new ArraySet<>();
15232        if (iviList.size() > 0) {
15233            for (IntentFilterVerificationInfo ivi : iviList) {
15234                for (String host : ivi.getDomains()) {
15235                    result.add(host);
15236                }
15237            }
15238        }
15239        if (filters != null && filters.size() > 0) {
15240            for (IntentFilter filter : filters) {
15241                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15242                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15243                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15244                    result.addAll(filter.getHostsList());
15245                }
15246            }
15247        }
15248
15249        StringBuilder sb = new StringBuilder(result.size() * 16);
15250        for (String domain : result) {
15251            if (sb.length() > 0) sb.append(" ");
15252            sb.append(domain);
15253        }
15254        return sb.toString();
15255    }
15256
15257    // ------- apps on sdcard specific code -------
15258    static final boolean DEBUG_SD_INSTALL = false;
15259
15260    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15261
15262    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15263
15264    private boolean mMediaMounted = false;
15265
15266    static String getEncryptKey() {
15267        try {
15268            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15269                    SD_ENCRYPTION_KEYSTORE_NAME);
15270            if (sdEncKey == null) {
15271                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15272                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15273                if (sdEncKey == null) {
15274                    Slog.e(TAG, "Failed to create encryption keys");
15275                    return null;
15276                }
15277            }
15278            return sdEncKey;
15279        } catch (NoSuchAlgorithmException nsae) {
15280            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15281            return null;
15282        } catch (IOException ioe) {
15283            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15284            return null;
15285        }
15286    }
15287
15288    /*
15289     * Update media status on PackageManager.
15290     */
15291    @Override
15292    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15293        int callingUid = Binder.getCallingUid();
15294        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15295            throw new SecurityException("Media status can only be updated by the system");
15296        }
15297        // reader; this apparently protects mMediaMounted, but should probably
15298        // be a different lock in that case.
15299        synchronized (mPackages) {
15300            Log.i(TAG, "Updating external media status from "
15301                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15302                    + (mediaStatus ? "mounted" : "unmounted"));
15303            if (DEBUG_SD_INSTALL)
15304                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15305                        + ", mMediaMounted=" + mMediaMounted);
15306            if (mediaStatus == mMediaMounted) {
15307                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15308                        : 0, -1);
15309                mHandler.sendMessage(msg);
15310                return;
15311            }
15312            mMediaMounted = mediaStatus;
15313        }
15314        // Queue up an async operation since the package installation may take a
15315        // little while.
15316        mHandler.post(new Runnable() {
15317            public void run() {
15318                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15319            }
15320        });
15321    }
15322
15323    /**
15324     * Called by MountService when the initial ASECs to scan are available.
15325     * Should block until all the ASEC containers are finished being scanned.
15326     */
15327    public void scanAvailableAsecs() {
15328        updateExternalMediaStatusInner(true, false, false);
15329        if (mShouldRestoreconData) {
15330            SELinuxMMAC.setRestoreconDone();
15331            mShouldRestoreconData = false;
15332        }
15333    }
15334
15335    /*
15336     * Collect information of applications on external media, map them against
15337     * existing containers and update information based on current mount status.
15338     * Please note that we always have to report status if reportStatus has been
15339     * set to true especially when unloading packages.
15340     */
15341    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15342            boolean externalStorage) {
15343        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15344        int[] uidArr = EmptyArray.INT;
15345
15346        final String[] list = PackageHelper.getSecureContainerList();
15347        if (ArrayUtils.isEmpty(list)) {
15348            Log.i(TAG, "No secure containers found");
15349        } else {
15350            // Process list of secure containers and categorize them
15351            // as active or stale based on their package internal state.
15352
15353            // reader
15354            synchronized (mPackages) {
15355                for (String cid : list) {
15356                    // Leave stages untouched for now; installer service owns them
15357                    if (PackageInstallerService.isStageName(cid)) continue;
15358
15359                    if (DEBUG_SD_INSTALL)
15360                        Log.i(TAG, "Processing container " + cid);
15361                    String pkgName = getAsecPackageName(cid);
15362                    if (pkgName == null) {
15363                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15364                        continue;
15365                    }
15366                    if (DEBUG_SD_INSTALL)
15367                        Log.i(TAG, "Looking for pkg : " + pkgName);
15368
15369                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15370                    if (ps == null) {
15371                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15372                        continue;
15373                    }
15374
15375                    /*
15376                     * Skip packages that are not external if we're unmounting
15377                     * external storage.
15378                     */
15379                    if (externalStorage && !isMounted && !isExternal(ps)) {
15380                        continue;
15381                    }
15382
15383                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15384                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15385                    // The package status is changed only if the code path
15386                    // matches between settings and the container id.
15387                    if (ps.codePathString != null
15388                            && ps.codePathString.startsWith(args.getCodePath())) {
15389                        if (DEBUG_SD_INSTALL) {
15390                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15391                                    + " at code path: " + ps.codePathString);
15392                        }
15393
15394                        // We do have a valid package installed on sdcard
15395                        processCids.put(args, ps.codePathString);
15396                        final int uid = ps.appId;
15397                        if (uid != -1) {
15398                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15399                        }
15400                    } else {
15401                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15402                                + ps.codePathString);
15403                    }
15404                }
15405            }
15406
15407            Arrays.sort(uidArr);
15408        }
15409
15410        // Process packages with valid entries.
15411        if (isMounted) {
15412            if (DEBUG_SD_INSTALL)
15413                Log.i(TAG, "Loading packages");
15414            loadMediaPackages(processCids, uidArr);
15415            startCleaningPackages();
15416            mInstallerService.onSecureContainersAvailable();
15417        } else {
15418            if (DEBUG_SD_INSTALL)
15419                Log.i(TAG, "Unloading packages");
15420            unloadMediaPackages(processCids, uidArr, reportStatus);
15421        }
15422    }
15423
15424    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15425            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15426        final int size = infos.size();
15427        final String[] packageNames = new String[size];
15428        final int[] packageUids = new int[size];
15429        for (int i = 0; i < size; i++) {
15430            final ApplicationInfo info = infos.get(i);
15431            packageNames[i] = info.packageName;
15432            packageUids[i] = info.uid;
15433        }
15434        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15435                finishedReceiver);
15436    }
15437
15438    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15439            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15440        sendResourcesChangedBroadcast(mediaStatus, replacing,
15441                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15442    }
15443
15444    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15445            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15446        int size = pkgList.length;
15447        if (size > 0) {
15448            // Send broadcasts here
15449            Bundle extras = new Bundle();
15450            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15451            if (uidArr != null) {
15452                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15453            }
15454            if (replacing) {
15455                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15456            }
15457            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15458                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15459            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15460        }
15461    }
15462
15463   /*
15464     * Look at potentially valid container ids from processCids If package
15465     * information doesn't match the one on record or package scanning fails,
15466     * the cid is added to list of removeCids. We currently don't delete stale
15467     * containers.
15468     */
15469    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15470        ArrayList<String> pkgList = new ArrayList<String>();
15471        Set<AsecInstallArgs> keys = processCids.keySet();
15472
15473        for (AsecInstallArgs args : keys) {
15474            String codePath = processCids.get(args);
15475            if (DEBUG_SD_INSTALL)
15476                Log.i(TAG, "Loading container : " + args.cid);
15477            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15478            try {
15479                // Make sure there are no container errors first.
15480                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15481                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15482                            + " when installing from sdcard");
15483                    continue;
15484                }
15485                // Check code path here.
15486                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15487                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15488                            + " does not match one in settings " + codePath);
15489                    continue;
15490                }
15491                // Parse package
15492                int parseFlags = mDefParseFlags;
15493                if (args.isExternalAsec()) {
15494                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15495                }
15496                if (args.isFwdLocked()) {
15497                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15498                }
15499
15500                synchronized (mInstallLock) {
15501                    PackageParser.Package pkg = null;
15502                    try {
15503                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15504                    } catch (PackageManagerException e) {
15505                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15506                    }
15507                    // Scan the package
15508                    if (pkg != null) {
15509                        /*
15510                         * TODO why is the lock being held? doPostInstall is
15511                         * called in other places without the lock. This needs
15512                         * to be straightened out.
15513                         */
15514                        // writer
15515                        synchronized (mPackages) {
15516                            retCode = PackageManager.INSTALL_SUCCEEDED;
15517                            pkgList.add(pkg.packageName);
15518                            // Post process args
15519                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15520                                    pkg.applicationInfo.uid);
15521                        }
15522                    } else {
15523                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15524                    }
15525                }
15526
15527            } finally {
15528                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15529                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15530                }
15531            }
15532        }
15533        // writer
15534        synchronized (mPackages) {
15535            // If the platform SDK has changed since the last time we booted,
15536            // we need to re-grant app permission to catch any new ones that
15537            // appear. This is really a hack, and means that apps can in some
15538            // cases get permissions that the user didn't initially explicitly
15539            // allow... it would be nice to have some better way to handle
15540            // this situation.
15541            final VersionInfo ver = mSettings.getExternalVersion();
15542
15543            int updateFlags = UPDATE_PERMISSIONS_ALL;
15544            if (ver.sdkVersion != mSdkVersion) {
15545                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15546                        + mSdkVersion + "; regranting permissions for external");
15547                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15548            }
15549            updatePermissionsLPw(null, null, updateFlags);
15550
15551            // Yay, everything is now upgraded
15552            ver.forceCurrent();
15553
15554            // can downgrade to reader
15555            // Persist settings
15556            mSettings.writeLPr();
15557        }
15558        // Send a broadcast to let everyone know we are done processing
15559        if (pkgList.size() > 0) {
15560            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15561        }
15562    }
15563
15564   /*
15565     * Utility method to unload a list of specified containers
15566     */
15567    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15568        // Just unmount all valid containers.
15569        for (AsecInstallArgs arg : cidArgs) {
15570            synchronized (mInstallLock) {
15571                arg.doPostDeleteLI(false);
15572           }
15573       }
15574   }
15575
15576    /*
15577     * Unload packages mounted on external media. This involves deleting package
15578     * data from internal structures, sending broadcasts about diabled packages,
15579     * gc'ing to free up references, unmounting all secure containers
15580     * corresponding to packages on external media, and posting a
15581     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15582     * that we always have to post this message if status has been requested no
15583     * matter what.
15584     */
15585    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15586            final boolean reportStatus) {
15587        if (DEBUG_SD_INSTALL)
15588            Log.i(TAG, "unloading media packages");
15589        ArrayList<String> pkgList = new ArrayList<String>();
15590        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15591        final Set<AsecInstallArgs> keys = processCids.keySet();
15592        for (AsecInstallArgs args : keys) {
15593            String pkgName = args.getPackageName();
15594            if (DEBUG_SD_INSTALL)
15595                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15596            // Delete package internally
15597            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15598            synchronized (mInstallLock) {
15599                boolean res = deletePackageLI(pkgName, null, false, null, null,
15600                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15601                if (res) {
15602                    pkgList.add(pkgName);
15603                } else {
15604                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15605                    failedList.add(args);
15606                }
15607            }
15608        }
15609
15610        // reader
15611        synchronized (mPackages) {
15612            // We didn't update the settings after removing each package;
15613            // write them now for all packages.
15614            mSettings.writeLPr();
15615        }
15616
15617        // We have to absolutely send UPDATED_MEDIA_STATUS only
15618        // after confirming that all the receivers processed the ordered
15619        // broadcast when packages get disabled, force a gc to clean things up.
15620        // and unload all the containers.
15621        if (pkgList.size() > 0) {
15622            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15623                    new IIntentReceiver.Stub() {
15624                public void performReceive(Intent intent, int resultCode, String data,
15625                        Bundle extras, boolean ordered, boolean sticky,
15626                        int sendingUser) throws RemoteException {
15627                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15628                            reportStatus ? 1 : 0, 1, keys);
15629                    mHandler.sendMessage(msg);
15630                }
15631            });
15632        } else {
15633            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15634                    keys);
15635            mHandler.sendMessage(msg);
15636        }
15637    }
15638
15639    private void loadPrivatePackages(VolumeInfo vol) {
15640        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15641        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15642        synchronized (mInstallLock) {
15643        synchronized (mPackages) {
15644            final VersionInfo ver = mSettings.findOrCreateVersion(vol.fsUuid);
15645            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15646            for (PackageSetting ps : packages) {
15647                final PackageParser.Package pkg;
15648                try {
15649                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15650                    loaded.add(pkg.applicationInfo);
15651                } catch (PackageManagerException e) {
15652                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15653                }
15654
15655                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15656                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15657                }
15658            }
15659
15660            int updateFlags = UPDATE_PERMISSIONS_ALL;
15661            if (ver.sdkVersion != mSdkVersion) {
15662                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15663                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15664                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15665            }
15666            updatePermissionsLPw(null, null, updateFlags);
15667
15668            // Yay, everything is now upgraded
15669            ver.forceCurrent();
15670
15671            mSettings.writeLPr();
15672        }
15673        }
15674
15675        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15676        sendResourcesChangedBroadcast(true, false, loaded, null);
15677    }
15678
15679    private void unloadPrivatePackages(VolumeInfo vol) {
15680        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15681        synchronized (mInstallLock) {
15682        synchronized (mPackages) {
15683            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15684            for (PackageSetting ps : packages) {
15685                if (ps.pkg == null) continue;
15686
15687                final ApplicationInfo info = ps.pkg.applicationInfo;
15688                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15689                if (deletePackageLI(ps.name, null, false, null, null,
15690                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15691                    unloaded.add(info);
15692                } else {
15693                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15694                }
15695            }
15696
15697            mSettings.writeLPr();
15698        }
15699        }
15700
15701        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15702        sendResourcesChangedBroadcast(false, false, unloaded, null);
15703    }
15704
15705    /**
15706     * Examine all users present on given mounted volume, and destroy data
15707     * belonging to users that are no longer valid, or whose user ID has been
15708     * recycled.
15709     */
15710    private void reconcileUsers(String volumeUuid) {
15711        final File[] files = FileUtils
15712                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15713        for (File file : files) {
15714            if (!file.isDirectory()) continue;
15715
15716            final int userId;
15717            final UserInfo info;
15718            try {
15719                userId = Integer.parseInt(file.getName());
15720                info = sUserManager.getUserInfo(userId);
15721            } catch (NumberFormatException e) {
15722                Slog.w(TAG, "Invalid user directory " + file);
15723                continue;
15724            }
15725
15726            boolean destroyUser = false;
15727            if (info == null) {
15728                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15729                        + " because no matching user was found");
15730                destroyUser = true;
15731            } else {
15732                try {
15733                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15734                } catch (IOException e) {
15735                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15736                            + " because we failed to enforce serial number: " + e);
15737                    destroyUser = true;
15738                }
15739            }
15740
15741            if (destroyUser) {
15742                synchronized (mInstallLock) {
15743                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15744                }
15745            }
15746        }
15747
15748        final UserManager um = mContext.getSystemService(UserManager.class);
15749        for (UserInfo user : um.getUsers()) {
15750            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15751            if (userDir.exists()) continue;
15752
15753            try {
15754                UserManagerService.prepareUserDirectory(userDir);
15755                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15756            } catch (IOException e) {
15757                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15758            }
15759        }
15760    }
15761
15762    /**
15763     * Examine all apps present on given mounted volume, and destroy apps that
15764     * aren't expected, either due to uninstallation or reinstallation on
15765     * another volume.
15766     */
15767    private void reconcileApps(String volumeUuid) {
15768        final File[] files = FileUtils
15769                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15770        for (File file : files) {
15771            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15772                    && !PackageInstallerService.isStageName(file.getName());
15773            if (!isPackage) {
15774                // Ignore entries which are not packages
15775                continue;
15776            }
15777
15778            boolean destroyApp = false;
15779            String packageName = null;
15780            try {
15781                final PackageLite pkg = PackageParser.parsePackageLite(file,
15782                        PackageParser.PARSE_MUST_BE_APK);
15783                packageName = pkg.packageName;
15784
15785                synchronized (mPackages) {
15786                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15787                    if (ps == null) {
15788                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15789                                + volumeUuid + " because we found no install record");
15790                        destroyApp = true;
15791                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15792                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15793                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15794                        destroyApp = true;
15795                    }
15796                }
15797
15798            } catch (PackageParserException e) {
15799                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15800                destroyApp = true;
15801            }
15802
15803            if (destroyApp) {
15804                synchronized (mInstallLock) {
15805                    if (packageName != null) {
15806                        removeDataDirsLI(volumeUuid, packageName);
15807                    }
15808                    if (file.isDirectory()) {
15809                        mInstaller.rmPackageDir(file.getAbsolutePath());
15810                    } else {
15811                        file.delete();
15812                    }
15813                }
15814            }
15815        }
15816    }
15817
15818    private void unfreezePackage(String packageName) {
15819        synchronized (mPackages) {
15820            final PackageSetting ps = mSettings.mPackages.get(packageName);
15821            if (ps != null) {
15822                ps.frozen = false;
15823            }
15824        }
15825    }
15826
15827    @Override
15828    public int movePackage(final String packageName, final String volumeUuid) {
15829        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15830
15831        final int moveId = mNextMoveId.getAndIncrement();
15832        try {
15833            movePackageInternal(packageName, volumeUuid, moveId);
15834        } catch (PackageManagerException e) {
15835            Slog.w(TAG, "Failed to move " + packageName, e);
15836            mMoveCallbacks.notifyStatusChanged(moveId,
15837                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15838        }
15839        return moveId;
15840    }
15841
15842    private void movePackageInternal(final String packageName, final String volumeUuid,
15843            final int moveId) throws PackageManagerException {
15844        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15845        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15846        final PackageManager pm = mContext.getPackageManager();
15847
15848        final boolean currentAsec;
15849        final String currentVolumeUuid;
15850        final File codeFile;
15851        final String installerPackageName;
15852        final String packageAbiOverride;
15853        final int appId;
15854        final String seinfo;
15855        final String label;
15856
15857        // reader
15858        synchronized (mPackages) {
15859            final PackageParser.Package pkg = mPackages.get(packageName);
15860            final PackageSetting ps = mSettings.mPackages.get(packageName);
15861            if (pkg == null || ps == null) {
15862                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15863            }
15864
15865            if (pkg.applicationInfo.isSystemApp()) {
15866                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15867                        "Cannot move system application");
15868            }
15869
15870            if (pkg.applicationInfo.isExternalAsec()) {
15871                currentAsec = true;
15872                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
15873            } else if (pkg.applicationInfo.isForwardLocked()) {
15874                currentAsec = true;
15875                currentVolumeUuid = "forward_locked";
15876            } else {
15877                currentAsec = false;
15878                currentVolumeUuid = ps.volumeUuid;
15879
15880                final File probe = new File(pkg.codePath);
15881                final File probeOat = new File(probe, "oat");
15882                if (!probe.isDirectory() || !probeOat.isDirectory()) {
15883                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15884                            "Move only supported for modern cluster style installs");
15885                }
15886            }
15887
15888            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
15889                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15890                        "Package already moved to " + volumeUuid);
15891            }
15892
15893            if (ps.frozen) {
15894                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15895                        "Failed to move already frozen package");
15896            }
15897            ps.frozen = true;
15898
15899            codeFile = new File(pkg.codePath);
15900            installerPackageName = ps.installerPackageName;
15901            packageAbiOverride = ps.cpuAbiOverrideString;
15902            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15903            seinfo = pkg.applicationInfo.seinfo;
15904            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15905        }
15906
15907        // Now that we're guarded by frozen state, kill app during move
15908        final long token = Binder.clearCallingIdentity();
15909        try {
15910            killApplication(packageName, appId, "move pkg");
15911        } finally {
15912            Binder.restoreCallingIdentity(token);
15913        }
15914
15915        final Bundle extras = new Bundle();
15916        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15917        extras.putString(Intent.EXTRA_TITLE, label);
15918        mMoveCallbacks.notifyCreated(moveId, extras);
15919
15920        int installFlags;
15921        final boolean moveCompleteApp;
15922        final File measurePath;
15923
15924        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15925            installFlags = INSTALL_INTERNAL;
15926            moveCompleteApp = !currentAsec;
15927            measurePath = Environment.getDataAppDirectory(volumeUuid);
15928        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15929            installFlags = INSTALL_EXTERNAL;
15930            moveCompleteApp = false;
15931            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15932        } else {
15933            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15934            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15935                    || !volume.isMountedWritable()) {
15936                unfreezePackage(packageName);
15937                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15938                        "Move location not mounted private volume");
15939            }
15940
15941            Preconditions.checkState(!currentAsec);
15942
15943            installFlags = INSTALL_INTERNAL;
15944            moveCompleteApp = true;
15945            measurePath = Environment.getDataAppDirectory(volumeUuid);
15946        }
15947
15948        final PackageStats stats = new PackageStats(null, -1);
15949        synchronized (mInstaller) {
15950            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15951                unfreezePackage(packageName);
15952                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15953                        "Failed to measure package size");
15954            }
15955        }
15956
15957        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15958                + stats.dataSize);
15959
15960        final long startFreeBytes = measurePath.getFreeSpace();
15961        final long sizeBytes;
15962        if (moveCompleteApp) {
15963            sizeBytes = stats.codeSize + stats.dataSize;
15964        } else {
15965            sizeBytes = stats.codeSize;
15966        }
15967
15968        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15969            unfreezePackage(packageName);
15970            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15971                    "Not enough free space to move");
15972        }
15973
15974        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15975
15976        final CountDownLatch installedLatch = new CountDownLatch(1);
15977        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15978            @Override
15979            public void onUserActionRequired(Intent intent) throws RemoteException {
15980                throw new IllegalStateException();
15981            }
15982
15983            @Override
15984            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15985                    Bundle extras) throws RemoteException {
15986                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15987                        + PackageManager.installStatusToString(returnCode, msg));
15988
15989                installedLatch.countDown();
15990
15991                // Regardless of success or failure of the move operation,
15992                // always unfreeze the package
15993                unfreezePackage(packageName);
15994
15995                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15996                switch (status) {
15997                    case PackageInstaller.STATUS_SUCCESS:
15998                        mMoveCallbacks.notifyStatusChanged(moveId,
15999                                PackageManager.MOVE_SUCCEEDED);
16000                        break;
16001                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16002                        mMoveCallbacks.notifyStatusChanged(moveId,
16003                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16004                        break;
16005                    default:
16006                        mMoveCallbacks.notifyStatusChanged(moveId,
16007                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16008                        break;
16009                }
16010            }
16011        };
16012
16013        final MoveInfo move;
16014        if (moveCompleteApp) {
16015            // Kick off a thread to report progress estimates
16016            new Thread() {
16017                @Override
16018                public void run() {
16019                    while (true) {
16020                        try {
16021                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16022                                break;
16023                            }
16024                        } catch (InterruptedException ignored) {
16025                        }
16026
16027                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16028                        final int progress = 10 + (int) MathUtils.constrain(
16029                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16030                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16031                    }
16032                }
16033            }.start();
16034
16035            final String dataAppName = codeFile.getName();
16036            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16037                    dataAppName, appId, seinfo);
16038        } else {
16039            move = null;
16040        }
16041
16042        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16043
16044        final Message msg = mHandler.obtainMessage(INIT_COPY);
16045        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16046        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
16047                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16048        mHandler.sendMessage(msg);
16049    }
16050
16051    @Override
16052    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16053        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16054
16055        final int realMoveId = mNextMoveId.getAndIncrement();
16056        final Bundle extras = new Bundle();
16057        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16058        mMoveCallbacks.notifyCreated(realMoveId, extras);
16059
16060        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16061            @Override
16062            public void onCreated(int moveId, Bundle extras) {
16063                // Ignored
16064            }
16065
16066            @Override
16067            public void onStatusChanged(int moveId, int status, long estMillis) {
16068                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16069            }
16070        };
16071
16072        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16073        storage.setPrimaryStorageUuid(volumeUuid, callback);
16074        return realMoveId;
16075    }
16076
16077    @Override
16078    public int getMoveStatus(int moveId) {
16079        mContext.enforceCallingOrSelfPermission(
16080                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16081        return mMoveCallbacks.mLastStatus.get(moveId);
16082    }
16083
16084    @Override
16085    public void registerMoveCallback(IPackageMoveObserver callback) {
16086        mContext.enforceCallingOrSelfPermission(
16087                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16088        mMoveCallbacks.register(callback);
16089    }
16090
16091    @Override
16092    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16093        mContext.enforceCallingOrSelfPermission(
16094                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16095        mMoveCallbacks.unregister(callback);
16096    }
16097
16098    @Override
16099    public boolean setInstallLocation(int loc) {
16100        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16101                null);
16102        if (getInstallLocation() == loc) {
16103            return true;
16104        }
16105        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16106                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16107            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16108                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16109            return true;
16110        }
16111        return false;
16112   }
16113
16114    @Override
16115    public int getInstallLocation() {
16116        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16117                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16118                PackageHelper.APP_INSTALL_AUTO);
16119    }
16120
16121    /** Called by UserManagerService */
16122    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16123        mDirtyUsers.remove(userHandle);
16124        mSettings.removeUserLPw(userHandle);
16125        mPendingBroadcasts.remove(userHandle);
16126        if (mInstaller != null) {
16127            // Technically, we shouldn't be doing this with the package lock
16128            // held.  However, this is very rare, and there is already so much
16129            // other disk I/O going on, that we'll let it slide for now.
16130            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16131            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16132                final String volumeUuid = vol.getFsUuid();
16133                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16134                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16135            }
16136        }
16137        mUserNeedsBadging.delete(userHandle);
16138        removeUnusedPackagesLILPw(userManager, userHandle);
16139    }
16140
16141    /**
16142     * We're removing userHandle and would like to remove any downloaded packages
16143     * that are no longer in use by any other user.
16144     * @param userHandle the user being removed
16145     */
16146    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16147        final boolean DEBUG_CLEAN_APKS = false;
16148        int [] users = userManager.getUserIdsLPr();
16149        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16150        while (psit.hasNext()) {
16151            PackageSetting ps = psit.next();
16152            if (ps.pkg == null) {
16153                continue;
16154            }
16155            final String packageName = ps.pkg.packageName;
16156            // Skip over if system app
16157            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16158                continue;
16159            }
16160            if (DEBUG_CLEAN_APKS) {
16161                Slog.i(TAG, "Checking package " + packageName);
16162            }
16163            boolean keep = false;
16164            for (int i = 0; i < users.length; i++) {
16165                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16166                    keep = true;
16167                    if (DEBUG_CLEAN_APKS) {
16168                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16169                                + users[i]);
16170                    }
16171                    break;
16172                }
16173            }
16174            if (!keep) {
16175                if (DEBUG_CLEAN_APKS) {
16176                    Slog.i(TAG, "  Removing package " + packageName);
16177                }
16178                mHandler.post(new Runnable() {
16179                    public void run() {
16180                        deletePackageX(packageName, userHandle, 0);
16181                    } //end run
16182                });
16183            }
16184        }
16185    }
16186
16187    /** Called by UserManagerService */
16188    void createNewUserLILPw(int userHandle) {
16189        if (mInstaller != null) {
16190            mInstaller.createUserConfig(userHandle);
16191            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16192            applyFactoryDefaultBrowserLPw(userHandle);
16193            primeDomainVerificationsLPw(userHandle);
16194        }
16195    }
16196
16197    void newUserCreated(final int userHandle) {
16198        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16199    }
16200
16201    @Override
16202    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16203        mContext.enforceCallingOrSelfPermission(
16204                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16205                "Only package verification agents can read the verifier device identity");
16206
16207        synchronized (mPackages) {
16208            return mSettings.getVerifierDeviceIdentityLPw();
16209        }
16210    }
16211
16212    @Override
16213    public void setPermissionEnforced(String permission, boolean enforced) {
16214        // TODO: Now that we no longer change GID for storage, this should to away.
16215        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16216                "setPermissionEnforced");
16217        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16218            synchronized (mPackages) {
16219                if (mSettings.mReadExternalStorageEnforced == null
16220                        || mSettings.mReadExternalStorageEnforced != enforced) {
16221                    mSettings.mReadExternalStorageEnforced = enforced;
16222                    mSettings.writeLPr();
16223                }
16224            }
16225            // kill any non-foreground processes so we restart them and
16226            // grant/revoke the GID.
16227            final IActivityManager am = ActivityManagerNative.getDefault();
16228            if (am != null) {
16229                final long token = Binder.clearCallingIdentity();
16230                try {
16231                    am.killProcessesBelowForeground("setPermissionEnforcement");
16232                } catch (RemoteException e) {
16233                } finally {
16234                    Binder.restoreCallingIdentity(token);
16235                }
16236            }
16237        } else {
16238            throw new IllegalArgumentException("No selective enforcement for " + permission);
16239        }
16240    }
16241
16242    @Override
16243    @Deprecated
16244    public boolean isPermissionEnforced(String permission) {
16245        return true;
16246    }
16247
16248    @Override
16249    public boolean isStorageLow() {
16250        final long token = Binder.clearCallingIdentity();
16251        try {
16252            final DeviceStorageMonitorInternal
16253                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16254            if (dsm != null) {
16255                return dsm.isMemoryLow();
16256            } else {
16257                return false;
16258            }
16259        } finally {
16260            Binder.restoreCallingIdentity(token);
16261        }
16262    }
16263
16264    @Override
16265    public IPackageInstaller getPackageInstaller() {
16266        return mInstallerService;
16267    }
16268
16269    private boolean userNeedsBadging(int userId) {
16270        int index = mUserNeedsBadging.indexOfKey(userId);
16271        if (index < 0) {
16272            final UserInfo userInfo;
16273            final long token = Binder.clearCallingIdentity();
16274            try {
16275                userInfo = sUserManager.getUserInfo(userId);
16276            } finally {
16277                Binder.restoreCallingIdentity(token);
16278            }
16279            final boolean b;
16280            if (userInfo != null && userInfo.isManagedProfile()) {
16281                b = true;
16282            } else {
16283                b = false;
16284            }
16285            mUserNeedsBadging.put(userId, b);
16286            return b;
16287        }
16288        return mUserNeedsBadging.valueAt(index);
16289    }
16290
16291    @Override
16292    public KeySet getKeySetByAlias(String packageName, String alias) {
16293        if (packageName == null || alias == null) {
16294            return null;
16295        }
16296        synchronized(mPackages) {
16297            final PackageParser.Package pkg = mPackages.get(packageName);
16298            if (pkg == null) {
16299                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16300                throw new IllegalArgumentException("Unknown package: " + packageName);
16301            }
16302            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16303            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16304        }
16305    }
16306
16307    @Override
16308    public KeySet getSigningKeySet(String packageName) {
16309        if (packageName == null) {
16310            return null;
16311        }
16312        synchronized(mPackages) {
16313            final PackageParser.Package pkg = mPackages.get(packageName);
16314            if (pkg == null) {
16315                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16316                throw new IllegalArgumentException("Unknown package: " + packageName);
16317            }
16318            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16319                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16320                throw new SecurityException("May not access signing KeySet of other apps.");
16321            }
16322            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16323            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16324        }
16325    }
16326
16327    @Override
16328    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16329        if (packageName == null || ks == null) {
16330            return false;
16331        }
16332        synchronized(mPackages) {
16333            final PackageParser.Package pkg = mPackages.get(packageName);
16334            if (pkg == null) {
16335                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16336                throw new IllegalArgumentException("Unknown package: " + packageName);
16337            }
16338            IBinder ksh = ks.getToken();
16339            if (ksh instanceof KeySetHandle) {
16340                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16341                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16342            }
16343            return false;
16344        }
16345    }
16346
16347    @Override
16348    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16349        if (packageName == null || ks == null) {
16350            return false;
16351        }
16352        synchronized(mPackages) {
16353            final PackageParser.Package pkg = mPackages.get(packageName);
16354            if (pkg == null) {
16355                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16356                throw new IllegalArgumentException("Unknown package: " + packageName);
16357            }
16358            IBinder ksh = ks.getToken();
16359            if (ksh instanceof KeySetHandle) {
16360                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16361                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16362            }
16363            return false;
16364        }
16365    }
16366
16367    public void getUsageStatsIfNoPackageUsageInfo() {
16368        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16369            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16370            if (usm == null) {
16371                throw new IllegalStateException("UsageStatsManager must be initialized");
16372            }
16373            long now = System.currentTimeMillis();
16374            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16375            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16376                String packageName = entry.getKey();
16377                PackageParser.Package pkg = mPackages.get(packageName);
16378                if (pkg == null) {
16379                    continue;
16380                }
16381                UsageStats usage = entry.getValue();
16382                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16383                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16384            }
16385        }
16386    }
16387
16388    /**
16389     * Check and throw if the given before/after packages would be considered a
16390     * downgrade.
16391     */
16392    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16393            throws PackageManagerException {
16394        if (after.versionCode < before.mVersionCode) {
16395            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16396                    "Update version code " + after.versionCode + " is older than current "
16397                    + before.mVersionCode);
16398        } else if (after.versionCode == before.mVersionCode) {
16399            if (after.baseRevisionCode < before.baseRevisionCode) {
16400                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16401                        "Update base revision code " + after.baseRevisionCode
16402                        + " is older than current " + before.baseRevisionCode);
16403            }
16404
16405            if (!ArrayUtils.isEmpty(after.splitNames)) {
16406                for (int i = 0; i < after.splitNames.length; i++) {
16407                    final String splitName = after.splitNames[i];
16408                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16409                    if (j != -1) {
16410                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16411                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16412                                    "Update split " + splitName + " revision code "
16413                                    + after.splitRevisionCodes[i] + " is older than current "
16414                                    + before.splitRevisionCodes[j]);
16415                        }
16416                    }
16417                }
16418            }
16419        }
16420    }
16421
16422    private static class MoveCallbacks extends Handler {
16423        private static final int MSG_CREATED = 1;
16424        private static final int MSG_STATUS_CHANGED = 2;
16425
16426        private final RemoteCallbackList<IPackageMoveObserver>
16427                mCallbacks = new RemoteCallbackList<>();
16428
16429        private final SparseIntArray mLastStatus = new SparseIntArray();
16430
16431        public MoveCallbacks(Looper looper) {
16432            super(looper);
16433        }
16434
16435        public void register(IPackageMoveObserver callback) {
16436            mCallbacks.register(callback);
16437        }
16438
16439        public void unregister(IPackageMoveObserver callback) {
16440            mCallbacks.unregister(callback);
16441        }
16442
16443        @Override
16444        public void handleMessage(Message msg) {
16445            final SomeArgs args = (SomeArgs) msg.obj;
16446            final int n = mCallbacks.beginBroadcast();
16447            for (int i = 0; i < n; i++) {
16448                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16449                try {
16450                    invokeCallback(callback, msg.what, args);
16451                } catch (RemoteException ignored) {
16452                }
16453            }
16454            mCallbacks.finishBroadcast();
16455            args.recycle();
16456        }
16457
16458        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16459                throws RemoteException {
16460            switch (what) {
16461                case MSG_CREATED: {
16462                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16463                    break;
16464                }
16465                case MSG_STATUS_CHANGED: {
16466                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16467                    break;
16468                }
16469            }
16470        }
16471
16472        private void notifyCreated(int moveId, Bundle extras) {
16473            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16474
16475            final SomeArgs args = SomeArgs.obtain();
16476            args.argi1 = moveId;
16477            args.arg2 = extras;
16478            obtainMessage(MSG_CREATED, args).sendToTarget();
16479        }
16480
16481        private void notifyStatusChanged(int moveId, int status) {
16482            notifyStatusChanged(moveId, status, -1);
16483        }
16484
16485        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16486            Slog.v(TAG, "Move " + moveId + " status " + status);
16487
16488            final SomeArgs args = SomeArgs.obtain();
16489            args.argi1 = moveId;
16490            args.argi2 = status;
16491            args.arg3 = estMillis;
16492            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16493
16494            synchronized (mLastStatus) {
16495                mLastStatus.put(moveId, status);
16496            }
16497        }
16498    }
16499
16500    private final class OnPermissionChangeListeners extends Handler {
16501        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16502
16503        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16504                new RemoteCallbackList<>();
16505
16506        public OnPermissionChangeListeners(Looper looper) {
16507            super(looper);
16508        }
16509
16510        @Override
16511        public void handleMessage(Message msg) {
16512            switch (msg.what) {
16513                case MSG_ON_PERMISSIONS_CHANGED: {
16514                    final int uid = msg.arg1;
16515                    handleOnPermissionsChanged(uid);
16516                } break;
16517            }
16518        }
16519
16520        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16521            mPermissionListeners.register(listener);
16522
16523        }
16524
16525        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16526            mPermissionListeners.unregister(listener);
16527        }
16528
16529        public void onPermissionsChanged(int uid) {
16530            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16531                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16532            }
16533        }
16534
16535        private void handleOnPermissionsChanged(int uid) {
16536            final int count = mPermissionListeners.beginBroadcast();
16537            try {
16538                for (int i = 0; i < count; i++) {
16539                    IOnPermissionsChangeListener callback = mPermissionListeners
16540                            .getBroadcastItem(i);
16541                    try {
16542                        callback.onPermissionsChanged(uid);
16543                    } catch (RemoteException e) {
16544                        Log.e(TAG, "Permission listener is dead", e);
16545                    }
16546                }
16547            } finally {
16548                mPermissionListeners.finishBroadcast();
16549            }
16550        }
16551    }
16552
16553    private class PackageManagerInternalImpl extends PackageManagerInternal {
16554        @Override
16555        public void setLocationPackagesProvider(PackagesProvider provider) {
16556            synchronized (mPackages) {
16557                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16558            }
16559        }
16560
16561        @Override
16562        public void setImePackagesProvider(PackagesProvider provider) {
16563            synchronized (mPackages) {
16564                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16565            }
16566        }
16567
16568        @Override
16569        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16570            synchronized (mPackages) {
16571                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16572            }
16573        }
16574
16575        @Override
16576        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16577            synchronized (mPackages) {
16578                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16579            }
16580        }
16581
16582        @Override
16583        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16584            synchronized (mPackages) {
16585                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16586            }
16587        }
16588
16589        @Override
16590        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16591            synchronized (mPackages) {
16592                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16593            }
16594        }
16595
16596        @Override
16597        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16598            synchronized (mPackages) {
16599                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16600            }
16601        }
16602
16603        @Override
16604        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16605            synchronized (mPackages) {
16606                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16607                        packageName, userId);
16608            }
16609        }
16610
16611        @Override
16612        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16613            synchronized (mPackages) {
16614                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16615                        packageName, userId);
16616            }
16617        }
16618        @Override
16619        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16620            synchronized (mPackages) {
16621                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16622                        packageName, userId);
16623            }
16624        }
16625    }
16626
16627    @Override
16628    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16629        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16630        synchronized (mPackages) {
16631            final long identity = Binder.clearCallingIdentity();
16632            try {
16633                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16634                        packageNames, userId);
16635            } finally {
16636                Binder.restoreCallingIdentity(identity);
16637            }
16638        }
16639    }
16640
16641    private static void enforceSystemOrPhoneCaller(String tag) {
16642        int callingUid = Binder.getCallingUid();
16643        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16644            throw new SecurityException(
16645                    "Cannot call " + tag + " from UID " + callingUid);
16646        }
16647    }
16648}
16649