PackageManagerService.java revision 389bb7f509fc74de3656492a9c474c11bcc96e5b
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
2291            // If this is the first boot or an update from pre-M, and it is a normal
2292            // boot, then we need to initialize the default preferred apps across
2293            // all defined users.
2294            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2295                for (UserInfo user : sUserManager.getUsers(true)) {
2296                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2297                    applyFactoryDefaultBrowserLPw(user.id);
2298                    primeDomainVerificationsLPw(user.id);
2299                }
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            // clear only after permissions and other defaults have been updated
2318            mExistingSystemPackages.clear();
2319            mPromoteSystemApps = false;
2320
2321            // All the changes are done during package scanning.
2322            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2323
2324            // can downgrade to reader
2325            mSettings.writeLPr();
2326
2327            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2328                    SystemClock.uptimeMillis());
2329
2330            mRequiredVerifierPackage = getRequiredVerifierLPr();
2331            mRequiredInstallerPackage = getRequiredInstallerLPr();
2332
2333            mInstallerService = new PackageInstallerService(context, this);
2334
2335            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2336            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2337                    mIntentFilterVerifierComponent);
2338
2339        } // synchronized (mPackages)
2340        } // synchronized (mInstallLock)
2341
2342        // Now after opening every single application zip, make sure they
2343        // are all flushed.  Not really needed, but keeps things nice and
2344        // tidy.
2345        Runtime.getRuntime().gc();
2346
2347        // Expose private service for system components to use.
2348        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2349    }
2350
2351    @Override
2352    public boolean isFirstBoot() {
2353        return !mRestoredSettings;
2354    }
2355
2356    @Override
2357    public boolean isOnlyCoreApps() {
2358        return mOnlyCore;
2359    }
2360
2361    @Override
2362    public boolean isUpgrade() {
2363        return mIsUpgrade;
2364    }
2365
2366    private String getRequiredVerifierLPr() {
2367        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2368        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2369                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2370
2371        String requiredVerifier = null;
2372
2373        final int N = receivers.size();
2374        for (int i = 0; i < N; i++) {
2375            final ResolveInfo info = receivers.get(i);
2376
2377            if (info.activityInfo == null) {
2378                continue;
2379            }
2380
2381            final String packageName = info.activityInfo.packageName;
2382
2383            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2384                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2385                continue;
2386            }
2387
2388            if (requiredVerifier != null) {
2389                throw new RuntimeException("There can be only one required verifier");
2390            }
2391
2392            requiredVerifier = packageName;
2393        }
2394
2395        return requiredVerifier;
2396    }
2397
2398    private String getRequiredInstallerLPr() {
2399        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2400        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2401        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2402
2403        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2404                PACKAGE_MIME_TYPE, 0, 0);
2405
2406        String requiredInstaller = null;
2407
2408        final int N = installers.size();
2409        for (int i = 0; i < N; i++) {
2410            final ResolveInfo info = installers.get(i);
2411            final String packageName = info.activityInfo.packageName;
2412
2413            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2414                continue;
2415            }
2416
2417            if (requiredInstaller != null) {
2418                throw new RuntimeException("There must be one required installer");
2419            }
2420
2421            requiredInstaller = packageName;
2422        }
2423
2424        if (requiredInstaller == null) {
2425            throw new RuntimeException("There must be one required installer");
2426        }
2427
2428        return requiredInstaller;
2429    }
2430
2431    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2432        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2433        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2434                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2435
2436        ComponentName verifierComponentName = null;
2437
2438        int priority = -1000;
2439        final int N = receivers.size();
2440        for (int i = 0; i < N; i++) {
2441            final ResolveInfo info = receivers.get(i);
2442
2443            if (info.activityInfo == null) {
2444                continue;
2445            }
2446
2447            final String packageName = info.activityInfo.packageName;
2448
2449            final PackageSetting ps = mSettings.mPackages.get(packageName);
2450            if (ps == null) {
2451                continue;
2452            }
2453
2454            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2455                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2456                continue;
2457            }
2458
2459            // Select the IntentFilterVerifier with the highest priority
2460            if (priority < info.priority) {
2461                priority = info.priority;
2462                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2463                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2464                        + verifierComponentName + " with priority: " + info.priority);
2465            }
2466        }
2467
2468        return verifierComponentName;
2469    }
2470
2471    private void primeDomainVerificationsLPw(int userId) {
2472        if (DEBUG_DOMAIN_VERIFICATION) {
2473            Slog.d(TAG, "Priming domain verifications in user " + userId);
2474        }
2475
2476        SystemConfig systemConfig = SystemConfig.getInstance();
2477        ArraySet<String> packages = systemConfig.getLinkedApps();
2478        ArraySet<String> domains = new ArraySet<String>();
2479
2480        for (String packageName : packages) {
2481            PackageParser.Package pkg = mPackages.get(packageName);
2482            if (pkg != null) {
2483                if (!pkg.isSystemApp()) {
2484                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2485                    continue;
2486                }
2487
2488                domains.clear();
2489                for (PackageParser.Activity a : pkg.activities) {
2490                    for (ActivityIntentInfo filter : a.intents) {
2491                        if (hasValidDomains(filter)) {
2492                            domains.addAll(filter.getHostsList());
2493                        }
2494                    }
2495                }
2496
2497                if (domains.size() > 0) {
2498                    if (DEBUG_DOMAIN_VERIFICATION) {
2499                        Slog.v(TAG, "      + " + packageName);
2500                    }
2501                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2502                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2503                    // and then 'always' in the per-user state actually used for intent resolution.
2504                    final IntentFilterVerificationInfo ivi;
2505                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2506                            new ArrayList<String>(domains));
2507                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2508                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2509                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2510                } else {
2511                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2512                            + "' does not handle web links");
2513                }
2514            } else {
2515                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2516            }
2517        }
2518
2519        scheduleWritePackageRestrictionsLocked(userId);
2520        scheduleWriteSettingsLocked();
2521    }
2522
2523    private void applyFactoryDefaultBrowserLPw(int userId) {
2524        // The default browser app's package name is stored in a string resource,
2525        // with a product-specific overlay used for vendor customization.
2526        String browserPkg = mContext.getResources().getString(
2527                com.android.internal.R.string.default_browser);
2528        if (!TextUtils.isEmpty(browserPkg)) {
2529            // non-empty string => required to be a known package
2530            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2531            if (ps == null) {
2532                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2533                browserPkg = null;
2534            } else {
2535                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2536            }
2537        }
2538
2539        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2540        // default.  If there's more than one, just leave everything alone.
2541        if (browserPkg == null) {
2542            calculateDefaultBrowserLPw(userId);
2543        }
2544    }
2545
2546    private void calculateDefaultBrowserLPw(int userId) {
2547        List<String> allBrowsers = resolveAllBrowserApps(userId);
2548        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2549        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2550    }
2551
2552    private List<String> resolveAllBrowserApps(int userId) {
2553        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2554        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2555                PackageManager.MATCH_ALL, userId);
2556
2557        final int count = list.size();
2558        List<String> result = new ArrayList<String>(count);
2559        for (int i=0; i<count; i++) {
2560            ResolveInfo info = list.get(i);
2561            if (info.activityInfo == null
2562                    || !info.handleAllWebDataURI
2563                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2564                    || result.contains(info.activityInfo.packageName)) {
2565                continue;
2566            }
2567            result.add(info.activityInfo.packageName);
2568        }
2569
2570        return result;
2571    }
2572
2573    private boolean packageIsBrowser(String packageName, int userId) {
2574        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2575                PackageManager.MATCH_ALL, userId);
2576        final int N = list.size();
2577        for (int i = 0; i < N; i++) {
2578            ResolveInfo info = list.get(i);
2579            if (packageName.equals(info.activityInfo.packageName)) {
2580                return true;
2581            }
2582        }
2583        return false;
2584    }
2585
2586    private void checkDefaultBrowser() {
2587        final int myUserId = UserHandle.myUserId();
2588        final String packageName = getDefaultBrowserPackageName(myUserId);
2589        if (packageName != null) {
2590            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2591            if (info == null) {
2592                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2593                synchronized (mPackages) {
2594                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2595                }
2596            }
2597        }
2598    }
2599
2600    @Override
2601    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2602            throws RemoteException {
2603        try {
2604            return super.onTransact(code, data, reply, flags);
2605        } catch (RuntimeException e) {
2606            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2607                Slog.wtf(TAG, "Package Manager Crash", e);
2608            }
2609            throw e;
2610        }
2611    }
2612
2613    void cleanupInstallFailedPackage(PackageSetting ps) {
2614        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2615
2616        removeDataDirsLI(ps.volumeUuid, ps.name);
2617        if (ps.codePath != null) {
2618            if (ps.codePath.isDirectory()) {
2619                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2620            } else {
2621                ps.codePath.delete();
2622            }
2623        }
2624        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2625            if (ps.resourcePath.isDirectory()) {
2626                FileUtils.deleteContents(ps.resourcePath);
2627            }
2628            ps.resourcePath.delete();
2629        }
2630        mSettings.removePackageLPw(ps.name);
2631    }
2632
2633    static int[] appendInts(int[] cur, int[] add) {
2634        if (add == null) return cur;
2635        if (cur == null) return add;
2636        final int N = add.length;
2637        for (int i=0; i<N; i++) {
2638            cur = appendInt(cur, add[i]);
2639        }
2640        return cur;
2641    }
2642
2643    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2644        if (!sUserManager.exists(userId)) return null;
2645        final PackageSetting ps = (PackageSetting) p.mExtras;
2646        if (ps == null) {
2647            return null;
2648        }
2649
2650        final PermissionsState permissionsState = ps.getPermissionsState();
2651
2652        final int[] gids = permissionsState.computeGids(userId);
2653        final Set<String> permissions = permissionsState.getPermissions(userId);
2654        final PackageUserState state = ps.readUserState(userId);
2655
2656        return PackageParser.generatePackageInfo(p, gids, flags,
2657                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2658    }
2659
2660    @Override
2661    public boolean isPackageFrozen(String packageName) {
2662        synchronized (mPackages) {
2663            final PackageSetting ps = mSettings.mPackages.get(packageName);
2664            if (ps != null) {
2665                return ps.frozen;
2666            }
2667        }
2668        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2669        return true;
2670    }
2671
2672    @Override
2673    public boolean isPackageAvailable(String packageName, int userId) {
2674        if (!sUserManager.exists(userId)) return false;
2675        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2676        synchronized (mPackages) {
2677            PackageParser.Package p = mPackages.get(packageName);
2678            if (p != null) {
2679                final PackageSetting ps = (PackageSetting) p.mExtras;
2680                if (ps != null) {
2681                    final PackageUserState state = ps.readUserState(userId);
2682                    if (state != null) {
2683                        return PackageParser.isAvailable(state);
2684                    }
2685                }
2686            }
2687        }
2688        return false;
2689    }
2690
2691    @Override
2692    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2693        if (!sUserManager.exists(userId)) return null;
2694        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2695        // reader
2696        synchronized (mPackages) {
2697            PackageParser.Package p = mPackages.get(packageName);
2698            if (DEBUG_PACKAGE_INFO)
2699                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2700            if (p != null) {
2701                return generatePackageInfo(p, flags, userId);
2702            }
2703            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2704                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2705            }
2706        }
2707        return null;
2708    }
2709
2710    @Override
2711    public String[] currentToCanonicalPackageNames(String[] names) {
2712        String[] out = new String[names.length];
2713        // reader
2714        synchronized (mPackages) {
2715            for (int i=names.length-1; i>=0; i--) {
2716                PackageSetting ps = mSettings.mPackages.get(names[i]);
2717                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2718            }
2719        }
2720        return out;
2721    }
2722
2723    @Override
2724    public String[] canonicalToCurrentPackageNames(String[] names) {
2725        String[] out = new String[names.length];
2726        // reader
2727        synchronized (mPackages) {
2728            for (int i=names.length-1; i>=0; i--) {
2729                String cur = mSettings.mRenamedPackages.get(names[i]);
2730                out[i] = cur != null ? cur : names[i];
2731            }
2732        }
2733        return out;
2734    }
2735
2736    @Override
2737    public int getPackageUid(String packageName, int userId) {
2738        if (!sUserManager.exists(userId)) return -1;
2739        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2740
2741        // reader
2742        synchronized (mPackages) {
2743            PackageParser.Package p = mPackages.get(packageName);
2744            if(p != null) {
2745                return UserHandle.getUid(userId, p.applicationInfo.uid);
2746            }
2747            PackageSetting ps = mSettings.mPackages.get(packageName);
2748            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2749                return -1;
2750            }
2751            p = ps.pkg;
2752            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2753        }
2754    }
2755
2756    @Override
2757    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2758        if (!sUserManager.exists(userId)) {
2759            return null;
2760        }
2761
2762        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2763                "getPackageGids");
2764
2765        // reader
2766        synchronized (mPackages) {
2767            PackageParser.Package p = mPackages.get(packageName);
2768            if (DEBUG_PACKAGE_INFO) {
2769                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2770            }
2771            if (p != null) {
2772                PackageSetting ps = (PackageSetting) p.mExtras;
2773                return ps.getPermissionsState().computeGids(userId);
2774            }
2775        }
2776
2777        return null;
2778    }
2779
2780    static PermissionInfo generatePermissionInfo(
2781            BasePermission bp, int flags) {
2782        if (bp.perm != null) {
2783            return PackageParser.generatePermissionInfo(bp.perm, flags);
2784        }
2785        PermissionInfo pi = new PermissionInfo();
2786        pi.name = bp.name;
2787        pi.packageName = bp.sourcePackage;
2788        pi.nonLocalizedLabel = bp.name;
2789        pi.protectionLevel = bp.protectionLevel;
2790        return pi;
2791    }
2792
2793    @Override
2794    public PermissionInfo getPermissionInfo(String name, int flags) {
2795        // reader
2796        synchronized (mPackages) {
2797            final BasePermission p = mSettings.mPermissions.get(name);
2798            if (p != null) {
2799                return generatePermissionInfo(p, flags);
2800            }
2801            return null;
2802        }
2803    }
2804
2805    @Override
2806    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2807        // reader
2808        synchronized (mPackages) {
2809            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2810            for (BasePermission p : mSettings.mPermissions.values()) {
2811                if (group == null) {
2812                    if (p.perm == null || p.perm.info.group == null) {
2813                        out.add(generatePermissionInfo(p, flags));
2814                    }
2815                } else {
2816                    if (p.perm != null && group.equals(p.perm.info.group)) {
2817                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2818                    }
2819                }
2820            }
2821
2822            if (out.size() > 0) {
2823                return out;
2824            }
2825            return mPermissionGroups.containsKey(group) ? out : null;
2826        }
2827    }
2828
2829    @Override
2830    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2831        // reader
2832        synchronized (mPackages) {
2833            return PackageParser.generatePermissionGroupInfo(
2834                    mPermissionGroups.get(name), flags);
2835        }
2836    }
2837
2838    @Override
2839    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2840        // reader
2841        synchronized (mPackages) {
2842            final int N = mPermissionGroups.size();
2843            ArrayList<PermissionGroupInfo> out
2844                    = new ArrayList<PermissionGroupInfo>(N);
2845            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2846                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2847            }
2848            return out;
2849        }
2850    }
2851
2852    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2853            int userId) {
2854        if (!sUserManager.exists(userId)) return null;
2855        PackageSetting ps = mSettings.mPackages.get(packageName);
2856        if (ps != null) {
2857            if (ps.pkg == null) {
2858                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2859                        flags, userId);
2860                if (pInfo != null) {
2861                    return pInfo.applicationInfo;
2862                }
2863                return null;
2864            }
2865            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2866                    ps.readUserState(userId), userId);
2867        }
2868        return null;
2869    }
2870
2871    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2872            int userId) {
2873        if (!sUserManager.exists(userId)) return null;
2874        PackageSetting ps = mSettings.mPackages.get(packageName);
2875        if (ps != null) {
2876            PackageParser.Package pkg = ps.pkg;
2877            if (pkg == null) {
2878                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2879                    return null;
2880                }
2881                // Only data remains, so we aren't worried about code paths
2882                pkg = new PackageParser.Package(packageName);
2883                pkg.applicationInfo.packageName = packageName;
2884                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2885                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2886                pkg.applicationInfo.dataDir = Environment
2887                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2888                        .getAbsolutePath();
2889                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2890                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2891            }
2892            return generatePackageInfo(pkg, flags, userId);
2893        }
2894        return null;
2895    }
2896
2897    @Override
2898    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2899        if (!sUserManager.exists(userId)) return null;
2900        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2901        // writer
2902        synchronized (mPackages) {
2903            PackageParser.Package p = mPackages.get(packageName);
2904            if (DEBUG_PACKAGE_INFO) Log.v(
2905                    TAG, "getApplicationInfo " + packageName
2906                    + ": " + p);
2907            if (p != null) {
2908                PackageSetting ps = mSettings.mPackages.get(packageName);
2909                if (ps == null) return null;
2910                // Note: isEnabledLP() does not apply here - always return info
2911                return PackageParser.generateApplicationInfo(
2912                        p, flags, ps.readUserState(userId), userId);
2913            }
2914            if ("android".equals(packageName)||"system".equals(packageName)) {
2915                return mAndroidApplication;
2916            }
2917            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2918                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2919            }
2920        }
2921        return null;
2922    }
2923
2924    @Override
2925    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2926            final IPackageDataObserver observer) {
2927        mContext.enforceCallingOrSelfPermission(
2928                android.Manifest.permission.CLEAR_APP_CACHE, null);
2929        // Queue up an async operation since clearing cache may take a little while.
2930        mHandler.post(new Runnable() {
2931            public void run() {
2932                mHandler.removeCallbacks(this);
2933                int retCode = -1;
2934                synchronized (mInstallLock) {
2935                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2936                    if (retCode < 0) {
2937                        Slog.w(TAG, "Couldn't clear application caches");
2938                    }
2939                }
2940                if (observer != null) {
2941                    try {
2942                        observer.onRemoveCompleted(null, (retCode >= 0));
2943                    } catch (RemoteException e) {
2944                        Slog.w(TAG, "RemoveException when invoking call back");
2945                    }
2946                }
2947            }
2948        });
2949    }
2950
2951    @Override
2952    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2953            final IntentSender pi) {
2954        mContext.enforceCallingOrSelfPermission(
2955                android.Manifest.permission.CLEAR_APP_CACHE, null);
2956        // Queue up an async operation since clearing cache may take a little while.
2957        mHandler.post(new Runnable() {
2958            public void run() {
2959                mHandler.removeCallbacks(this);
2960                int retCode = -1;
2961                synchronized (mInstallLock) {
2962                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2963                    if (retCode < 0) {
2964                        Slog.w(TAG, "Couldn't clear application caches");
2965                    }
2966                }
2967                if(pi != null) {
2968                    try {
2969                        // Callback via pending intent
2970                        int code = (retCode >= 0) ? 1 : 0;
2971                        pi.sendIntent(null, code, null,
2972                                null, null);
2973                    } catch (SendIntentException e1) {
2974                        Slog.i(TAG, "Failed to send pending intent");
2975                    }
2976                }
2977            }
2978        });
2979    }
2980
2981    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2982        synchronized (mInstallLock) {
2983            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2984                throw new IOException("Failed to free enough space");
2985            }
2986        }
2987    }
2988
2989    @Override
2990    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2991        if (!sUserManager.exists(userId)) return null;
2992        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2993        synchronized (mPackages) {
2994            PackageParser.Activity a = mActivities.mActivities.get(component);
2995
2996            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2997            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2998                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2999                if (ps == null) return null;
3000                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3001                        userId);
3002            }
3003            if (mResolveComponentName.equals(component)) {
3004                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3005                        new PackageUserState(), userId);
3006            }
3007        }
3008        return null;
3009    }
3010
3011    @Override
3012    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3013            String resolvedType) {
3014        synchronized (mPackages) {
3015            if (component.equals(mResolveComponentName)) {
3016                // The resolver supports EVERYTHING!
3017                return true;
3018            }
3019            PackageParser.Activity a = mActivities.mActivities.get(component);
3020            if (a == null) {
3021                return false;
3022            }
3023            for (int i=0; i<a.intents.size(); i++) {
3024                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3025                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3026                    return true;
3027                }
3028            }
3029            return false;
3030        }
3031    }
3032
3033    @Override
3034    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3035        if (!sUserManager.exists(userId)) return null;
3036        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3037        synchronized (mPackages) {
3038            PackageParser.Activity a = mReceivers.mActivities.get(component);
3039            if (DEBUG_PACKAGE_INFO) Log.v(
3040                TAG, "getReceiverInfo " + component + ": " + a);
3041            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3042                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3043                if (ps == null) return null;
3044                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3045                        userId);
3046            }
3047        }
3048        return null;
3049    }
3050
3051    @Override
3052    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3053        if (!sUserManager.exists(userId)) return null;
3054        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3055        synchronized (mPackages) {
3056            PackageParser.Service s = mServices.mServices.get(component);
3057            if (DEBUG_PACKAGE_INFO) Log.v(
3058                TAG, "getServiceInfo " + component + ": " + s);
3059            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3060                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3061                if (ps == null) return null;
3062                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3063                        userId);
3064            }
3065        }
3066        return null;
3067    }
3068
3069    @Override
3070    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3071        if (!sUserManager.exists(userId)) return null;
3072        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3073        synchronized (mPackages) {
3074            PackageParser.Provider p = mProviders.mProviders.get(component);
3075            if (DEBUG_PACKAGE_INFO) Log.v(
3076                TAG, "getProviderInfo " + component + ": " + p);
3077            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3078                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3079                if (ps == null) return null;
3080                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3081                        userId);
3082            }
3083        }
3084        return null;
3085    }
3086
3087    @Override
3088    public String[] getSystemSharedLibraryNames() {
3089        Set<String> libSet;
3090        synchronized (mPackages) {
3091            libSet = mSharedLibraries.keySet();
3092            int size = libSet.size();
3093            if (size > 0) {
3094                String[] libs = new String[size];
3095                libSet.toArray(libs);
3096                return libs;
3097            }
3098        }
3099        return null;
3100    }
3101
3102    /**
3103     * @hide
3104     */
3105    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3106        synchronized (mPackages) {
3107            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3108            if (lib != null && lib.apk != null) {
3109                return mPackages.get(lib.apk);
3110            }
3111        }
3112        return null;
3113    }
3114
3115    @Override
3116    public FeatureInfo[] getSystemAvailableFeatures() {
3117        Collection<FeatureInfo> featSet;
3118        synchronized (mPackages) {
3119            featSet = mAvailableFeatures.values();
3120            int size = featSet.size();
3121            if (size > 0) {
3122                FeatureInfo[] features = new FeatureInfo[size+1];
3123                featSet.toArray(features);
3124                FeatureInfo fi = new FeatureInfo();
3125                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3126                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3127                features[size] = fi;
3128                return features;
3129            }
3130        }
3131        return null;
3132    }
3133
3134    @Override
3135    public boolean hasSystemFeature(String name) {
3136        synchronized (mPackages) {
3137            return mAvailableFeatures.containsKey(name);
3138        }
3139    }
3140
3141    private void checkValidCaller(int uid, int userId) {
3142        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3143            return;
3144
3145        throw new SecurityException("Caller uid=" + uid
3146                + " is not privileged to communicate with user=" + userId);
3147    }
3148
3149    @Override
3150    public int checkPermission(String permName, String pkgName, int userId) {
3151        if (!sUserManager.exists(userId)) {
3152            return PackageManager.PERMISSION_DENIED;
3153        }
3154
3155        synchronized (mPackages) {
3156            final PackageParser.Package p = mPackages.get(pkgName);
3157            if (p != null && p.mExtras != null) {
3158                final PackageSetting ps = (PackageSetting) p.mExtras;
3159                final PermissionsState permissionsState = ps.getPermissionsState();
3160                if (permissionsState.hasPermission(permName, userId)) {
3161                    return PackageManager.PERMISSION_GRANTED;
3162                }
3163                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3164                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3165                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3166                    return PackageManager.PERMISSION_GRANTED;
3167                }
3168            }
3169        }
3170
3171        return PackageManager.PERMISSION_DENIED;
3172    }
3173
3174    @Override
3175    public int checkUidPermission(String permName, int uid) {
3176        final int userId = UserHandle.getUserId(uid);
3177
3178        if (!sUserManager.exists(userId)) {
3179            return PackageManager.PERMISSION_DENIED;
3180        }
3181
3182        synchronized (mPackages) {
3183            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3184            if (obj != null) {
3185                final SettingBase ps = (SettingBase) obj;
3186                final PermissionsState permissionsState = ps.getPermissionsState();
3187                if (permissionsState.hasPermission(permName, userId)) {
3188                    return PackageManager.PERMISSION_GRANTED;
3189                }
3190                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3191                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3192                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3193                    return PackageManager.PERMISSION_GRANTED;
3194                }
3195            } else {
3196                ArraySet<String> perms = mSystemPermissions.get(uid);
3197                if (perms != null) {
3198                    if (perms.contains(permName)) {
3199                        return PackageManager.PERMISSION_GRANTED;
3200                    }
3201                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3202                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3203                        return PackageManager.PERMISSION_GRANTED;
3204                    }
3205                }
3206            }
3207        }
3208
3209        return PackageManager.PERMISSION_DENIED;
3210    }
3211
3212    @Override
3213    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3214        if (UserHandle.getCallingUserId() != userId) {
3215            mContext.enforceCallingPermission(
3216                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3217                    "isPermissionRevokedByPolicy for user " + userId);
3218        }
3219
3220        if (checkPermission(permission, packageName, userId)
3221                == PackageManager.PERMISSION_GRANTED) {
3222            return false;
3223        }
3224
3225        final long identity = Binder.clearCallingIdentity();
3226        try {
3227            final int flags = getPermissionFlags(permission, packageName, userId);
3228            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3229        } finally {
3230            Binder.restoreCallingIdentity(identity);
3231        }
3232    }
3233
3234    @Override
3235    public String getPermissionControllerPackageName() {
3236        synchronized (mPackages) {
3237            return mRequiredInstallerPackage;
3238        }
3239    }
3240
3241    /**
3242     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3243     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3244     * @param checkShell TODO(yamasani):
3245     * @param message the message to log on security exception
3246     */
3247    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3248            boolean checkShell, String message) {
3249        if (userId < 0) {
3250            throw new IllegalArgumentException("Invalid userId " + userId);
3251        }
3252        if (checkShell) {
3253            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3254        }
3255        if (userId == UserHandle.getUserId(callingUid)) return;
3256        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3257            if (requireFullPermission) {
3258                mContext.enforceCallingOrSelfPermission(
3259                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3260            } else {
3261                try {
3262                    mContext.enforceCallingOrSelfPermission(
3263                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3264                } catch (SecurityException se) {
3265                    mContext.enforceCallingOrSelfPermission(
3266                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3267                }
3268            }
3269        }
3270    }
3271
3272    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3273        if (callingUid == Process.SHELL_UID) {
3274            if (userHandle >= 0
3275                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3276                throw new SecurityException("Shell does not have permission to access user "
3277                        + userHandle);
3278            } else if (userHandle < 0) {
3279                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3280                        + Debug.getCallers(3));
3281            }
3282        }
3283    }
3284
3285    private BasePermission findPermissionTreeLP(String permName) {
3286        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3287            if (permName.startsWith(bp.name) &&
3288                    permName.length() > bp.name.length() &&
3289                    permName.charAt(bp.name.length()) == '.') {
3290                return bp;
3291            }
3292        }
3293        return null;
3294    }
3295
3296    private BasePermission checkPermissionTreeLP(String permName) {
3297        if (permName != null) {
3298            BasePermission bp = findPermissionTreeLP(permName);
3299            if (bp != null) {
3300                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3301                    return bp;
3302                }
3303                throw new SecurityException("Calling uid "
3304                        + Binder.getCallingUid()
3305                        + " is not allowed to add to permission tree "
3306                        + bp.name + " owned by uid " + bp.uid);
3307            }
3308        }
3309        throw new SecurityException("No permission tree found for " + permName);
3310    }
3311
3312    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3313        if (s1 == null) {
3314            return s2 == null;
3315        }
3316        if (s2 == null) {
3317            return false;
3318        }
3319        if (s1.getClass() != s2.getClass()) {
3320            return false;
3321        }
3322        return s1.equals(s2);
3323    }
3324
3325    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3326        if (pi1.icon != pi2.icon) return false;
3327        if (pi1.logo != pi2.logo) return false;
3328        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3329        if (!compareStrings(pi1.name, pi2.name)) return false;
3330        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3331        // We'll take care of setting this one.
3332        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3333        // These are not currently stored in settings.
3334        //if (!compareStrings(pi1.group, pi2.group)) return false;
3335        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3336        //if (pi1.labelRes != pi2.labelRes) return false;
3337        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3338        return true;
3339    }
3340
3341    int permissionInfoFootprint(PermissionInfo info) {
3342        int size = info.name.length();
3343        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3344        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3345        return size;
3346    }
3347
3348    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3349        int size = 0;
3350        for (BasePermission perm : mSettings.mPermissions.values()) {
3351            if (perm.uid == tree.uid) {
3352                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3353            }
3354        }
3355        return size;
3356    }
3357
3358    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3359        // We calculate the max size of permissions defined by this uid and throw
3360        // if that plus the size of 'info' would exceed our stated maximum.
3361        if (tree.uid != Process.SYSTEM_UID) {
3362            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3363            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3364                throw new SecurityException("Permission tree size cap exceeded");
3365            }
3366        }
3367    }
3368
3369    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3370        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3371            throw new SecurityException("Label must be specified in permission");
3372        }
3373        BasePermission tree = checkPermissionTreeLP(info.name);
3374        BasePermission bp = mSettings.mPermissions.get(info.name);
3375        boolean added = bp == null;
3376        boolean changed = true;
3377        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3378        if (added) {
3379            enforcePermissionCapLocked(info, tree);
3380            bp = new BasePermission(info.name, tree.sourcePackage,
3381                    BasePermission.TYPE_DYNAMIC);
3382        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3383            throw new SecurityException(
3384                    "Not allowed to modify non-dynamic permission "
3385                    + info.name);
3386        } else {
3387            if (bp.protectionLevel == fixedLevel
3388                    && bp.perm.owner.equals(tree.perm.owner)
3389                    && bp.uid == tree.uid
3390                    && comparePermissionInfos(bp.perm.info, info)) {
3391                changed = false;
3392            }
3393        }
3394        bp.protectionLevel = fixedLevel;
3395        info = new PermissionInfo(info);
3396        info.protectionLevel = fixedLevel;
3397        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3398        bp.perm.info.packageName = tree.perm.info.packageName;
3399        bp.uid = tree.uid;
3400        if (added) {
3401            mSettings.mPermissions.put(info.name, bp);
3402        }
3403        if (changed) {
3404            if (!async) {
3405                mSettings.writeLPr();
3406            } else {
3407                scheduleWriteSettingsLocked();
3408            }
3409        }
3410        return added;
3411    }
3412
3413    @Override
3414    public boolean addPermission(PermissionInfo info) {
3415        synchronized (mPackages) {
3416            return addPermissionLocked(info, false);
3417        }
3418    }
3419
3420    @Override
3421    public boolean addPermissionAsync(PermissionInfo info) {
3422        synchronized (mPackages) {
3423            return addPermissionLocked(info, true);
3424        }
3425    }
3426
3427    @Override
3428    public void removePermission(String name) {
3429        synchronized (mPackages) {
3430            checkPermissionTreeLP(name);
3431            BasePermission bp = mSettings.mPermissions.get(name);
3432            if (bp != null) {
3433                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3434                    throw new SecurityException(
3435                            "Not allowed to modify non-dynamic permission "
3436                            + name);
3437                }
3438                mSettings.mPermissions.remove(name);
3439                mSettings.writeLPr();
3440            }
3441        }
3442    }
3443
3444    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3445            BasePermission bp) {
3446        int index = pkg.requestedPermissions.indexOf(bp.name);
3447        if (index == -1) {
3448            throw new SecurityException("Package " + pkg.packageName
3449                    + " has not requested permission " + bp.name);
3450        }
3451        if (!bp.isRuntime() && !bp.isDevelopment()) {
3452            throw new SecurityException("Permission " + bp.name
3453                    + " is not a changeable permission type");
3454        }
3455    }
3456
3457    @Override
3458    public void grantRuntimePermission(String packageName, String name, final int userId) {
3459        if (!sUserManager.exists(userId)) {
3460            Log.e(TAG, "No such user:" + userId);
3461            return;
3462        }
3463
3464        mContext.enforceCallingOrSelfPermission(
3465                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3466                "grantRuntimePermission");
3467
3468        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3469                "grantRuntimePermission");
3470
3471        final int uid;
3472        final SettingBase sb;
3473
3474        synchronized (mPackages) {
3475            final PackageParser.Package pkg = mPackages.get(packageName);
3476            if (pkg == null) {
3477                throw new IllegalArgumentException("Unknown package: " + packageName);
3478            }
3479
3480            final BasePermission bp = mSettings.mPermissions.get(name);
3481            if (bp == null) {
3482                throw new IllegalArgumentException("Unknown permission: " + name);
3483            }
3484
3485            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3486
3487            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3488            sb = (SettingBase) pkg.mExtras;
3489            if (sb == null) {
3490                throw new IllegalArgumentException("Unknown package: " + packageName);
3491            }
3492
3493            final PermissionsState permissionsState = sb.getPermissionsState();
3494
3495            final int flags = permissionsState.getPermissionFlags(name, userId);
3496            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3497                throw new SecurityException("Cannot grant system fixed permission: "
3498                        + name + " for package: " + packageName);
3499            }
3500
3501            if (bp.isDevelopment()) {
3502                // Development permissions must be handled specially, since they are not
3503                // normal runtime permissions.  For now they apply to all users.
3504                if (permissionsState.grantInstallPermission(bp) !=
3505                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3506                    scheduleWriteSettingsLocked();
3507                }
3508                return;
3509            }
3510
3511            final int result = permissionsState.grantRuntimePermission(bp, userId);
3512            switch (result) {
3513                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3514                    return;
3515                }
3516
3517                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3518                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3519                    mHandler.post(new Runnable() {
3520                        @Override
3521                        public void run() {
3522                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3523                        }
3524                    });
3525                } break;
3526            }
3527
3528            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3529
3530            // Not critical if that is lost - app has to request again.
3531            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3532        }
3533
3534        // Only need to do this if user is initialized. Otherwise it's a new user
3535        // and there are no processes running as the user yet and there's no need
3536        // to make an expensive call to remount processes for the changed permissions.
3537        if (READ_EXTERNAL_STORAGE.equals(name)
3538                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3539            final long token = Binder.clearCallingIdentity();
3540            try {
3541                if (sUserManager.isInitialized(userId)) {
3542                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3543                            MountServiceInternal.class);
3544                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3545                }
3546            } finally {
3547                Binder.restoreCallingIdentity(token);
3548            }
3549        }
3550    }
3551
3552    @Override
3553    public void revokeRuntimePermission(String packageName, String name, int userId) {
3554        if (!sUserManager.exists(userId)) {
3555            Log.e(TAG, "No such user:" + userId);
3556            return;
3557        }
3558
3559        mContext.enforceCallingOrSelfPermission(
3560                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3561                "revokeRuntimePermission");
3562
3563        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3564                "revokeRuntimePermission");
3565
3566        final int appId;
3567
3568        synchronized (mPackages) {
3569            final PackageParser.Package pkg = mPackages.get(packageName);
3570            if (pkg == null) {
3571                throw new IllegalArgumentException("Unknown package: " + packageName);
3572            }
3573
3574            final BasePermission bp = mSettings.mPermissions.get(name);
3575            if (bp == null) {
3576                throw new IllegalArgumentException("Unknown permission: " + name);
3577            }
3578
3579            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3580
3581            SettingBase sb = (SettingBase) pkg.mExtras;
3582            if (sb == null) {
3583                throw new IllegalArgumentException("Unknown package: " + packageName);
3584            }
3585
3586            final PermissionsState permissionsState = sb.getPermissionsState();
3587
3588            final int flags = permissionsState.getPermissionFlags(name, userId);
3589            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3590                throw new SecurityException("Cannot revoke system fixed permission: "
3591                        + name + " for package: " + packageName);
3592            }
3593
3594            if (bp.isDevelopment()) {
3595                // Development permissions must be handled specially, since they are not
3596                // normal runtime permissions.  For now they apply to all users.
3597                if (permissionsState.revokeInstallPermission(bp) !=
3598                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3599                    scheduleWriteSettingsLocked();
3600                }
3601                return;
3602            }
3603
3604            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3605                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3606                return;
3607            }
3608
3609            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3610
3611            // Critical, after this call app should never have the permission.
3612            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3613
3614            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3615        }
3616
3617        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3618    }
3619
3620    @Override
3621    public void resetRuntimePermissions() {
3622        mContext.enforceCallingOrSelfPermission(
3623                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3624                "revokeRuntimePermission");
3625
3626        int callingUid = Binder.getCallingUid();
3627        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3628            mContext.enforceCallingOrSelfPermission(
3629                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3630                    "resetRuntimePermissions");
3631        }
3632
3633        synchronized (mPackages) {
3634            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3635            for (int userId : UserManagerService.getInstance().getUserIds()) {
3636                final int packageCount = mPackages.size();
3637                for (int i = 0; i < packageCount; i++) {
3638                    PackageParser.Package pkg = mPackages.valueAt(i);
3639                    if (!(pkg.mExtras instanceof PackageSetting)) {
3640                        continue;
3641                    }
3642                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3643                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3644                }
3645            }
3646        }
3647    }
3648
3649    @Override
3650    public int getPermissionFlags(String name, String packageName, int userId) {
3651        if (!sUserManager.exists(userId)) {
3652            return 0;
3653        }
3654
3655        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3656
3657        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3658                "getPermissionFlags");
3659
3660        synchronized (mPackages) {
3661            final PackageParser.Package pkg = mPackages.get(packageName);
3662            if (pkg == null) {
3663                throw new IllegalArgumentException("Unknown package: " + packageName);
3664            }
3665
3666            final BasePermission bp = mSettings.mPermissions.get(name);
3667            if (bp == null) {
3668                throw new IllegalArgumentException("Unknown permission: " + name);
3669            }
3670
3671            SettingBase sb = (SettingBase) pkg.mExtras;
3672            if (sb == null) {
3673                throw new IllegalArgumentException("Unknown package: " + packageName);
3674            }
3675
3676            PermissionsState permissionsState = sb.getPermissionsState();
3677            return permissionsState.getPermissionFlags(name, userId);
3678        }
3679    }
3680
3681    @Override
3682    public void updatePermissionFlags(String name, String packageName, int flagMask,
3683            int flagValues, int userId) {
3684        if (!sUserManager.exists(userId)) {
3685            return;
3686        }
3687
3688        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3689
3690        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3691                "updatePermissionFlags");
3692
3693        // Only the system can change these flags and nothing else.
3694        if (getCallingUid() != Process.SYSTEM_UID) {
3695            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3696            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3697            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3698            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3699        }
3700
3701        synchronized (mPackages) {
3702            final PackageParser.Package pkg = mPackages.get(packageName);
3703            if (pkg == null) {
3704                throw new IllegalArgumentException("Unknown package: " + packageName);
3705            }
3706
3707            final BasePermission bp = mSettings.mPermissions.get(name);
3708            if (bp == null) {
3709                throw new IllegalArgumentException("Unknown permission: " + name);
3710            }
3711
3712            SettingBase sb = (SettingBase) pkg.mExtras;
3713            if (sb == null) {
3714                throw new IllegalArgumentException("Unknown package: " + packageName);
3715            }
3716
3717            PermissionsState permissionsState = sb.getPermissionsState();
3718
3719            // Only the package manager can change flags for system component permissions.
3720            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3721            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3722                return;
3723            }
3724
3725            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3726
3727            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3728                // Install and runtime permissions are stored in different places,
3729                // so figure out what permission changed and persist the change.
3730                if (permissionsState.getInstallPermissionState(name) != null) {
3731                    scheduleWriteSettingsLocked();
3732                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3733                        || hadState) {
3734                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3735                }
3736            }
3737        }
3738    }
3739
3740    /**
3741     * Update the permission flags for all packages and runtime permissions of a user in order
3742     * to allow device or profile owner to remove POLICY_FIXED.
3743     */
3744    @Override
3745    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3746        if (!sUserManager.exists(userId)) {
3747            return;
3748        }
3749
3750        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3751
3752        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3753                "updatePermissionFlagsForAllApps");
3754
3755        // Only the system can change system fixed flags.
3756        if (getCallingUid() != Process.SYSTEM_UID) {
3757            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3758            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3759        }
3760
3761        synchronized (mPackages) {
3762            boolean changed = false;
3763            final int packageCount = mPackages.size();
3764            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3765                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3766                SettingBase sb = (SettingBase) pkg.mExtras;
3767                if (sb == null) {
3768                    continue;
3769                }
3770                PermissionsState permissionsState = sb.getPermissionsState();
3771                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3772                        userId, flagMask, flagValues);
3773            }
3774            if (changed) {
3775                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3776            }
3777        }
3778    }
3779
3780    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3781        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3782                != PackageManager.PERMISSION_GRANTED
3783            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3784                != PackageManager.PERMISSION_GRANTED) {
3785            throw new SecurityException(message + " requires "
3786                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3787                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3788        }
3789    }
3790
3791    @Override
3792    public boolean shouldShowRequestPermissionRationale(String permissionName,
3793            String packageName, int userId) {
3794        if (UserHandle.getCallingUserId() != userId) {
3795            mContext.enforceCallingPermission(
3796                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3797                    "canShowRequestPermissionRationale for user " + userId);
3798        }
3799
3800        final int uid = getPackageUid(packageName, userId);
3801        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3802            return false;
3803        }
3804
3805        if (checkPermission(permissionName, packageName, userId)
3806                == PackageManager.PERMISSION_GRANTED) {
3807            return false;
3808        }
3809
3810        final int flags;
3811
3812        final long identity = Binder.clearCallingIdentity();
3813        try {
3814            flags = getPermissionFlags(permissionName,
3815                    packageName, userId);
3816        } finally {
3817            Binder.restoreCallingIdentity(identity);
3818        }
3819
3820        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3821                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3822                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3823
3824        if ((flags & fixedFlags) != 0) {
3825            return false;
3826        }
3827
3828        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3829    }
3830
3831    @Override
3832    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3833        mContext.enforceCallingOrSelfPermission(
3834                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3835                "addOnPermissionsChangeListener");
3836
3837        synchronized (mPackages) {
3838            mOnPermissionChangeListeners.addListenerLocked(listener);
3839        }
3840    }
3841
3842    @Override
3843    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3844        synchronized (mPackages) {
3845            mOnPermissionChangeListeners.removeListenerLocked(listener);
3846        }
3847    }
3848
3849    @Override
3850    public boolean isProtectedBroadcast(String actionName) {
3851        synchronized (mPackages) {
3852            return mProtectedBroadcasts.contains(actionName);
3853        }
3854    }
3855
3856    @Override
3857    public int checkSignatures(String pkg1, String pkg2) {
3858        synchronized (mPackages) {
3859            final PackageParser.Package p1 = mPackages.get(pkg1);
3860            final PackageParser.Package p2 = mPackages.get(pkg2);
3861            if (p1 == null || p1.mExtras == null
3862                    || p2 == null || p2.mExtras == null) {
3863                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3864            }
3865            return compareSignatures(p1.mSignatures, p2.mSignatures);
3866        }
3867    }
3868
3869    @Override
3870    public int checkUidSignatures(int uid1, int uid2) {
3871        // Map to base uids.
3872        uid1 = UserHandle.getAppId(uid1);
3873        uid2 = UserHandle.getAppId(uid2);
3874        // reader
3875        synchronized (mPackages) {
3876            Signature[] s1;
3877            Signature[] s2;
3878            Object obj = mSettings.getUserIdLPr(uid1);
3879            if (obj != null) {
3880                if (obj instanceof SharedUserSetting) {
3881                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3882                } else if (obj instanceof PackageSetting) {
3883                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3884                } else {
3885                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3886                }
3887            } else {
3888                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3889            }
3890            obj = mSettings.getUserIdLPr(uid2);
3891            if (obj != null) {
3892                if (obj instanceof SharedUserSetting) {
3893                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3894                } else if (obj instanceof PackageSetting) {
3895                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3896                } else {
3897                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3898                }
3899            } else {
3900                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3901            }
3902            return compareSignatures(s1, s2);
3903        }
3904    }
3905
3906    private void killUid(int appId, int userId, String reason) {
3907        final long identity = Binder.clearCallingIdentity();
3908        try {
3909            IActivityManager am = ActivityManagerNative.getDefault();
3910            if (am != null) {
3911                try {
3912                    am.killUid(appId, userId, reason);
3913                } catch (RemoteException e) {
3914                    /* ignore - same process */
3915                }
3916            }
3917        } finally {
3918            Binder.restoreCallingIdentity(identity);
3919        }
3920    }
3921
3922    /**
3923     * Compares two sets of signatures. Returns:
3924     * <br />
3925     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3926     * <br />
3927     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3928     * <br />
3929     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3930     * <br />
3931     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3932     * <br />
3933     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3934     */
3935    static int compareSignatures(Signature[] s1, Signature[] s2) {
3936        if (s1 == null) {
3937            return s2 == null
3938                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3939                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3940        }
3941
3942        if (s2 == null) {
3943            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3944        }
3945
3946        if (s1.length != s2.length) {
3947            return PackageManager.SIGNATURE_NO_MATCH;
3948        }
3949
3950        // Since both signature sets are of size 1, we can compare without HashSets.
3951        if (s1.length == 1) {
3952            return s1[0].equals(s2[0]) ?
3953                    PackageManager.SIGNATURE_MATCH :
3954                    PackageManager.SIGNATURE_NO_MATCH;
3955        }
3956
3957        ArraySet<Signature> set1 = new ArraySet<Signature>();
3958        for (Signature sig : s1) {
3959            set1.add(sig);
3960        }
3961        ArraySet<Signature> set2 = new ArraySet<Signature>();
3962        for (Signature sig : s2) {
3963            set2.add(sig);
3964        }
3965        // Make sure s2 contains all signatures in s1.
3966        if (set1.equals(set2)) {
3967            return PackageManager.SIGNATURE_MATCH;
3968        }
3969        return PackageManager.SIGNATURE_NO_MATCH;
3970    }
3971
3972    /**
3973     * If the database version for this type of package (internal storage or
3974     * external storage) is less than the version where package signatures
3975     * were updated, return true.
3976     */
3977    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3978        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3979        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3980    }
3981
3982    /**
3983     * Used for backward compatibility to make sure any packages with
3984     * certificate chains get upgraded to the new style. {@code existingSigs}
3985     * will be in the old format (since they were stored on disk from before the
3986     * system upgrade) and {@code scannedSigs} will be in the newer format.
3987     */
3988    private int compareSignaturesCompat(PackageSignatures existingSigs,
3989            PackageParser.Package scannedPkg) {
3990        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3991            return PackageManager.SIGNATURE_NO_MATCH;
3992        }
3993
3994        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3995        for (Signature sig : existingSigs.mSignatures) {
3996            existingSet.add(sig);
3997        }
3998        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3999        for (Signature sig : scannedPkg.mSignatures) {
4000            try {
4001                Signature[] chainSignatures = sig.getChainSignatures();
4002                for (Signature chainSig : chainSignatures) {
4003                    scannedCompatSet.add(chainSig);
4004                }
4005            } catch (CertificateEncodingException e) {
4006                scannedCompatSet.add(sig);
4007            }
4008        }
4009        /*
4010         * Make sure the expanded scanned set contains all signatures in the
4011         * existing one.
4012         */
4013        if (scannedCompatSet.equals(existingSet)) {
4014            // Migrate the old signatures to the new scheme.
4015            existingSigs.assignSignatures(scannedPkg.mSignatures);
4016            // The new KeySets will be re-added later in the scanning process.
4017            synchronized (mPackages) {
4018                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4019            }
4020            return PackageManager.SIGNATURE_MATCH;
4021        }
4022        return PackageManager.SIGNATURE_NO_MATCH;
4023    }
4024
4025    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4026        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4027        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4028    }
4029
4030    private int compareSignaturesRecover(PackageSignatures existingSigs,
4031            PackageParser.Package scannedPkg) {
4032        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4033            return PackageManager.SIGNATURE_NO_MATCH;
4034        }
4035
4036        String msg = null;
4037        try {
4038            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4039                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4040                        + scannedPkg.packageName);
4041                return PackageManager.SIGNATURE_MATCH;
4042            }
4043        } catch (CertificateException e) {
4044            msg = e.getMessage();
4045        }
4046
4047        logCriticalInfo(Log.INFO,
4048                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4049        return PackageManager.SIGNATURE_NO_MATCH;
4050    }
4051
4052    @Override
4053    public String[] getPackagesForUid(int uid) {
4054        uid = UserHandle.getAppId(uid);
4055        // reader
4056        synchronized (mPackages) {
4057            Object obj = mSettings.getUserIdLPr(uid);
4058            if (obj instanceof SharedUserSetting) {
4059                final SharedUserSetting sus = (SharedUserSetting) obj;
4060                final int N = sus.packages.size();
4061                final String[] res = new String[N];
4062                final Iterator<PackageSetting> it = sus.packages.iterator();
4063                int i = 0;
4064                while (it.hasNext()) {
4065                    res[i++] = it.next().name;
4066                }
4067                return res;
4068            } else if (obj instanceof PackageSetting) {
4069                final PackageSetting ps = (PackageSetting) obj;
4070                return new String[] { ps.name };
4071            }
4072        }
4073        return null;
4074    }
4075
4076    @Override
4077    public String getNameForUid(int uid) {
4078        // reader
4079        synchronized (mPackages) {
4080            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4081            if (obj instanceof SharedUserSetting) {
4082                final SharedUserSetting sus = (SharedUserSetting) obj;
4083                return sus.name + ":" + sus.userId;
4084            } else if (obj instanceof PackageSetting) {
4085                final PackageSetting ps = (PackageSetting) obj;
4086                return ps.name;
4087            }
4088        }
4089        return null;
4090    }
4091
4092    @Override
4093    public int getUidForSharedUser(String sharedUserName) {
4094        if(sharedUserName == null) {
4095            return -1;
4096        }
4097        // reader
4098        synchronized (mPackages) {
4099            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4100            if (suid == null) {
4101                return -1;
4102            }
4103            return suid.userId;
4104        }
4105    }
4106
4107    @Override
4108    public int getFlagsForUid(int uid) {
4109        synchronized (mPackages) {
4110            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4111            if (obj instanceof SharedUserSetting) {
4112                final SharedUserSetting sus = (SharedUserSetting) obj;
4113                return sus.pkgFlags;
4114            } else if (obj instanceof PackageSetting) {
4115                final PackageSetting ps = (PackageSetting) obj;
4116                return ps.pkgFlags;
4117            }
4118        }
4119        return 0;
4120    }
4121
4122    @Override
4123    public int getPrivateFlagsForUid(int uid) {
4124        synchronized (mPackages) {
4125            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4126            if (obj instanceof SharedUserSetting) {
4127                final SharedUserSetting sus = (SharedUserSetting) obj;
4128                return sus.pkgPrivateFlags;
4129            } else if (obj instanceof PackageSetting) {
4130                final PackageSetting ps = (PackageSetting) obj;
4131                return ps.pkgPrivateFlags;
4132            }
4133        }
4134        return 0;
4135    }
4136
4137    @Override
4138    public boolean isUidPrivileged(int uid) {
4139        uid = UserHandle.getAppId(uid);
4140        // reader
4141        synchronized (mPackages) {
4142            Object obj = mSettings.getUserIdLPr(uid);
4143            if (obj instanceof SharedUserSetting) {
4144                final SharedUserSetting sus = (SharedUserSetting) obj;
4145                final Iterator<PackageSetting> it = sus.packages.iterator();
4146                while (it.hasNext()) {
4147                    if (it.next().isPrivileged()) {
4148                        return true;
4149                    }
4150                }
4151            } else if (obj instanceof PackageSetting) {
4152                final PackageSetting ps = (PackageSetting) obj;
4153                return ps.isPrivileged();
4154            }
4155        }
4156        return false;
4157    }
4158
4159    @Override
4160    public String[] getAppOpPermissionPackages(String permissionName) {
4161        synchronized (mPackages) {
4162            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4163            if (pkgs == null) {
4164                return null;
4165            }
4166            return pkgs.toArray(new String[pkgs.size()]);
4167        }
4168    }
4169
4170    @Override
4171    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4172            int flags, int userId) {
4173        if (!sUserManager.exists(userId)) return null;
4174        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4175        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4176        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4177    }
4178
4179    @Override
4180    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4181            IntentFilter filter, int match, ComponentName activity) {
4182        final int userId = UserHandle.getCallingUserId();
4183        if (DEBUG_PREFERRED) {
4184            Log.v(TAG, "setLastChosenActivity intent=" + intent
4185                + " resolvedType=" + resolvedType
4186                + " flags=" + flags
4187                + " filter=" + filter
4188                + " match=" + match
4189                + " activity=" + activity);
4190            filter.dump(new PrintStreamPrinter(System.out), "    ");
4191        }
4192        intent.setComponent(null);
4193        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4194        // Find any earlier preferred or last chosen entries and nuke them
4195        findPreferredActivity(intent, resolvedType,
4196                flags, query, 0, false, true, false, userId);
4197        // Add the new activity as the last chosen for this filter
4198        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4199                "Setting last chosen");
4200    }
4201
4202    @Override
4203    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4204        final int userId = UserHandle.getCallingUserId();
4205        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4206        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4207        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4208                false, false, false, userId);
4209    }
4210
4211    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4212            int flags, List<ResolveInfo> query, int userId) {
4213        if (query != null) {
4214            final int N = query.size();
4215            if (N == 1) {
4216                return query.get(0);
4217            } else if (N > 1) {
4218                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4219                // If there is more than one activity with the same priority,
4220                // then let the user decide between them.
4221                ResolveInfo r0 = query.get(0);
4222                ResolveInfo r1 = query.get(1);
4223                if (DEBUG_INTENT_MATCHING || debug) {
4224                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4225                            + r1.activityInfo.name + "=" + r1.priority);
4226                }
4227                // If the first activity has a higher priority, or a different
4228                // default, then it is always desireable to pick it.
4229                if (r0.priority != r1.priority
4230                        || r0.preferredOrder != r1.preferredOrder
4231                        || r0.isDefault != r1.isDefault) {
4232                    return query.get(0);
4233                }
4234                // If we have saved a preference for a preferred activity for
4235                // this Intent, use that.
4236                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4237                        flags, query, r0.priority, true, false, debug, userId);
4238                if (ri != null) {
4239                    return ri;
4240                }
4241                ri = new ResolveInfo(mResolveInfo);
4242                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4243                ri.activityInfo.applicationInfo = new ApplicationInfo(
4244                        ri.activityInfo.applicationInfo);
4245                if (userId != 0) {
4246                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4247                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4248                }
4249                // Make sure that the resolver is displayable in car mode
4250                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4251                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4252                return ri;
4253            }
4254        }
4255        return null;
4256    }
4257
4258    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4259            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4260        final int N = query.size();
4261        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4262                .get(userId);
4263        // Get the list of persistent preferred activities that handle the intent
4264        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4265        List<PersistentPreferredActivity> pprefs = ppir != null
4266                ? ppir.queryIntent(intent, resolvedType,
4267                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4268                : null;
4269        if (pprefs != null && pprefs.size() > 0) {
4270            final int M = pprefs.size();
4271            for (int i=0; i<M; i++) {
4272                final PersistentPreferredActivity ppa = pprefs.get(i);
4273                if (DEBUG_PREFERRED || debug) {
4274                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4275                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4276                            + "\n  component=" + ppa.mComponent);
4277                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4278                }
4279                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4280                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4281                if (DEBUG_PREFERRED || debug) {
4282                    Slog.v(TAG, "Found persistent preferred activity:");
4283                    if (ai != null) {
4284                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4285                    } else {
4286                        Slog.v(TAG, "  null");
4287                    }
4288                }
4289                if (ai == null) {
4290                    // This previously registered persistent preferred activity
4291                    // component is no longer known. Ignore it and do NOT remove it.
4292                    continue;
4293                }
4294                for (int j=0; j<N; j++) {
4295                    final ResolveInfo ri = query.get(j);
4296                    if (!ri.activityInfo.applicationInfo.packageName
4297                            .equals(ai.applicationInfo.packageName)) {
4298                        continue;
4299                    }
4300                    if (!ri.activityInfo.name.equals(ai.name)) {
4301                        continue;
4302                    }
4303                    //  Found a persistent preference that can handle the intent.
4304                    if (DEBUG_PREFERRED || debug) {
4305                        Slog.v(TAG, "Returning persistent preferred activity: " +
4306                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4307                    }
4308                    return ri;
4309                }
4310            }
4311        }
4312        return null;
4313    }
4314
4315    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4316            List<ResolveInfo> query, int priority, boolean always,
4317            boolean removeMatches, boolean debug, int userId) {
4318        if (!sUserManager.exists(userId)) return null;
4319        // writer
4320        synchronized (mPackages) {
4321            if (intent.getSelector() != null) {
4322                intent = intent.getSelector();
4323            }
4324            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4325
4326            // Try to find a matching persistent preferred activity.
4327            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4328                    debug, userId);
4329
4330            // If a persistent preferred activity matched, use it.
4331            if (pri != null) {
4332                return pri;
4333            }
4334
4335            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4336            // Get the list of preferred activities that handle the intent
4337            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4338            List<PreferredActivity> prefs = pir != null
4339                    ? pir.queryIntent(intent, resolvedType,
4340                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4341                    : null;
4342            if (prefs != null && prefs.size() > 0) {
4343                boolean changed = false;
4344                try {
4345                    // First figure out how good the original match set is.
4346                    // We will only allow preferred activities that came
4347                    // from the same match quality.
4348                    int match = 0;
4349
4350                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4351
4352                    final int N = query.size();
4353                    for (int j=0; j<N; j++) {
4354                        final ResolveInfo ri = query.get(j);
4355                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4356                                + ": 0x" + Integer.toHexString(match));
4357                        if (ri.match > match) {
4358                            match = ri.match;
4359                        }
4360                    }
4361
4362                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4363                            + Integer.toHexString(match));
4364
4365                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4366                    final int M = prefs.size();
4367                    for (int i=0; i<M; i++) {
4368                        final PreferredActivity pa = prefs.get(i);
4369                        if (DEBUG_PREFERRED || debug) {
4370                            Slog.v(TAG, "Checking PreferredActivity ds="
4371                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4372                                    + "\n  component=" + pa.mPref.mComponent);
4373                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4374                        }
4375                        if (pa.mPref.mMatch != match) {
4376                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4377                                    + Integer.toHexString(pa.mPref.mMatch));
4378                            continue;
4379                        }
4380                        // If it's not an "always" type preferred activity and that's what we're
4381                        // looking for, skip it.
4382                        if (always && !pa.mPref.mAlways) {
4383                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4384                            continue;
4385                        }
4386                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4387                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4388                        if (DEBUG_PREFERRED || debug) {
4389                            Slog.v(TAG, "Found preferred activity:");
4390                            if (ai != null) {
4391                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4392                            } else {
4393                                Slog.v(TAG, "  null");
4394                            }
4395                        }
4396                        if (ai == null) {
4397                            // This previously registered preferred activity
4398                            // component is no longer known.  Most likely an update
4399                            // to the app was installed and in the new version this
4400                            // component no longer exists.  Clean it up by removing
4401                            // it from the preferred activities list, and skip it.
4402                            Slog.w(TAG, "Removing dangling preferred activity: "
4403                                    + pa.mPref.mComponent);
4404                            pir.removeFilter(pa);
4405                            changed = true;
4406                            continue;
4407                        }
4408                        for (int j=0; j<N; j++) {
4409                            final ResolveInfo ri = query.get(j);
4410                            if (!ri.activityInfo.applicationInfo.packageName
4411                                    .equals(ai.applicationInfo.packageName)) {
4412                                continue;
4413                            }
4414                            if (!ri.activityInfo.name.equals(ai.name)) {
4415                                continue;
4416                            }
4417
4418                            if (removeMatches) {
4419                                pir.removeFilter(pa);
4420                                changed = true;
4421                                if (DEBUG_PREFERRED) {
4422                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4423                                }
4424                                break;
4425                            }
4426
4427                            // Okay we found a previously set preferred or last chosen app.
4428                            // If the result set is different from when this
4429                            // was created, we need to clear it and re-ask the
4430                            // user their preference, if we're looking for an "always" type entry.
4431                            if (always && !pa.mPref.sameSet(query)) {
4432                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4433                                        + intent + " type " + resolvedType);
4434                                if (DEBUG_PREFERRED) {
4435                                    Slog.v(TAG, "Removing preferred activity since set changed "
4436                                            + pa.mPref.mComponent);
4437                                }
4438                                pir.removeFilter(pa);
4439                                // Re-add the filter as a "last chosen" entry (!always)
4440                                PreferredActivity lastChosen = new PreferredActivity(
4441                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4442                                pir.addFilter(lastChosen);
4443                                changed = true;
4444                                return null;
4445                            }
4446
4447                            // Yay! Either the set matched or we're looking for the last chosen
4448                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4449                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4450                            return ri;
4451                        }
4452                    }
4453                } finally {
4454                    if (changed) {
4455                        if (DEBUG_PREFERRED) {
4456                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4457                        }
4458                        scheduleWritePackageRestrictionsLocked(userId);
4459                    }
4460                }
4461            }
4462        }
4463        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4464        return null;
4465    }
4466
4467    /*
4468     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4469     */
4470    @Override
4471    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4472            int targetUserId) {
4473        mContext.enforceCallingOrSelfPermission(
4474                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4475        List<CrossProfileIntentFilter> matches =
4476                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4477        if (matches != null) {
4478            int size = matches.size();
4479            for (int i = 0; i < size; i++) {
4480                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4481            }
4482        }
4483        if (hasWebURI(intent)) {
4484            // cross-profile app linking works only towards the parent.
4485            final UserInfo parent = getProfileParent(sourceUserId);
4486            synchronized(mPackages) {
4487                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4488                        intent, resolvedType, 0, sourceUserId, parent.id);
4489                return xpDomainInfo != null;
4490            }
4491        }
4492        return false;
4493    }
4494
4495    private UserInfo getProfileParent(int userId) {
4496        final long identity = Binder.clearCallingIdentity();
4497        try {
4498            return sUserManager.getProfileParent(userId);
4499        } finally {
4500            Binder.restoreCallingIdentity(identity);
4501        }
4502    }
4503
4504    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4505            String resolvedType, int userId) {
4506        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4507        if (resolver != null) {
4508            return resolver.queryIntent(intent, resolvedType, false, userId);
4509        }
4510        return null;
4511    }
4512
4513    @Override
4514    public List<ResolveInfo> queryIntentActivities(Intent intent,
4515            String resolvedType, int flags, int userId) {
4516        if (!sUserManager.exists(userId)) return Collections.emptyList();
4517        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4518        ComponentName comp = intent.getComponent();
4519        if (comp == null) {
4520            if (intent.getSelector() != null) {
4521                intent = intent.getSelector();
4522                comp = intent.getComponent();
4523            }
4524        }
4525
4526        if (comp != null) {
4527            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4528            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4529            if (ai != null) {
4530                final ResolveInfo ri = new ResolveInfo();
4531                ri.activityInfo = ai;
4532                list.add(ri);
4533            }
4534            return list;
4535        }
4536
4537        // reader
4538        synchronized (mPackages) {
4539            final String pkgName = intent.getPackage();
4540            if (pkgName == null) {
4541                List<CrossProfileIntentFilter> matchingFilters =
4542                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4543                // Check for results that need to skip the current profile.
4544                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4545                        resolvedType, flags, userId);
4546                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4547                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4548                    result.add(xpResolveInfo);
4549                    return filterIfNotPrimaryUser(result, userId);
4550                }
4551
4552                // Check for results in the current profile.
4553                List<ResolveInfo> result = mActivities.queryIntent(
4554                        intent, resolvedType, flags, userId);
4555
4556                // Check for cross profile results.
4557                xpResolveInfo = queryCrossProfileIntents(
4558                        matchingFilters, intent, resolvedType, flags, userId);
4559                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4560                    result.add(xpResolveInfo);
4561                    Collections.sort(result, mResolvePrioritySorter);
4562                }
4563                result = filterIfNotPrimaryUser(result, userId);
4564                if (hasWebURI(intent)) {
4565                    CrossProfileDomainInfo xpDomainInfo = null;
4566                    final UserInfo parent = getProfileParent(userId);
4567                    if (parent != null) {
4568                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4569                                flags, userId, parent.id);
4570                    }
4571                    if (xpDomainInfo != null) {
4572                        if (xpResolveInfo != null) {
4573                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4574                            // in the result.
4575                            result.remove(xpResolveInfo);
4576                        }
4577                        if (result.size() == 0) {
4578                            result.add(xpDomainInfo.resolveInfo);
4579                            return result;
4580                        }
4581                    } else if (result.size() <= 1) {
4582                        return result;
4583                    }
4584                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4585                            xpDomainInfo, userId);
4586                    Collections.sort(result, mResolvePrioritySorter);
4587                }
4588                return result;
4589            }
4590            final PackageParser.Package pkg = mPackages.get(pkgName);
4591            if (pkg != null) {
4592                return filterIfNotPrimaryUser(
4593                        mActivities.queryIntentForPackage(
4594                                intent, resolvedType, flags, pkg.activities, userId),
4595                        userId);
4596            }
4597            return new ArrayList<ResolveInfo>();
4598        }
4599    }
4600
4601    private static class CrossProfileDomainInfo {
4602        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4603        ResolveInfo resolveInfo;
4604        /* Best domain verification status of the activities found in the other profile */
4605        int bestDomainVerificationStatus;
4606    }
4607
4608    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4609            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4610        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4611                sourceUserId)) {
4612            return null;
4613        }
4614        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4615                resolvedType, flags, parentUserId);
4616
4617        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4618            return null;
4619        }
4620        CrossProfileDomainInfo result = null;
4621        int size = resultTargetUser.size();
4622        for (int i = 0; i < size; i++) {
4623            ResolveInfo riTargetUser = resultTargetUser.get(i);
4624            // Intent filter verification is only for filters that specify a host. So don't return
4625            // those that handle all web uris.
4626            if (riTargetUser.handleAllWebDataURI) {
4627                continue;
4628            }
4629            String packageName = riTargetUser.activityInfo.packageName;
4630            PackageSetting ps = mSettings.mPackages.get(packageName);
4631            if (ps == null) {
4632                continue;
4633            }
4634            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4635            int status = (int)(verificationState >> 32);
4636            if (result == null) {
4637                result = new CrossProfileDomainInfo();
4638                result.resolveInfo =
4639                        createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId);
4640                result.bestDomainVerificationStatus = status;
4641            } else {
4642                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4643                        result.bestDomainVerificationStatus);
4644            }
4645        }
4646        // Don't consider matches with status NEVER across profiles.
4647        if (result != null && result.bestDomainVerificationStatus
4648                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4649            return null;
4650        }
4651        return result;
4652    }
4653
4654    /**
4655     * Verification statuses are ordered from the worse to the best, except for
4656     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4657     */
4658    private int bestDomainVerificationStatus(int status1, int status2) {
4659        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4660            return status2;
4661        }
4662        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4663            return status1;
4664        }
4665        return (int) MathUtils.max(status1, status2);
4666    }
4667
4668    private boolean isUserEnabled(int userId) {
4669        long callingId = Binder.clearCallingIdentity();
4670        try {
4671            UserInfo userInfo = sUserManager.getUserInfo(userId);
4672            return userInfo != null && userInfo.isEnabled();
4673        } finally {
4674            Binder.restoreCallingIdentity(callingId);
4675        }
4676    }
4677
4678    /**
4679     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4680     *
4681     * @return filtered list
4682     */
4683    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4684        if (userId == UserHandle.USER_OWNER) {
4685            return resolveInfos;
4686        }
4687        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4688            ResolveInfo info = resolveInfos.get(i);
4689            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4690                resolveInfos.remove(i);
4691            }
4692        }
4693        return resolveInfos;
4694    }
4695
4696    private static boolean hasWebURI(Intent intent) {
4697        if (intent.getData() == null) {
4698            return false;
4699        }
4700        final String scheme = intent.getScheme();
4701        if (TextUtils.isEmpty(scheme)) {
4702            return false;
4703        }
4704        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4705    }
4706
4707    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4708            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4709            int userId) {
4710        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4711
4712        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4713            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4714                    candidates.size());
4715        }
4716
4717        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4718        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4719        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4720        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4721        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4722        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4723
4724        synchronized (mPackages) {
4725            final int count = candidates.size();
4726            // First, try to use linked apps. Partition the candidates into four lists:
4727            // one for the final results, one for the "do not use ever", one for "undefined status"
4728            // and finally one for "browser app type".
4729            for (int n=0; n<count; n++) {
4730                ResolveInfo info = candidates.get(n);
4731                String packageName = info.activityInfo.packageName;
4732                PackageSetting ps = mSettings.mPackages.get(packageName);
4733                if (ps != null) {
4734                    // Add to the special match all list (Browser use case)
4735                    if (info.handleAllWebDataURI) {
4736                        matchAllList.add(info);
4737                        continue;
4738                    }
4739                    // Try to get the status from User settings first
4740                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4741                    int status = (int)(packedStatus >> 32);
4742                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4743                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4744                        if (DEBUG_DOMAIN_VERIFICATION) {
4745                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4746                                    + " : linkgen=" + linkGeneration);
4747                        }
4748                        // Use link-enabled generation as preferredOrder, i.e.
4749                        // prefer newly-enabled over earlier-enabled.
4750                        info.preferredOrder = linkGeneration;
4751                        alwaysList.add(info);
4752                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4753                        if (DEBUG_DOMAIN_VERIFICATION) {
4754                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4755                        }
4756                        neverList.add(info);
4757                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4758                        if (DEBUG_DOMAIN_VERIFICATION) {
4759                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4760                        }
4761                        alwaysAskList.add(info);
4762                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4763                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4764                        if (DEBUG_DOMAIN_VERIFICATION) {
4765                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4766                        }
4767                        undefinedList.add(info);
4768                    }
4769                }
4770            }
4771
4772            // We'll want to include browser possibilities in a few cases
4773            boolean includeBrowser = false;
4774
4775            // First try to add the "always" resolution(s) for the current user, if any
4776            if (alwaysList.size() > 0) {
4777                result.addAll(alwaysList);
4778            // if there is an "always" for the parent user, add it.
4779            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4780                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4781                result.add(xpDomainInfo.resolveInfo);
4782            } else {
4783                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4784                result.addAll(undefinedList);
4785                if (xpDomainInfo != null && (
4786                        xpDomainInfo.bestDomainVerificationStatus
4787                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4788                        || xpDomainInfo.bestDomainVerificationStatus
4789                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4790                    result.add(xpDomainInfo.resolveInfo);
4791                }
4792                includeBrowser = true;
4793            }
4794
4795            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4796            // If there were 'always' entries their preferred order has been set, so we also
4797            // back that off to make the alternatives equivalent
4798            if (alwaysAskList.size() > 0) {
4799                for (ResolveInfo i : result) {
4800                    i.preferredOrder = 0;
4801                }
4802                result.addAll(alwaysAskList);
4803                includeBrowser = true;
4804            }
4805
4806            if (includeBrowser) {
4807                // Also add browsers (all of them or only the default one)
4808                if (DEBUG_DOMAIN_VERIFICATION) {
4809                    Slog.v(TAG, "   ...including browsers in candidate set");
4810                }
4811                if ((matchFlags & MATCH_ALL) != 0) {
4812                    result.addAll(matchAllList);
4813                } else {
4814                    // Browser/generic handling case.  If there's a default browser, go straight
4815                    // to that (but only if there is no other higher-priority match).
4816                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4817                    int maxMatchPrio = 0;
4818                    ResolveInfo defaultBrowserMatch = null;
4819                    final int numCandidates = matchAllList.size();
4820                    for (int n = 0; n < numCandidates; n++) {
4821                        ResolveInfo info = matchAllList.get(n);
4822                        // track the highest overall match priority...
4823                        if (info.priority > maxMatchPrio) {
4824                            maxMatchPrio = info.priority;
4825                        }
4826                        // ...and the highest-priority default browser match
4827                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4828                            if (defaultBrowserMatch == null
4829                                    || (defaultBrowserMatch.priority < info.priority)) {
4830                                if (debug) {
4831                                    Slog.v(TAG, "Considering default browser match " + info);
4832                                }
4833                                defaultBrowserMatch = info;
4834                            }
4835                        }
4836                    }
4837                    if (defaultBrowserMatch != null
4838                            && defaultBrowserMatch.priority >= maxMatchPrio
4839                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4840                    {
4841                        if (debug) {
4842                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4843                        }
4844                        result.add(defaultBrowserMatch);
4845                    } else {
4846                        result.addAll(matchAllList);
4847                    }
4848                }
4849
4850                // If there is nothing selected, add all candidates and remove the ones that the user
4851                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4852                if (result.size() == 0) {
4853                    result.addAll(candidates);
4854                    result.removeAll(neverList);
4855                }
4856            }
4857        }
4858        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4859            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4860                    result.size());
4861            for (ResolveInfo info : result) {
4862                Slog.v(TAG, "  + " + info.activityInfo);
4863            }
4864        }
4865        return result;
4866    }
4867
4868    // Returns a packed value as a long:
4869    //
4870    // high 'int'-sized word: link status: undefined/ask/never/always.
4871    // low 'int'-sized word: relative priority among 'always' results.
4872    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4873        long result = ps.getDomainVerificationStatusForUser(userId);
4874        // if none available, get the master status
4875        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4876            if (ps.getIntentFilterVerificationInfo() != null) {
4877                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4878            }
4879        }
4880        return result;
4881    }
4882
4883    private ResolveInfo querySkipCurrentProfileIntents(
4884            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4885            int flags, int sourceUserId) {
4886        if (matchingFilters != null) {
4887            int size = matchingFilters.size();
4888            for (int i = 0; i < size; i ++) {
4889                CrossProfileIntentFilter filter = matchingFilters.get(i);
4890                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4891                    // Checking if there are activities in the target user that can handle the
4892                    // intent.
4893                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4894                            flags, sourceUserId);
4895                    if (resolveInfo != null) {
4896                        return resolveInfo;
4897                    }
4898                }
4899            }
4900        }
4901        return null;
4902    }
4903
4904    // Return matching ResolveInfo if any for skip current profile intent filters.
4905    private ResolveInfo queryCrossProfileIntents(
4906            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4907            int flags, int sourceUserId) {
4908        if (matchingFilters != null) {
4909            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4910            // match the same intent. For performance reasons, it is better not to
4911            // run queryIntent twice for the same userId
4912            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4913            int size = matchingFilters.size();
4914            for (int i = 0; i < size; i++) {
4915                CrossProfileIntentFilter filter = matchingFilters.get(i);
4916                int targetUserId = filter.getTargetUserId();
4917                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4918                        && !alreadyTriedUserIds.get(targetUserId)) {
4919                    // Checking if there are activities in the target user that can handle the
4920                    // intent.
4921                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4922                            flags, sourceUserId);
4923                    if (resolveInfo != null) return resolveInfo;
4924                    alreadyTriedUserIds.put(targetUserId, true);
4925                }
4926            }
4927        }
4928        return null;
4929    }
4930
4931    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4932            String resolvedType, int flags, int sourceUserId) {
4933        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4934                resolvedType, flags, filter.getTargetUserId());
4935        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4936            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4937        }
4938        return null;
4939    }
4940
4941    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4942            int sourceUserId, int targetUserId) {
4943        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4944        String className;
4945        if (targetUserId == UserHandle.USER_OWNER) {
4946            className = FORWARD_INTENT_TO_USER_OWNER;
4947        } else {
4948            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4949        }
4950        ComponentName forwardingActivityComponentName = new ComponentName(
4951                mAndroidApplication.packageName, className);
4952        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4953                sourceUserId);
4954        if (targetUserId == UserHandle.USER_OWNER) {
4955            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4956            forwardingResolveInfo.noResourceId = true;
4957        }
4958        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4959        forwardingResolveInfo.priority = 0;
4960        forwardingResolveInfo.preferredOrder = 0;
4961        forwardingResolveInfo.match = 0;
4962        forwardingResolveInfo.isDefault = true;
4963        forwardingResolveInfo.filter = filter;
4964        forwardingResolveInfo.targetUserId = targetUserId;
4965        return forwardingResolveInfo;
4966    }
4967
4968    @Override
4969    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4970            Intent[] specifics, String[] specificTypes, Intent intent,
4971            String resolvedType, int flags, int userId) {
4972        if (!sUserManager.exists(userId)) return Collections.emptyList();
4973        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4974                false, "query intent activity options");
4975        final String resultsAction = intent.getAction();
4976
4977        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4978                | PackageManager.GET_RESOLVED_FILTER, userId);
4979
4980        if (DEBUG_INTENT_MATCHING) {
4981            Log.v(TAG, "Query " + intent + ": " + results);
4982        }
4983
4984        int specificsPos = 0;
4985        int N;
4986
4987        // todo: note that the algorithm used here is O(N^2).  This
4988        // isn't a problem in our current environment, but if we start running
4989        // into situations where we have more than 5 or 10 matches then this
4990        // should probably be changed to something smarter...
4991
4992        // First we go through and resolve each of the specific items
4993        // that were supplied, taking care of removing any corresponding
4994        // duplicate items in the generic resolve list.
4995        if (specifics != null) {
4996            for (int i=0; i<specifics.length; i++) {
4997                final Intent sintent = specifics[i];
4998                if (sintent == null) {
4999                    continue;
5000                }
5001
5002                if (DEBUG_INTENT_MATCHING) {
5003                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5004                }
5005
5006                String action = sintent.getAction();
5007                if (resultsAction != null && resultsAction.equals(action)) {
5008                    // If this action was explicitly requested, then don't
5009                    // remove things that have it.
5010                    action = null;
5011                }
5012
5013                ResolveInfo ri = null;
5014                ActivityInfo ai = null;
5015
5016                ComponentName comp = sintent.getComponent();
5017                if (comp == null) {
5018                    ri = resolveIntent(
5019                        sintent,
5020                        specificTypes != null ? specificTypes[i] : null,
5021                            flags, userId);
5022                    if (ri == null) {
5023                        continue;
5024                    }
5025                    if (ri == mResolveInfo) {
5026                        // ACK!  Must do something better with this.
5027                    }
5028                    ai = ri.activityInfo;
5029                    comp = new ComponentName(ai.applicationInfo.packageName,
5030                            ai.name);
5031                } else {
5032                    ai = getActivityInfo(comp, flags, userId);
5033                    if (ai == null) {
5034                        continue;
5035                    }
5036                }
5037
5038                // Look for any generic query activities that are duplicates
5039                // of this specific one, and remove them from the results.
5040                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5041                N = results.size();
5042                int j;
5043                for (j=specificsPos; j<N; j++) {
5044                    ResolveInfo sri = results.get(j);
5045                    if ((sri.activityInfo.name.equals(comp.getClassName())
5046                            && sri.activityInfo.applicationInfo.packageName.equals(
5047                                    comp.getPackageName()))
5048                        || (action != null && sri.filter.matchAction(action))) {
5049                        results.remove(j);
5050                        if (DEBUG_INTENT_MATCHING) Log.v(
5051                            TAG, "Removing duplicate item from " + j
5052                            + " due to specific " + specificsPos);
5053                        if (ri == null) {
5054                            ri = sri;
5055                        }
5056                        j--;
5057                        N--;
5058                    }
5059                }
5060
5061                // Add this specific item to its proper place.
5062                if (ri == null) {
5063                    ri = new ResolveInfo();
5064                    ri.activityInfo = ai;
5065                }
5066                results.add(specificsPos, ri);
5067                ri.specificIndex = i;
5068                specificsPos++;
5069            }
5070        }
5071
5072        // Now we go through the remaining generic results and remove any
5073        // duplicate actions that are found here.
5074        N = results.size();
5075        for (int i=specificsPos; i<N-1; i++) {
5076            final ResolveInfo rii = results.get(i);
5077            if (rii.filter == null) {
5078                continue;
5079            }
5080
5081            // Iterate over all of the actions of this result's intent
5082            // filter...  typically this should be just one.
5083            final Iterator<String> it = rii.filter.actionsIterator();
5084            if (it == null) {
5085                continue;
5086            }
5087            while (it.hasNext()) {
5088                final String action = it.next();
5089                if (resultsAction != null && resultsAction.equals(action)) {
5090                    // If this action was explicitly requested, then don't
5091                    // remove things that have it.
5092                    continue;
5093                }
5094                for (int j=i+1; j<N; j++) {
5095                    final ResolveInfo rij = results.get(j);
5096                    if (rij.filter != null && rij.filter.hasAction(action)) {
5097                        results.remove(j);
5098                        if (DEBUG_INTENT_MATCHING) Log.v(
5099                            TAG, "Removing duplicate item from " + j
5100                            + " due to action " + action + " at " + i);
5101                        j--;
5102                        N--;
5103                    }
5104                }
5105            }
5106
5107            // If the caller didn't request filter information, drop it now
5108            // so we don't have to marshall/unmarshall it.
5109            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5110                rii.filter = null;
5111            }
5112        }
5113
5114        // Filter out the caller activity if so requested.
5115        if (caller != null) {
5116            N = results.size();
5117            for (int i=0; i<N; i++) {
5118                ActivityInfo ainfo = results.get(i).activityInfo;
5119                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5120                        && caller.getClassName().equals(ainfo.name)) {
5121                    results.remove(i);
5122                    break;
5123                }
5124            }
5125        }
5126
5127        // If the caller didn't request filter information,
5128        // drop them now so we don't have to
5129        // marshall/unmarshall it.
5130        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5131            N = results.size();
5132            for (int i=0; i<N; i++) {
5133                results.get(i).filter = null;
5134            }
5135        }
5136
5137        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5138        return results;
5139    }
5140
5141    @Override
5142    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5143            int userId) {
5144        if (!sUserManager.exists(userId)) return Collections.emptyList();
5145        ComponentName comp = intent.getComponent();
5146        if (comp == null) {
5147            if (intent.getSelector() != null) {
5148                intent = intent.getSelector();
5149                comp = intent.getComponent();
5150            }
5151        }
5152        if (comp != null) {
5153            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5154            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5155            if (ai != null) {
5156                ResolveInfo ri = new ResolveInfo();
5157                ri.activityInfo = ai;
5158                list.add(ri);
5159            }
5160            return list;
5161        }
5162
5163        // reader
5164        synchronized (mPackages) {
5165            String pkgName = intent.getPackage();
5166            if (pkgName == null) {
5167                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5168            }
5169            final PackageParser.Package pkg = mPackages.get(pkgName);
5170            if (pkg != null) {
5171                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5172                        userId);
5173            }
5174            return null;
5175        }
5176    }
5177
5178    @Override
5179    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5180        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5181        if (!sUserManager.exists(userId)) return null;
5182        if (query != null) {
5183            if (query.size() >= 1) {
5184                // If there is more than one service with the same priority,
5185                // just arbitrarily pick the first one.
5186                return query.get(0);
5187            }
5188        }
5189        return null;
5190    }
5191
5192    @Override
5193    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5194            int userId) {
5195        if (!sUserManager.exists(userId)) return Collections.emptyList();
5196        ComponentName comp = intent.getComponent();
5197        if (comp == null) {
5198            if (intent.getSelector() != null) {
5199                intent = intent.getSelector();
5200                comp = intent.getComponent();
5201            }
5202        }
5203        if (comp != null) {
5204            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5205            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5206            if (si != null) {
5207                final ResolveInfo ri = new ResolveInfo();
5208                ri.serviceInfo = si;
5209                list.add(ri);
5210            }
5211            return list;
5212        }
5213
5214        // reader
5215        synchronized (mPackages) {
5216            String pkgName = intent.getPackage();
5217            if (pkgName == null) {
5218                return mServices.queryIntent(intent, resolvedType, flags, userId);
5219            }
5220            final PackageParser.Package pkg = mPackages.get(pkgName);
5221            if (pkg != null) {
5222                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5223                        userId);
5224            }
5225            return null;
5226        }
5227    }
5228
5229    @Override
5230    public List<ResolveInfo> queryIntentContentProviders(
5231            Intent intent, String resolvedType, int flags, int userId) {
5232        if (!sUserManager.exists(userId)) return Collections.emptyList();
5233        ComponentName comp = intent.getComponent();
5234        if (comp == null) {
5235            if (intent.getSelector() != null) {
5236                intent = intent.getSelector();
5237                comp = intent.getComponent();
5238            }
5239        }
5240        if (comp != null) {
5241            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5242            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5243            if (pi != null) {
5244                final ResolveInfo ri = new ResolveInfo();
5245                ri.providerInfo = pi;
5246                list.add(ri);
5247            }
5248            return list;
5249        }
5250
5251        // reader
5252        synchronized (mPackages) {
5253            String pkgName = intent.getPackage();
5254            if (pkgName == null) {
5255                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5256            }
5257            final PackageParser.Package pkg = mPackages.get(pkgName);
5258            if (pkg != null) {
5259                return mProviders.queryIntentForPackage(
5260                        intent, resolvedType, flags, pkg.providers, userId);
5261            }
5262            return null;
5263        }
5264    }
5265
5266    @Override
5267    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5268        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5269
5270        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5271
5272        // writer
5273        synchronized (mPackages) {
5274            ArrayList<PackageInfo> list;
5275            if (listUninstalled) {
5276                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5277                for (PackageSetting ps : mSettings.mPackages.values()) {
5278                    PackageInfo pi;
5279                    if (ps.pkg != null) {
5280                        pi = generatePackageInfo(ps.pkg, flags, userId);
5281                    } else {
5282                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5283                    }
5284                    if (pi != null) {
5285                        list.add(pi);
5286                    }
5287                }
5288            } else {
5289                list = new ArrayList<PackageInfo>(mPackages.size());
5290                for (PackageParser.Package p : mPackages.values()) {
5291                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5292                    if (pi != null) {
5293                        list.add(pi);
5294                    }
5295                }
5296            }
5297
5298            return new ParceledListSlice<PackageInfo>(list);
5299        }
5300    }
5301
5302    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5303            String[] permissions, boolean[] tmp, int flags, int userId) {
5304        int numMatch = 0;
5305        final PermissionsState permissionsState = ps.getPermissionsState();
5306        for (int i=0; i<permissions.length; i++) {
5307            final String permission = permissions[i];
5308            if (permissionsState.hasPermission(permission, userId)) {
5309                tmp[i] = true;
5310                numMatch++;
5311            } else {
5312                tmp[i] = false;
5313            }
5314        }
5315        if (numMatch == 0) {
5316            return;
5317        }
5318        PackageInfo pi;
5319        if (ps.pkg != null) {
5320            pi = generatePackageInfo(ps.pkg, flags, userId);
5321        } else {
5322            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5323        }
5324        // The above might return null in cases of uninstalled apps or install-state
5325        // skew across users/profiles.
5326        if (pi != null) {
5327            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5328                if (numMatch == permissions.length) {
5329                    pi.requestedPermissions = permissions;
5330                } else {
5331                    pi.requestedPermissions = new String[numMatch];
5332                    numMatch = 0;
5333                    for (int i=0; i<permissions.length; i++) {
5334                        if (tmp[i]) {
5335                            pi.requestedPermissions[numMatch] = permissions[i];
5336                            numMatch++;
5337                        }
5338                    }
5339                }
5340            }
5341            list.add(pi);
5342        }
5343    }
5344
5345    @Override
5346    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5347            String[] permissions, int flags, int userId) {
5348        if (!sUserManager.exists(userId)) return null;
5349        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5350
5351        // writer
5352        synchronized (mPackages) {
5353            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5354            boolean[] tmpBools = new boolean[permissions.length];
5355            if (listUninstalled) {
5356                for (PackageSetting ps : mSettings.mPackages.values()) {
5357                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5358                }
5359            } else {
5360                for (PackageParser.Package pkg : mPackages.values()) {
5361                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5362                    if (ps != null) {
5363                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5364                                userId);
5365                    }
5366                }
5367            }
5368
5369            return new ParceledListSlice<PackageInfo>(list);
5370        }
5371    }
5372
5373    @Override
5374    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5375        if (!sUserManager.exists(userId)) return null;
5376        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5377
5378        // writer
5379        synchronized (mPackages) {
5380            ArrayList<ApplicationInfo> list;
5381            if (listUninstalled) {
5382                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5383                for (PackageSetting ps : mSettings.mPackages.values()) {
5384                    ApplicationInfo ai;
5385                    if (ps.pkg != null) {
5386                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5387                                ps.readUserState(userId), userId);
5388                    } else {
5389                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5390                    }
5391                    if (ai != null) {
5392                        list.add(ai);
5393                    }
5394                }
5395            } else {
5396                list = new ArrayList<ApplicationInfo>(mPackages.size());
5397                for (PackageParser.Package p : mPackages.values()) {
5398                    if (p.mExtras != null) {
5399                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5400                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5401                        if (ai != null) {
5402                            list.add(ai);
5403                        }
5404                    }
5405                }
5406            }
5407
5408            return new ParceledListSlice<ApplicationInfo>(list);
5409        }
5410    }
5411
5412    public List<ApplicationInfo> getPersistentApplications(int flags) {
5413        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5414
5415        // reader
5416        synchronized (mPackages) {
5417            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5418            final int userId = UserHandle.getCallingUserId();
5419            while (i.hasNext()) {
5420                final PackageParser.Package p = i.next();
5421                if (p.applicationInfo != null
5422                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5423                        && (!mSafeMode || isSystemApp(p))) {
5424                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5425                    if (ps != null) {
5426                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5427                                ps.readUserState(userId), userId);
5428                        if (ai != null) {
5429                            finalList.add(ai);
5430                        }
5431                    }
5432                }
5433            }
5434        }
5435
5436        return finalList;
5437    }
5438
5439    @Override
5440    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5441        if (!sUserManager.exists(userId)) return null;
5442        // reader
5443        synchronized (mPackages) {
5444            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5445            PackageSetting ps = provider != null
5446                    ? mSettings.mPackages.get(provider.owner.packageName)
5447                    : null;
5448            return ps != null
5449                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5450                    && (!mSafeMode || (provider.info.applicationInfo.flags
5451                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5452                    ? PackageParser.generateProviderInfo(provider, flags,
5453                            ps.readUserState(userId), userId)
5454                    : null;
5455        }
5456    }
5457
5458    /**
5459     * @deprecated
5460     */
5461    @Deprecated
5462    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5463        // reader
5464        synchronized (mPackages) {
5465            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5466                    .entrySet().iterator();
5467            final int userId = UserHandle.getCallingUserId();
5468            while (i.hasNext()) {
5469                Map.Entry<String, PackageParser.Provider> entry = i.next();
5470                PackageParser.Provider p = entry.getValue();
5471                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5472
5473                if (ps != null && p.syncable
5474                        && (!mSafeMode || (p.info.applicationInfo.flags
5475                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5476                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5477                            ps.readUserState(userId), userId);
5478                    if (info != null) {
5479                        outNames.add(entry.getKey());
5480                        outInfo.add(info);
5481                    }
5482                }
5483            }
5484        }
5485    }
5486
5487    @Override
5488    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5489            int uid, int flags) {
5490        ArrayList<ProviderInfo> finalList = null;
5491        // reader
5492        synchronized (mPackages) {
5493            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5494            final int userId = processName != null ?
5495                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5496            while (i.hasNext()) {
5497                final PackageParser.Provider p = i.next();
5498                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5499                if (ps != null && p.info.authority != null
5500                        && (processName == null
5501                                || (p.info.processName.equals(processName)
5502                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5503                        && mSettings.isEnabledLPr(p.info, flags, userId)
5504                        && (!mSafeMode
5505                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5506                    if (finalList == null) {
5507                        finalList = new ArrayList<ProviderInfo>(3);
5508                    }
5509                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5510                            ps.readUserState(userId), userId);
5511                    if (info != null) {
5512                        finalList.add(info);
5513                    }
5514                }
5515            }
5516        }
5517
5518        if (finalList != null) {
5519            Collections.sort(finalList, mProviderInitOrderSorter);
5520            return new ParceledListSlice<ProviderInfo>(finalList);
5521        }
5522
5523        return null;
5524    }
5525
5526    @Override
5527    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5528            int flags) {
5529        // reader
5530        synchronized (mPackages) {
5531            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5532            return PackageParser.generateInstrumentationInfo(i, flags);
5533        }
5534    }
5535
5536    @Override
5537    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5538            int flags) {
5539        ArrayList<InstrumentationInfo> finalList =
5540            new ArrayList<InstrumentationInfo>();
5541
5542        // reader
5543        synchronized (mPackages) {
5544            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5545            while (i.hasNext()) {
5546                final PackageParser.Instrumentation p = i.next();
5547                if (targetPackage == null
5548                        || targetPackage.equals(p.info.targetPackage)) {
5549                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5550                            flags);
5551                    if (ii != null) {
5552                        finalList.add(ii);
5553                    }
5554                }
5555            }
5556        }
5557
5558        return finalList;
5559    }
5560
5561    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5562        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5563        if (overlays == null) {
5564            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5565            return;
5566        }
5567        for (PackageParser.Package opkg : overlays.values()) {
5568            // Not much to do if idmap fails: we already logged the error
5569            // and we certainly don't want to abort installation of pkg simply
5570            // because an overlay didn't fit properly. For these reasons,
5571            // ignore the return value of createIdmapForPackagePairLI.
5572            createIdmapForPackagePairLI(pkg, opkg);
5573        }
5574    }
5575
5576    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5577            PackageParser.Package opkg) {
5578        if (!opkg.mTrustedOverlay) {
5579            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5580                    opkg.baseCodePath + ": overlay not trusted");
5581            return false;
5582        }
5583        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5584        if (overlaySet == null) {
5585            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5586                    opkg.baseCodePath + " but target package has no known overlays");
5587            return false;
5588        }
5589        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5590        // TODO: generate idmap for split APKs
5591        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5592            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5593                    + opkg.baseCodePath);
5594            return false;
5595        }
5596        PackageParser.Package[] overlayArray =
5597            overlaySet.values().toArray(new PackageParser.Package[0]);
5598        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5599            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5600                return p1.mOverlayPriority - p2.mOverlayPriority;
5601            }
5602        };
5603        Arrays.sort(overlayArray, cmp);
5604
5605        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5606        int i = 0;
5607        for (PackageParser.Package p : overlayArray) {
5608            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5609        }
5610        return true;
5611    }
5612
5613    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5614        final File[] files = dir.listFiles();
5615        if (ArrayUtils.isEmpty(files)) {
5616            Log.d(TAG, "No files in app dir " + dir);
5617            return;
5618        }
5619
5620        if (DEBUG_PACKAGE_SCANNING) {
5621            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5622                    + " flags=0x" + Integer.toHexString(parseFlags));
5623        }
5624
5625        for (File file : files) {
5626            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5627                    && !PackageInstallerService.isStageName(file.getName());
5628            if (!isPackage) {
5629                // Ignore entries which are not packages
5630                continue;
5631            }
5632            try {
5633                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5634                        scanFlags, currentTime, null);
5635            } catch (PackageManagerException e) {
5636                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5637
5638                // Delete invalid userdata apps
5639                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5640                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5641                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5642                    if (file.isDirectory()) {
5643                        mInstaller.rmPackageDir(file.getAbsolutePath());
5644                    } else {
5645                        file.delete();
5646                    }
5647                }
5648            }
5649        }
5650    }
5651
5652    private static File getSettingsProblemFile() {
5653        File dataDir = Environment.getDataDirectory();
5654        File systemDir = new File(dataDir, "system");
5655        File fname = new File(systemDir, "uiderrors.txt");
5656        return fname;
5657    }
5658
5659    static void reportSettingsProblem(int priority, String msg) {
5660        logCriticalInfo(priority, msg);
5661    }
5662
5663    static void logCriticalInfo(int priority, String msg) {
5664        Slog.println(priority, TAG, msg);
5665        EventLogTags.writePmCriticalInfo(msg);
5666        try {
5667            File fname = getSettingsProblemFile();
5668            FileOutputStream out = new FileOutputStream(fname, true);
5669            PrintWriter pw = new FastPrintWriter(out);
5670            SimpleDateFormat formatter = new SimpleDateFormat();
5671            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5672            pw.println(dateString + ": " + msg);
5673            pw.close();
5674            FileUtils.setPermissions(
5675                    fname.toString(),
5676                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5677                    -1, -1);
5678        } catch (java.io.IOException e) {
5679        }
5680    }
5681
5682    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5683            PackageParser.Package pkg, File srcFile, int parseFlags)
5684            throws PackageManagerException {
5685        if (ps != null
5686                && ps.codePath.equals(srcFile)
5687                && ps.timeStamp == srcFile.lastModified()
5688                && !isCompatSignatureUpdateNeeded(pkg)
5689                && !isRecoverSignatureUpdateNeeded(pkg)) {
5690            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5691            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5692            ArraySet<PublicKey> signingKs;
5693            synchronized (mPackages) {
5694                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5695            }
5696            if (ps.signatures.mSignatures != null
5697                    && ps.signatures.mSignatures.length != 0
5698                    && signingKs != null) {
5699                // Optimization: reuse the existing cached certificates
5700                // if the package appears to be unchanged.
5701                pkg.mSignatures = ps.signatures.mSignatures;
5702                pkg.mSigningKeys = signingKs;
5703                return;
5704            }
5705
5706            Slog.w(TAG, "PackageSetting for " + ps.name
5707                    + " is missing signatures.  Collecting certs again to recover them.");
5708        } else {
5709            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5710        }
5711
5712        try {
5713            pp.collectCertificates(pkg, parseFlags);
5714            pp.collectManifestDigest(pkg);
5715        } catch (PackageParserException e) {
5716            throw PackageManagerException.from(e);
5717        }
5718    }
5719
5720    /*
5721     *  Scan a package and return the newly parsed package.
5722     *  Returns null in case of errors and the error code is stored in mLastScanError
5723     */
5724    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5725            long currentTime, UserHandle user) throws PackageManagerException {
5726        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5727        parseFlags |= mDefParseFlags;
5728        PackageParser pp = new PackageParser();
5729        pp.setSeparateProcesses(mSeparateProcesses);
5730        pp.setOnlyCoreApps(mOnlyCore);
5731        pp.setDisplayMetrics(mMetrics);
5732
5733        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5734            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5735        }
5736
5737        final PackageParser.Package pkg;
5738        try {
5739            pkg = pp.parsePackage(scanFile, parseFlags);
5740        } catch (PackageParserException e) {
5741            throw PackageManagerException.from(e);
5742        }
5743
5744        PackageSetting ps = null;
5745        PackageSetting updatedPkg;
5746        // reader
5747        synchronized (mPackages) {
5748            // Look to see if we already know about this package.
5749            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5750            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5751                // This package has been renamed to its original name.  Let's
5752                // use that.
5753                ps = mSettings.peekPackageLPr(oldName);
5754            }
5755            // If there was no original package, see one for the real package name.
5756            if (ps == null) {
5757                ps = mSettings.peekPackageLPr(pkg.packageName);
5758            }
5759            // Check to see if this package could be hiding/updating a system
5760            // package.  Must look for it either under the original or real
5761            // package name depending on our state.
5762            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5763            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5764        }
5765        boolean updatedPkgBetter = false;
5766        // First check if this is a system package that may involve an update
5767        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5768            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5769            // it needs to drop FLAG_PRIVILEGED.
5770            if (locationIsPrivileged(scanFile)) {
5771                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5772            } else {
5773                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5774            }
5775
5776            if (ps != null && !ps.codePath.equals(scanFile)) {
5777                // The path has changed from what was last scanned...  check the
5778                // version of the new path against what we have stored to determine
5779                // what to do.
5780                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5781                if (pkg.mVersionCode <= ps.versionCode) {
5782                    // The system package has been updated and the code path does not match
5783                    // Ignore entry. Skip it.
5784                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5785                            + " ignored: updated version " + ps.versionCode
5786                            + " better than this " + pkg.mVersionCode);
5787                    if (!updatedPkg.codePath.equals(scanFile)) {
5788                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5789                                + ps.name + " changing from " + updatedPkg.codePathString
5790                                + " to " + scanFile);
5791                        updatedPkg.codePath = scanFile;
5792                        updatedPkg.codePathString = scanFile.toString();
5793                        updatedPkg.resourcePath = scanFile;
5794                        updatedPkg.resourcePathString = scanFile.toString();
5795                    }
5796                    updatedPkg.pkg = pkg;
5797                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5798                            "Package " + ps.name + " at " + scanFile
5799                                    + " ignored: updated version " + ps.versionCode
5800                                    + " better than this " + pkg.mVersionCode);
5801                } else {
5802                    // The current app on the system partition is better than
5803                    // what we have updated to on the data partition; switch
5804                    // back to the system partition version.
5805                    // At this point, its safely assumed that package installation for
5806                    // apps in system partition will go through. If not there won't be a working
5807                    // version of the app
5808                    // writer
5809                    synchronized (mPackages) {
5810                        // Just remove the loaded entries from package lists.
5811                        mPackages.remove(ps.name);
5812                    }
5813
5814                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5815                            + " reverting from " + ps.codePathString
5816                            + ": new version " + pkg.mVersionCode
5817                            + " better than installed " + ps.versionCode);
5818
5819                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5820                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5821                    synchronized (mInstallLock) {
5822                        args.cleanUpResourcesLI();
5823                    }
5824                    synchronized (mPackages) {
5825                        mSettings.enableSystemPackageLPw(ps.name);
5826                    }
5827                    updatedPkgBetter = true;
5828                }
5829            }
5830        }
5831
5832        if (updatedPkg != null) {
5833            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5834            // initially
5835            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5836
5837            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5838            // flag set initially
5839            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5840                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5841            }
5842        }
5843
5844        // Verify certificates against what was last scanned
5845        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5846
5847        /*
5848         * A new system app appeared, but we already had a non-system one of the
5849         * same name installed earlier.
5850         */
5851        boolean shouldHideSystemApp = false;
5852        if (updatedPkg == null && ps != null
5853                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5854            /*
5855             * Check to make sure the signatures match first. If they don't,
5856             * wipe the installed application and its data.
5857             */
5858            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5859                    != PackageManager.SIGNATURE_MATCH) {
5860                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5861                        + " signatures don't match existing userdata copy; removing");
5862                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5863                ps = null;
5864            } else {
5865                /*
5866                 * If the newly-added system app is an older version than the
5867                 * already installed version, hide it. It will be scanned later
5868                 * and re-added like an update.
5869                 */
5870                if (pkg.mVersionCode <= ps.versionCode) {
5871                    shouldHideSystemApp = true;
5872                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5873                            + " but new version " + pkg.mVersionCode + " better than installed "
5874                            + ps.versionCode + "; hiding system");
5875                } else {
5876                    /*
5877                     * The newly found system app is a newer version that the
5878                     * one previously installed. Simply remove the
5879                     * already-installed application and replace it with our own
5880                     * while keeping the application data.
5881                     */
5882                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5883                            + " reverting from " + ps.codePathString + ": new version "
5884                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5885                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5886                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5887                    synchronized (mInstallLock) {
5888                        args.cleanUpResourcesLI();
5889                    }
5890                }
5891            }
5892        }
5893
5894        // The apk is forward locked (not public) if its code and resources
5895        // are kept in different files. (except for app in either system or
5896        // vendor path).
5897        // TODO grab this value from PackageSettings
5898        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5899            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5900                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5901            }
5902        }
5903
5904        // TODO: extend to support forward-locked splits
5905        String resourcePath = null;
5906        String baseResourcePath = null;
5907        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5908            if (ps != null && ps.resourcePathString != null) {
5909                resourcePath = ps.resourcePathString;
5910                baseResourcePath = ps.resourcePathString;
5911            } else {
5912                // Should not happen at all. Just log an error.
5913                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5914            }
5915        } else {
5916            resourcePath = pkg.codePath;
5917            baseResourcePath = pkg.baseCodePath;
5918        }
5919
5920        // Set application objects path explicitly.
5921        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5922        pkg.applicationInfo.setCodePath(pkg.codePath);
5923        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5924        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5925        pkg.applicationInfo.setResourcePath(resourcePath);
5926        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5927        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5928
5929        // Note that we invoke the following method only if we are about to unpack an application
5930        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5931                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5932
5933        /*
5934         * If the system app should be overridden by a previously installed
5935         * data, hide the system app now and let the /data/app scan pick it up
5936         * again.
5937         */
5938        if (shouldHideSystemApp) {
5939            synchronized (mPackages) {
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                final long token = Binder.clearCallingIdentity();
13581                try {
13582                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13583                    if (secureContainerId != null) {
13584                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13585                    }
13586                } finally {
13587                    Binder.restoreCallingIdentity(token);
13588                }
13589            }
13590        }
13591        String publicSrcDir = null;
13592        if(!dataOnly) {
13593            final ApplicationInfo applicationInfo = p.applicationInfo;
13594            if (applicationInfo == null) {
13595                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13596                return false;
13597            }
13598            if (p.isForwardLocked()) {
13599                publicSrcDir = applicationInfo.getBaseResourcePath();
13600            }
13601        }
13602        // TODO: extend to measure size of split APKs
13603        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13604        // not just the first level.
13605        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13606        // just the primary.
13607        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13608
13609        String apkPath;
13610        File packageDir = new File(p.codePath);
13611
13612        if (packageDir.isDirectory() && p.canHaveOatDir()) {
13613            apkPath = packageDir.getAbsolutePath();
13614            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
13615            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
13616                libDirRoot = null;
13617            }
13618        } else {
13619            apkPath = p.baseCodePath;
13620        }
13621
13622        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
13623                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13624        if (res < 0) {
13625            return false;
13626        }
13627
13628        // Fix-up for forward-locked applications in ASEC containers.
13629        if (!isExternal(p)) {
13630            pStats.codeSize += pStats.externalCodeSize;
13631            pStats.externalCodeSize = 0L;
13632        }
13633
13634        return true;
13635    }
13636
13637
13638    @Override
13639    public void addPackageToPreferred(String packageName) {
13640        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13641    }
13642
13643    @Override
13644    public void removePackageFromPreferred(String packageName) {
13645        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13646    }
13647
13648    @Override
13649    public List<PackageInfo> getPreferredPackages(int flags) {
13650        return new ArrayList<PackageInfo>();
13651    }
13652
13653    private int getUidTargetSdkVersionLockedLPr(int uid) {
13654        Object obj = mSettings.getUserIdLPr(uid);
13655        if (obj instanceof SharedUserSetting) {
13656            final SharedUserSetting sus = (SharedUserSetting) obj;
13657            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13658            final Iterator<PackageSetting> it = sus.packages.iterator();
13659            while (it.hasNext()) {
13660                final PackageSetting ps = it.next();
13661                if (ps.pkg != null) {
13662                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13663                    if (v < vers) vers = v;
13664                }
13665            }
13666            return vers;
13667        } else if (obj instanceof PackageSetting) {
13668            final PackageSetting ps = (PackageSetting) obj;
13669            if (ps.pkg != null) {
13670                return ps.pkg.applicationInfo.targetSdkVersion;
13671            }
13672        }
13673        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13674    }
13675
13676    @Override
13677    public void addPreferredActivity(IntentFilter filter, int match,
13678            ComponentName[] set, ComponentName activity, int userId) {
13679        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13680                "Adding preferred");
13681    }
13682
13683    private void addPreferredActivityInternal(IntentFilter filter, int match,
13684            ComponentName[] set, ComponentName activity, boolean always, int userId,
13685            String opname) {
13686        // writer
13687        int callingUid = Binder.getCallingUid();
13688        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13689        if (filter.countActions() == 0) {
13690            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13691            return;
13692        }
13693        synchronized (mPackages) {
13694            if (mContext.checkCallingOrSelfPermission(
13695                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13696                    != PackageManager.PERMISSION_GRANTED) {
13697                if (getUidTargetSdkVersionLockedLPr(callingUid)
13698                        < Build.VERSION_CODES.FROYO) {
13699                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13700                            + callingUid);
13701                    return;
13702                }
13703                mContext.enforceCallingOrSelfPermission(
13704                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13705            }
13706
13707            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13708            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13709                    + userId + ":");
13710            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13711            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13712            scheduleWritePackageRestrictionsLocked(userId);
13713        }
13714    }
13715
13716    @Override
13717    public void replacePreferredActivity(IntentFilter filter, int match,
13718            ComponentName[] set, ComponentName activity, int userId) {
13719        if (filter.countActions() != 1) {
13720            throw new IllegalArgumentException(
13721                    "replacePreferredActivity expects filter to have only 1 action.");
13722        }
13723        if (filter.countDataAuthorities() != 0
13724                || filter.countDataPaths() != 0
13725                || filter.countDataSchemes() > 1
13726                || filter.countDataTypes() != 0) {
13727            throw new IllegalArgumentException(
13728                    "replacePreferredActivity expects filter to have no data authorities, " +
13729                    "paths, or types; and at most one scheme.");
13730        }
13731
13732        final int callingUid = Binder.getCallingUid();
13733        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13734        synchronized (mPackages) {
13735            if (mContext.checkCallingOrSelfPermission(
13736                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13737                    != PackageManager.PERMISSION_GRANTED) {
13738                if (getUidTargetSdkVersionLockedLPr(callingUid)
13739                        < Build.VERSION_CODES.FROYO) {
13740                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13741                            + Binder.getCallingUid());
13742                    return;
13743                }
13744                mContext.enforceCallingOrSelfPermission(
13745                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13746            }
13747
13748            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13749            if (pir != null) {
13750                // Get all of the existing entries that exactly match this filter.
13751                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13752                if (existing != null && existing.size() == 1) {
13753                    PreferredActivity cur = existing.get(0);
13754                    if (DEBUG_PREFERRED) {
13755                        Slog.i(TAG, "Checking replace of preferred:");
13756                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13757                        if (!cur.mPref.mAlways) {
13758                            Slog.i(TAG, "  -- CUR; not mAlways!");
13759                        } else {
13760                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13761                            Slog.i(TAG, "  -- CUR: mSet="
13762                                    + Arrays.toString(cur.mPref.mSetComponents));
13763                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13764                            Slog.i(TAG, "  -- NEW: mMatch="
13765                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13766                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13767                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13768                        }
13769                    }
13770                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13771                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13772                            && cur.mPref.sameSet(set)) {
13773                        // Setting the preferred activity to what it happens to be already
13774                        if (DEBUG_PREFERRED) {
13775                            Slog.i(TAG, "Replacing with same preferred activity "
13776                                    + cur.mPref.mShortComponent + " for user "
13777                                    + userId + ":");
13778                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13779                        }
13780                        return;
13781                    }
13782                }
13783
13784                if (existing != null) {
13785                    if (DEBUG_PREFERRED) {
13786                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13787                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13788                    }
13789                    for (int i = 0; i < existing.size(); i++) {
13790                        PreferredActivity pa = existing.get(i);
13791                        if (DEBUG_PREFERRED) {
13792                            Slog.i(TAG, "Removing existing preferred activity "
13793                                    + pa.mPref.mComponent + ":");
13794                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13795                        }
13796                        pir.removeFilter(pa);
13797                    }
13798                }
13799            }
13800            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13801                    "Replacing preferred");
13802        }
13803    }
13804
13805    @Override
13806    public void clearPackagePreferredActivities(String packageName) {
13807        final int uid = Binder.getCallingUid();
13808        // writer
13809        synchronized (mPackages) {
13810            PackageParser.Package pkg = mPackages.get(packageName);
13811            if (pkg == null || pkg.applicationInfo.uid != uid) {
13812                if (mContext.checkCallingOrSelfPermission(
13813                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13814                        != PackageManager.PERMISSION_GRANTED) {
13815                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13816                            < Build.VERSION_CODES.FROYO) {
13817                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13818                                + Binder.getCallingUid());
13819                        return;
13820                    }
13821                    mContext.enforceCallingOrSelfPermission(
13822                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13823                }
13824            }
13825
13826            int user = UserHandle.getCallingUserId();
13827            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13828                scheduleWritePackageRestrictionsLocked(user);
13829            }
13830        }
13831    }
13832
13833    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13834    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13835        ArrayList<PreferredActivity> removed = null;
13836        boolean changed = false;
13837        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13838            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13839            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13840            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13841                continue;
13842            }
13843            Iterator<PreferredActivity> it = pir.filterIterator();
13844            while (it.hasNext()) {
13845                PreferredActivity pa = it.next();
13846                // Mark entry for removal only if it matches the package name
13847                // and the entry is of type "always".
13848                if (packageName == null ||
13849                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13850                                && pa.mPref.mAlways)) {
13851                    if (removed == null) {
13852                        removed = new ArrayList<PreferredActivity>();
13853                    }
13854                    removed.add(pa);
13855                }
13856            }
13857            if (removed != null) {
13858                for (int j=0; j<removed.size(); j++) {
13859                    PreferredActivity pa = removed.get(j);
13860                    pir.removeFilter(pa);
13861                }
13862                changed = true;
13863            }
13864        }
13865        return changed;
13866    }
13867
13868    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13869    private void clearIntentFilterVerificationsLPw(int userId) {
13870        final int packageCount = mPackages.size();
13871        for (int i = 0; i < packageCount; i++) {
13872            PackageParser.Package pkg = mPackages.valueAt(i);
13873            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13874        }
13875    }
13876
13877    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13878    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13879        if (userId == UserHandle.USER_ALL) {
13880            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13881                    sUserManager.getUserIds())) {
13882                for (int oneUserId : sUserManager.getUserIds()) {
13883                    scheduleWritePackageRestrictionsLocked(oneUserId);
13884                }
13885            }
13886        } else {
13887            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13888                scheduleWritePackageRestrictionsLocked(userId);
13889            }
13890        }
13891    }
13892
13893    void clearDefaultBrowserIfNeeded(String packageName) {
13894        for (int oneUserId : sUserManager.getUserIds()) {
13895            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13896            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13897            if (packageName.equals(defaultBrowserPackageName)) {
13898                setDefaultBrowserPackageName(null, oneUserId);
13899            }
13900        }
13901    }
13902
13903    @Override
13904    public void resetApplicationPreferences(int userId) {
13905        mContext.enforceCallingOrSelfPermission(
13906                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13907        // writer
13908        synchronized (mPackages) {
13909            final long identity = Binder.clearCallingIdentity();
13910            try {
13911                clearPackagePreferredActivitiesLPw(null, userId);
13912                mSettings.applyDefaultPreferredAppsLPw(this, userId);
13913                // TODO: We have to reset the default SMS and Phone. This requires
13914                // significant refactoring to keep all default apps in the package
13915                // manager (cleaner but more work) or have the services provide
13916                // callbacks to the package manager to request a default app reset.
13917                applyFactoryDefaultBrowserLPw(userId);
13918                clearIntentFilterVerificationsLPw(userId);
13919                primeDomainVerificationsLPw(userId);
13920                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
13921                scheduleWritePackageRestrictionsLocked(userId);
13922            } finally {
13923                Binder.restoreCallingIdentity(identity);
13924            }
13925        }
13926    }
13927
13928    @Override
13929    public int getPreferredActivities(List<IntentFilter> outFilters,
13930            List<ComponentName> outActivities, String packageName) {
13931
13932        int num = 0;
13933        final int userId = UserHandle.getCallingUserId();
13934        // reader
13935        synchronized (mPackages) {
13936            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13937            if (pir != null) {
13938                final Iterator<PreferredActivity> it = pir.filterIterator();
13939                while (it.hasNext()) {
13940                    final PreferredActivity pa = it.next();
13941                    if (packageName == null
13942                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13943                                    && pa.mPref.mAlways)) {
13944                        if (outFilters != null) {
13945                            outFilters.add(new IntentFilter(pa));
13946                        }
13947                        if (outActivities != null) {
13948                            outActivities.add(pa.mPref.mComponent);
13949                        }
13950                    }
13951                }
13952            }
13953        }
13954
13955        return num;
13956    }
13957
13958    @Override
13959    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13960            int userId) {
13961        int callingUid = Binder.getCallingUid();
13962        if (callingUid != Process.SYSTEM_UID) {
13963            throw new SecurityException(
13964                    "addPersistentPreferredActivity can only be run by the system");
13965        }
13966        if (filter.countActions() == 0) {
13967            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13968            return;
13969        }
13970        synchronized (mPackages) {
13971            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13972                    " :");
13973            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13974            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13975                    new PersistentPreferredActivity(filter, activity));
13976            scheduleWritePackageRestrictionsLocked(userId);
13977        }
13978    }
13979
13980    @Override
13981    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13982        int callingUid = Binder.getCallingUid();
13983        if (callingUid != Process.SYSTEM_UID) {
13984            throw new SecurityException(
13985                    "clearPackagePersistentPreferredActivities can only be run by the system");
13986        }
13987        ArrayList<PersistentPreferredActivity> removed = null;
13988        boolean changed = false;
13989        synchronized (mPackages) {
13990            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13991                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13992                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13993                        .valueAt(i);
13994                if (userId != thisUserId) {
13995                    continue;
13996                }
13997                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13998                while (it.hasNext()) {
13999                    PersistentPreferredActivity ppa = it.next();
14000                    // Mark entry for removal only if it matches the package name.
14001                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14002                        if (removed == null) {
14003                            removed = new ArrayList<PersistentPreferredActivity>();
14004                        }
14005                        removed.add(ppa);
14006                    }
14007                }
14008                if (removed != null) {
14009                    for (int j=0; j<removed.size(); j++) {
14010                        PersistentPreferredActivity ppa = removed.get(j);
14011                        ppir.removeFilter(ppa);
14012                    }
14013                    changed = true;
14014                }
14015            }
14016
14017            if (changed) {
14018                scheduleWritePackageRestrictionsLocked(userId);
14019            }
14020        }
14021    }
14022
14023    /**
14024     * Common machinery for picking apart a restored XML blob and passing
14025     * it to a caller-supplied functor to be applied to the running system.
14026     */
14027    private void restoreFromXml(XmlPullParser parser, int userId,
14028            String expectedStartTag, BlobXmlRestorer functor)
14029            throws IOException, XmlPullParserException {
14030        int type;
14031        while ((type = parser.next()) != XmlPullParser.START_TAG
14032                && type != XmlPullParser.END_DOCUMENT) {
14033        }
14034        if (type != XmlPullParser.START_TAG) {
14035            // oops didn't find a start tag?!
14036            if (DEBUG_BACKUP) {
14037                Slog.e(TAG, "Didn't find start tag during restore");
14038            }
14039            return;
14040        }
14041
14042        // this is supposed to be TAG_PREFERRED_BACKUP
14043        if (!expectedStartTag.equals(parser.getName())) {
14044            if (DEBUG_BACKUP) {
14045                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14046            }
14047            return;
14048        }
14049
14050        // skip interfering stuff, then we're aligned with the backing implementation
14051        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14052        functor.apply(parser, userId);
14053    }
14054
14055    private interface BlobXmlRestorer {
14056        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14057    }
14058
14059    /**
14060     * Non-Binder method, support for the backup/restore mechanism: write the
14061     * full set of preferred activities in its canonical XML format.  Returns the
14062     * XML output as a byte array, or null if there is none.
14063     */
14064    @Override
14065    public byte[] getPreferredActivityBackup(int userId) {
14066        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14067            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14068        }
14069
14070        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14071        try {
14072            final XmlSerializer serializer = new FastXmlSerializer();
14073            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14074            serializer.startDocument(null, true);
14075            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14076
14077            synchronized (mPackages) {
14078                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14079            }
14080
14081            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14082            serializer.endDocument();
14083            serializer.flush();
14084        } catch (Exception e) {
14085            if (DEBUG_BACKUP) {
14086                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14087            }
14088            return null;
14089        }
14090
14091        return dataStream.toByteArray();
14092    }
14093
14094    @Override
14095    public void restorePreferredActivities(byte[] backup, int userId) {
14096        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14097            throw new SecurityException("Only the system may call restorePreferredActivities()");
14098        }
14099
14100        try {
14101            final XmlPullParser parser = Xml.newPullParser();
14102            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14103            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14104                    new BlobXmlRestorer() {
14105                        @Override
14106                        public void apply(XmlPullParser parser, int userId)
14107                                throws XmlPullParserException, IOException {
14108                            synchronized (mPackages) {
14109                                mSettings.readPreferredActivitiesLPw(parser, userId);
14110                            }
14111                        }
14112                    } );
14113        } catch (Exception e) {
14114            if (DEBUG_BACKUP) {
14115                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14116            }
14117        }
14118    }
14119
14120    /**
14121     * Non-Binder method, support for the backup/restore mechanism: write the
14122     * default browser (etc) settings in its canonical XML format.  Returns the default
14123     * browser XML representation as a byte array, or null if there is none.
14124     */
14125    @Override
14126    public byte[] getDefaultAppsBackup(int userId) {
14127        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14128            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14129        }
14130
14131        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14132        try {
14133            final XmlSerializer serializer = new FastXmlSerializer();
14134            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14135            serializer.startDocument(null, true);
14136            serializer.startTag(null, TAG_DEFAULT_APPS);
14137
14138            synchronized (mPackages) {
14139                mSettings.writeDefaultAppsLPr(serializer, userId);
14140            }
14141
14142            serializer.endTag(null, TAG_DEFAULT_APPS);
14143            serializer.endDocument();
14144            serializer.flush();
14145        } catch (Exception e) {
14146            if (DEBUG_BACKUP) {
14147                Slog.e(TAG, "Unable to write default apps for backup", e);
14148            }
14149            return null;
14150        }
14151
14152        return dataStream.toByteArray();
14153    }
14154
14155    @Override
14156    public void restoreDefaultApps(byte[] backup, int userId) {
14157        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14158            throw new SecurityException("Only the system may call restoreDefaultApps()");
14159        }
14160
14161        try {
14162            final XmlPullParser parser = Xml.newPullParser();
14163            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14164            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14165                    new BlobXmlRestorer() {
14166                        @Override
14167                        public void apply(XmlPullParser parser, int userId)
14168                                throws XmlPullParserException, IOException {
14169                            synchronized (mPackages) {
14170                                mSettings.readDefaultAppsLPw(parser, userId);
14171                            }
14172                        }
14173                    } );
14174        } catch (Exception e) {
14175            if (DEBUG_BACKUP) {
14176                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14177            }
14178        }
14179    }
14180
14181    @Override
14182    public byte[] getIntentFilterVerificationBackup(int userId) {
14183        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14184            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14185        }
14186
14187        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14188        try {
14189            final XmlSerializer serializer = new FastXmlSerializer();
14190            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14191            serializer.startDocument(null, true);
14192            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14193
14194            synchronized (mPackages) {
14195                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14196            }
14197
14198            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14199            serializer.endDocument();
14200            serializer.flush();
14201        } catch (Exception e) {
14202            if (DEBUG_BACKUP) {
14203                Slog.e(TAG, "Unable to write default apps for backup", e);
14204            }
14205            return null;
14206        }
14207
14208        return dataStream.toByteArray();
14209    }
14210
14211    @Override
14212    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14213        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14214            throw new SecurityException("Only the system may call restorePreferredActivities()");
14215        }
14216
14217        try {
14218            final XmlPullParser parser = Xml.newPullParser();
14219            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14220            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14221                    new BlobXmlRestorer() {
14222                        @Override
14223                        public void apply(XmlPullParser parser, int userId)
14224                                throws XmlPullParserException, IOException {
14225                            synchronized (mPackages) {
14226                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14227                                mSettings.writeLPr();
14228                            }
14229                        }
14230                    } );
14231        } catch (Exception e) {
14232            if (DEBUG_BACKUP) {
14233                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14234            }
14235        }
14236    }
14237
14238    @Override
14239    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14240            int sourceUserId, int targetUserId, int flags) {
14241        mContext.enforceCallingOrSelfPermission(
14242                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14243        int callingUid = Binder.getCallingUid();
14244        enforceOwnerRights(ownerPackage, callingUid);
14245        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14246        if (intentFilter.countActions() == 0) {
14247            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14248            return;
14249        }
14250        synchronized (mPackages) {
14251            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14252                    ownerPackage, targetUserId, flags);
14253            CrossProfileIntentResolver resolver =
14254                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14255            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14256            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14257            if (existing != null) {
14258                int size = existing.size();
14259                for (int i = 0; i < size; i++) {
14260                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14261                        return;
14262                    }
14263                }
14264            }
14265            resolver.addFilter(newFilter);
14266            scheduleWritePackageRestrictionsLocked(sourceUserId);
14267        }
14268    }
14269
14270    @Override
14271    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14272        mContext.enforceCallingOrSelfPermission(
14273                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14274        int callingUid = Binder.getCallingUid();
14275        enforceOwnerRights(ownerPackage, callingUid);
14276        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14277        synchronized (mPackages) {
14278            CrossProfileIntentResolver resolver =
14279                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14280            ArraySet<CrossProfileIntentFilter> set =
14281                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14282            for (CrossProfileIntentFilter filter : set) {
14283                if (filter.getOwnerPackage().equals(ownerPackage)) {
14284                    resolver.removeFilter(filter);
14285                }
14286            }
14287            scheduleWritePackageRestrictionsLocked(sourceUserId);
14288        }
14289    }
14290
14291    // Enforcing that callingUid is owning pkg on userId
14292    private void enforceOwnerRights(String pkg, int callingUid) {
14293        // The system owns everything.
14294        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14295            return;
14296        }
14297        int callingUserId = UserHandle.getUserId(callingUid);
14298        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14299        if (pi == null) {
14300            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14301                    + callingUserId);
14302        }
14303        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14304            throw new SecurityException("Calling uid " + callingUid
14305                    + " does not own package " + pkg);
14306        }
14307    }
14308
14309    @Override
14310    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14311        Intent intent = new Intent(Intent.ACTION_MAIN);
14312        intent.addCategory(Intent.CATEGORY_HOME);
14313
14314        final int callingUserId = UserHandle.getCallingUserId();
14315        List<ResolveInfo> list = queryIntentActivities(intent, null,
14316                PackageManager.GET_META_DATA, callingUserId);
14317        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14318                true, false, false, callingUserId);
14319
14320        allHomeCandidates.clear();
14321        if (list != null) {
14322            for (ResolveInfo ri : list) {
14323                allHomeCandidates.add(ri);
14324            }
14325        }
14326        return (preferred == null || preferred.activityInfo == null)
14327                ? null
14328                : new ComponentName(preferred.activityInfo.packageName,
14329                        preferred.activityInfo.name);
14330    }
14331
14332    @Override
14333    public void setApplicationEnabledSetting(String appPackageName,
14334            int newState, int flags, int userId, String callingPackage) {
14335        if (!sUserManager.exists(userId)) return;
14336        if (callingPackage == null) {
14337            callingPackage = Integer.toString(Binder.getCallingUid());
14338        }
14339        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14340    }
14341
14342    @Override
14343    public void setComponentEnabledSetting(ComponentName componentName,
14344            int newState, int flags, int userId) {
14345        if (!sUserManager.exists(userId)) return;
14346        setEnabledSetting(componentName.getPackageName(),
14347                componentName.getClassName(), newState, flags, userId, null);
14348    }
14349
14350    private void setEnabledSetting(final String packageName, String className, int newState,
14351            final int flags, int userId, String callingPackage) {
14352        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14353              || newState == COMPONENT_ENABLED_STATE_ENABLED
14354              || newState == COMPONENT_ENABLED_STATE_DISABLED
14355              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14356              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14357            throw new IllegalArgumentException("Invalid new component state: "
14358                    + newState);
14359        }
14360        PackageSetting pkgSetting;
14361        final int uid = Binder.getCallingUid();
14362        final int permission = mContext.checkCallingOrSelfPermission(
14363                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14364        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14365        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14366        boolean sendNow = false;
14367        boolean isApp = (className == null);
14368        String componentName = isApp ? packageName : className;
14369        int packageUid = -1;
14370        ArrayList<String> components;
14371
14372        // writer
14373        synchronized (mPackages) {
14374            pkgSetting = mSettings.mPackages.get(packageName);
14375            if (pkgSetting == null) {
14376                if (className == null) {
14377                    throw new IllegalArgumentException(
14378                            "Unknown package: " + packageName);
14379                }
14380                throw new IllegalArgumentException(
14381                        "Unknown component: " + packageName
14382                        + "/" + className);
14383            }
14384            // Allow root and verify that userId is not being specified by a different user
14385            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14386                throw new SecurityException(
14387                        "Permission Denial: attempt to change component state from pid="
14388                        + Binder.getCallingPid()
14389                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14390            }
14391            if (className == null) {
14392                // We're dealing with an application/package level state change
14393                if (pkgSetting.getEnabled(userId) == newState) {
14394                    // Nothing to do
14395                    return;
14396                }
14397                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14398                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14399                    // Don't care about who enables an app.
14400                    callingPackage = null;
14401                }
14402                pkgSetting.setEnabled(newState, userId, callingPackage);
14403                // pkgSetting.pkg.mSetEnabled = newState;
14404            } else {
14405                // We're dealing with a component level state change
14406                // First, verify that this is a valid class name.
14407                PackageParser.Package pkg = pkgSetting.pkg;
14408                if (pkg == null || !pkg.hasComponentClassName(className)) {
14409                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14410                        throw new IllegalArgumentException("Component class " + className
14411                                + " does not exist in " + packageName);
14412                    } else {
14413                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14414                                + className + " does not exist in " + packageName);
14415                    }
14416                }
14417                switch (newState) {
14418                case COMPONENT_ENABLED_STATE_ENABLED:
14419                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14420                        return;
14421                    }
14422                    break;
14423                case COMPONENT_ENABLED_STATE_DISABLED:
14424                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14425                        return;
14426                    }
14427                    break;
14428                case COMPONENT_ENABLED_STATE_DEFAULT:
14429                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14430                        return;
14431                    }
14432                    break;
14433                default:
14434                    Slog.e(TAG, "Invalid new component state: " + newState);
14435                    return;
14436                }
14437            }
14438            scheduleWritePackageRestrictionsLocked(userId);
14439            components = mPendingBroadcasts.get(userId, packageName);
14440            final boolean newPackage = components == null;
14441            if (newPackage) {
14442                components = new ArrayList<String>();
14443            }
14444            if (!components.contains(componentName)) {
14445                components.add(componentName);
14446            }
14447            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14448                sendNow = true;
14449                // Purge entry from pending broadcast list if another one exists already
14450                // since we are sending one right away.
14451                mPendingBroadcasts.remove(userId, packageName);
14452            } else {
14453                if (newPackage) {
14454                    mPendingBroadcasts.put(userId, packageName, components);
14455                }
14456                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14457                    // Schedule a message
14458                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14459                }
14460            }
14461        }
14462
14463        long callingId = Binder.clearCallingIdentity();
14464        try {
14465            if (sendNow) {
14466                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14467                sendPackageChangedBroadcast(packageName,
14468                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14469            }
14470        } finally {
14471            Binder.restoreCallingIdentity(callingId);
14472        }
14473    }
14474
14475    private void sendPackageChangedBroadcast(String packageName,
14476            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14477        if (DEBUG_INSTALL)
14478            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14479                    + componentNames);
14480        Bundle extras = new Bundle(4);
14481        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14482        String nameList[] = new String[componentNames.size()];
14483        componentNames.toArray(nameList);
14484        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14485        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14486        extras.putInt(Intent.EXTRA_UID, packageUid);
14487        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14488                new int[] {UserHandle.getUserId(packageUid)});
14489    }
14490
14491    @Override
14492    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14493        if (!sUserManager.exists(userId)) return;
14494        final int uid = Binder.getCallingUid();
14495        final int permission = mContext.checkCallingOrSelfPermission(
14496                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14497        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14498        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14499        // writer
14500        synchronized (mPackages) {
14501            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14502                    allowedByPermission, uid, userId)) {
14503                scheduleWritePackageRestrictionsLocked(userId);
14504            }
14505        }
14506    }
14507
14508    @Override
14509    public String getInstallerPackageName(String packageName) {
14510        // reader
14511        synchronized (mPackages) {
14512            return mSettings.getInstallerPackageNameLPr(packageName);
14513        }
14514    }
14515
14516    @Override
14517    public int getApplicationEnabledSetting(String packageName, int userId) {
14518        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14519        int uid = Binder.getCallingUid();
14520        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14521        // reader
14522        synchronized (mPackages) {
14523            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14524        }
14525    }
14526
14527    @Override
14528    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14529        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14530        int uid = Binder.getCallingUid();
14531        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14532        // reader
14533        synchronized (mPackages) {
14534            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14535        }
14536    }
14537
14538    @Override
14539    public void enterSafeMode() {
14540        enforceSystemOrRoot("Only the system can request entering safe mode");
14541
14542        if (!mSystemReady) {
14543            mSafeMode = true;
14544        }
14545    }
14546
14547    @Override
14548    public void systemReady() {
14549        mSystemReady = true;
14550
14551        // Read the compatibilty setting when the system is ready.
14552        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14553                mContext.getContentResolver(),
14554                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14555        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14556        if (DEBUG_SETTINGS) {
14557            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14558        }
14559
14560        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14561
14562        synchronized (mPackages) {
14563            // Verify that all of the preferred activity components actually
14564            // exist.  It is possible for applications to be updated and at
14565            // that point remove a previously declared activity component that
14566            // had been set as a preferred activity.  We try to clean this up
14567            // the next time we encounter that preferred activity, but it is
14568            // possible for the user flow to never be able to return to that
14569            // situation so here we do a sanity check to make sure we haven't
14570            // left any junk around.
14571            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14572            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14573                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14574                removed.clear();
14575                for (PreferredActivity pa : pir.filterSet()) {
14576                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14577                        removed.add(pa);
14578                    }
14579                }
14580                if (removed.size() > 0) {
14581                    for (int r=0; r<removed.size(); r++) {
14582                        PreferredActivity pa = removed.get(r);
14583                        Slog.w(TAG, "Removing dangling preferred activity: "
14584                                + pa.mPref.mComponent);
14585                        pir.removeFilter(pa);
14586                    }
14587                    mSettings.writePackageRestrictionsLPr(
14588                            mSettings.mPreferredActivities.keyAt(i));
14589                }
14590            }
14591
14592            for (int userId : UserManagerService.getInstance().getUserIds()) {
14593                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14594                    grantPermissionsUserIds = ArrayUtils.appendInt(
14595                            grantPermissionsUserIds, userId);
14596                }
14597            }
14598        }
14599        sUserManager.systemReady();
14600
14601        // If we upgraded grant all default permissions before kicking off.
14602        for (int userId : grantPermissionsUserIds) {
14603            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14604        }
14605
14606        // Kick off any messages waiting for system ready
14607        if (mPostSystemReadyMessages != null) {
14608            for (Message msg : mPostSystemReadyMessages) {
14609                msg.sendToTarget();
14610            }
14611            mPostSystemReadyMessages = null;
14612        }
14613
14614        // Watch for external volumes that come and go over time
14615        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14616        storage.registerListener(mStorageListener);
14617
14618        mInstallerService.systemReady();
14619        mPackageDexOptimizer.systemReady();
14620
14621        MountServiceInternal mountServiceInternal = LocalServices.getService(
14622                MountServiceInternal.class);
14623        mountServiceInternal.addExternalStoragePolicy(
14624                new MountServiceInternal.ExternalStorageMountPolicy() {
14625            @Override
14626            public int getMountMode(int uid, String packageName) {
14627                if (Process.isIsolated(uid)) {
14628                    return Zygote.MOUNT_EXTERNAL_NONE;
14629                }
14630                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14631                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14632                }
14633                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14634                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14635                }
14636                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14637                    return Zygote.MOUNT_EXTERNAL_READ;
14638                }
14639                return Zygote.MOUNT_EXTERNAL_WRITE;
14640            }
14641
14642            @Override
14643            public boolean hasExternalStorage(int uid, String packageName) {
14644                return true;
14645            }
14646        });
14647    }
14648
14649    @Override
14650    public boolean isSafeMode() {
14651        return mSafeMode;
14652    }
14653
14654    @Override
14655    public boolean hasSystemUidErrors() {
14656        return mHasSystemUidErrors;
14657    }
14658
14659    static String arrayToString(int[] array) {
14660        StringBuffer buf = new StringBuffer(128);
14661        buf.append('[');
14662        if (array != null) {
14663            for (int i=0; i<array.length; i++) {
14664                if (i > 0) buf.append(", ");
14665                buf.append(array[i]);
14666            }
14667        }
14668        buf.append(']');
14669        return buf.toString();
14670    }
14671
14672    static class DumpState {
14673        public static final int DUMP_LIBS = 1 << 0;
14674        public static final int DUMP_FEATURES = 1 << 1;
14675        public static final int DUMP_RESOLVERS = 1 << 2;
14676        public static final int DUMP_PERMISSIONS = 1 << 3;
14677        public static final int DUMP_PACKAGES = 1 << 4;
14678        public static final int DUMP_SHARED_USERS = 1 << 5;
14679        public static final int DUMP_MESSAGES = 1 << 6;
14680        public static final int DUMP_PROVIDERS = 1 << 7;
14681        public static final int DUMP_VERIFIERS = 1 << 8;
14682        public static final int DUMP_PREFERRED = 1 << 9;
14683        public static final int DUMP_PREFERRED_XML = 1 << 10;
14684        public static final int DUMP_KEYSETS = 1 << 11;
14685        public static final int DUMP_VERSION = 1 << 12;
14686        public static final int DUMP_INSTALLS = 1 << 13;
14687        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14688        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14689
14690        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14691
14692        private int mTypes;
14693
14694        private int mOptions;
14695
14696        private boolean mTitlePrinted;
14697
14698        private SharedUserSetting mSharedUser;
14699
14700        public boolean isDumping(int type) {
14701            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14702                return true;
14703            }
14704
14705            return (mTypes & type) != 0;
14706        }
14707
14708        public void setDump(int type) {
14709            mTypes |= type;
14710        }
14711
14712        public boolean isOptionEnabled(int option) {
14713            return (mOptions & option) != 0;
14714        }
14715
14716        public void setOptionEnabled(int option) {
14717            mOptions |= option;
14718        }
14719
14720        public boolean onTitlePrinted() {
14721            final boolean printed = mTitlePrinted;
14722            mTitlePrinted = true;
14723            return printed;
14724        }
14725
14726        public boolean getTitlePrinted() {
14727            return mTitlePrinted;
14728        }
14729
14730        public void setTitlePrinted(boolean enabled) {
14731            mTitlePrinted = enabled;
14732        }
14733
14734        public SharedUserSetting getSharedUser() {
14735            return mSharedUser;
14736        }
14737
14738        public void setSharedUser(SharedUserSetting user) {
14739            mSharedUser = user;
14740        }
14741    }
14742
14743    @Override
14744    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14745        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14746                != PackageManager.PERMISSION_GRANTED) {
14747            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14748                    + Binder.getCallingPid()
14749                    + ", uid=" + Binder.getCallingUid()
14750                    + " without permission "
14751                    + android.Manifest.permission.DUMP);
14752            return;
14753        }
14754
14755        DumpState dumpState = new DumpState();
14756        boolean fullPreferred = false;
14757        boolean checkin = false;
14758
14759        String packageName = null;
14760        ArraySet<String> permissionNames = null;
14761
14762        int opti = 0;
14763        while (opti < args.length) {
14764            String opt = args[opti];
14765            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14766                break;
14767            }
14768            opti++;
14769
14770            if ("-a".equals(opt)) {
14771                // Right now we only know how to print all.
14772            } else if ("-h".equals(opt)) {
14773                pw.println("Package manager dump options:");
14774                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14775                pw.println("    --checkin: dump for a checkin");
14776                pw.println("    -f: print details of intent filters");
14777                pw.println("    -h: print this help");
14778                pw.println("  cmd may be one of:");
14779                pw.println("    l[ibraries]: list known shared libraries");
14780                pw.println("    f[ibraries]: list device features");
14781                pw.println("    k[eysets]: print known keysets");
14782                pw.println("    r[esolvers]: dump intent resolvers");
14783                pw.println("    perm[issions]: dump permissions");
14784                pw.println("    permission [name ...]: dump declaration and use of given permission");
14785                pw.println("    pref[erred]: print preferred package settings");
14786                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14787                pw.println("    prov[iders]: dump content providers");
14788                pw.println("    p[ackages]: dump installed packages");
14789                pw.println("    s[hared-users]: dump shared user IDs");
14790                pw.println("    m[essages]: print collected runtime messages");
14791                pw.println("    v[erifiers]: print package verifier info");
14792                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14793                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14794                pw.println("    version: print database version info");
14795                pw.println("    write: write current settings now");
14796                pw.println("    installs: details about install sessions");
14797                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
14798                pw.println("    <package.name>: info about given package");
14799                return;
14800            } else if ("--checkin".equals(opt)) {
14801                checkin = true;
14802            } else if ("-f".equals(opt)) {
14803                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14804            } else {
14805                pw.println("Unknown argument: " + opt + "; use -h for help");
14806            }
14807        }
14808
14809        // Is the caller requesting to dump a particular piece of data?
14810        if (opti < args.length) {
14811            String cmd = args[opti];
14812            opti++;
14813            // Is this a package name?
14814            if ("android".equals(cmd) || cmd.contains(".")) {
14815                packageName = cmd;
14816                // When dumping a single package, we always dump all of its
14817                // filter information since the amount of data will be reasonable.
14818                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14819            } else if ("check-permission".equals(cmd)) {
14820                if (opti >= args.length) {
14821                    pw.println("Error: check-permission missing permission argument");
14822                    return;
14823                }
14824                String perm = args[opti];
14825                opti++;
14826                if (opti >= args.length) {
14827                    pw.println("Error: check-permission missing package argument");
14828                    return;
14829                }
14830                String pkg = args[opti];
14831                opti++;
14832                int user = UserHandle.getUserId(Binder.getCallingUid());
14833                if (opti < args.length) {
14834                    try {
14835                        user = Integer.parseInt(args[opti]);
14836                    } catch (NumberFormatException e) {
14837                        pw.println("Error: check-permission user argument is not a number: "
14838                                + args[opti]);
14839                        return;
14840                    }
14841                }
14842                pw.println(checkPermission(perm, pkg, user));
14843                return;
14844            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14845                dumpState.setDump(DumpState.DUMP_LIBS);
14846            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14847                dumpState.setDump(DumpState.DUMP_FEATURES);
14848            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14849                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14850            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14851                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14852            } else if ("permission".equals(cmd)) {
14853                if (opti >= args.length) {
14854                    pw.println("Error: permission requires permission name");
14855                    return;
14856                }
14857                permissionNames = new ArraySet<>();
14858                while (opti < args.length) {
14859                    permissionNames.add(args[opti]);
14860                    opti++;
14861                }
14862                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14863                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14864            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14865                dumpState.setDump(DumpState.DUMP_PREFERRED);
14866            } else if ("preferred-xml".equals(cmd)) {
14867                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14868                if (opti < args.length && "--full".equals(args[opti])) {
14869                    fullPreferred = true;
14870                    opti++;
14871                }
14872            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14873                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14874            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14875                dumpState.setDump(DumpState.DUMP_PACKAGES);
14876            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14877                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14878            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14879                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14880            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14881                dumpState.setDump(DumpState.DUMP_MESSAGES);
14882            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14883                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14884            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14885                    || "intent-filter-verifiers".equals(cmd)) {
14886                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14887            } else if ("version".equals(cmd)) {
14888                dumpState.setDump(DumpState.DUMP_VERSION);
14889            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14890                dumpState.setDump(DumpState.DUMP_KEYSETS);
14891            } else if ("installs".equals(cmd)) {
14892                dumpState.setDump(DumpState.DUMP_INSTALLS);
14893            } else if ("write".equals(cmd)) {
14894                synchronized (mPackages) {
14895                    mSettings.writeLPr();
14896                    pw.println("Settings written.");
14897                    return;
14898                }
14899            }
14900        }
14901
14902        if (checkin) {
14903            pw.println("vers,1");
14904        }
14905
14906        // reader
14907        synchronized (mPackages) {
14908            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14909                if (!checkin) {
14910                    if (dumpState.onTitlePrinted())
14911                        pw.println();
14912                    pw.println("Database versions:");
14913                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
14914                }
14915            }
14916
14917            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14918                if (!checkin) {
14919                    if (dumpState.onTitlePrinted())
14920                        pw.println();
14921                    pw.println("Verifiers:");
14922                    pw.print("  Required: ");
14923                    pw.print(mRequiredVerifierPackage);
14924                    pw.print(" (uid=");
14925                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14926                    pw.println(")");
14927                } else if (mRequiredVerifierPackage != null) {
14928                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14929                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14930                }
14931            }
14932
14933            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14934                    packageName == null) {
14935                if (mIntentFilterVerifierComponent != null) {
14936                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14937                    if (!checkin) {
14938                        if (dumpState.onTitlePrinted())
14939                            pw.println();
14940                        pw.println("Intent Filter Verifier:");
14941                        pw.print("  Using: ");
14942                        pw.print(verifierPackageName);
14943                        pw.print(" (uid=");
14944                        pw.print(getPackageUid(verifierPackageName, 0));
14945                        pw.println(")");
14946                    } else if (verifierPackageName != null) {
14947                        pw.print("ifv,"); pw.print(verifierPackageName);
14948                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14949                    }
14950                } else {
14951                    pw.println();
14952                    pw.println("No Intent Filter Verifier available!");
14953                }
14954            }
14955
14956            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14957                boolean printedHeader = false;
14958                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14959                while (it.hasNext()) {
14960                    String name = it.next();
14961                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14962                    if (!checkin) {
14963                        if (!printedHeader) {
14964                            if (dumpState.onTitlePrinted())
14965                                pw.println();
14966                            pw.println("Libraries:");
14967                            printedHeader = true;
14968                        }
14969                        pw.print("  ");
14970                    } else {
14971                        pw.print("lib,");
14972                    }
14973                    pw.print(name);
14974                    if (!checkin) {
14975                        pw.print(" -> ");
14976                    }
14977                    if (ent.path != null) {
14978                        if (!checkin) {
14979                            pw.print("(jar) ");
14980                            pw.print(ent.path);
14981                        } else {
14982                            pw.print(",jar,");
14983                            pw.print(ent.path);
14984                        }
14985                    } else {
14986                        if (!checkin) {
14987                            pw.print("(apk) ");
14988                            pw.print(ent.apk);
14989                        } else {
14990                            pw.print(",apk,");
14991                            pw.print(ent.apk);
14992                        }
14993                    }
14994                    pw.println();
14995                }
14996            }
14997
14998            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14999                if (dumpState.onTitlePrinted())
15000                    pw.println();
15001                if (!checkin) {
15002                    pw.println("Features:");
15003                }
15004                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15005                while (it.hasNext()) {
15006                    String name = it.next();
15007                    if (!checkin) {
15008                        pw.print("  ");
15009                    } else {
15010                        pw.print("feat,");
15011                    }
15012                    pw.println(name);
15013                }
15014            }
15015
15016            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15017                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15018                        : "Activity Resolver Table:", "  ", packageName,
15019                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15020                    dumpState.setTitlePrinted(true);
15021                }
15022                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15023                        : "Receiver Resolver Table:", "  ", packageName,
15024                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15025                    dumpState.setTitlePrinted(true);
15026                }
15027                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15028                        : "Service Resolver Table:", "  ", packageName,
15029                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15030                    dumpState.setTitlePrinted(true);
15031                }
15032                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15033                        : "Provider Resolver Table:", "  ", packageName,
15034                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15035                    dumpState.setTitlePrinted(true);
15036                }
15037            }
15038
15039            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15040                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15041                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15042                    int user = mSettings.mPreferredActivities.keyAt(i);
15043                    if (pir.dump(pw,
15044                            dumpState.getTitlePrinted()
15045                                ? "\nPreferred Activities User " + user + ":"
15046                                : "Preferred Activities User " + user + ":", "  ",
15047                            packageName, true, false)) {
15048                        dumpState.setTitlePrinted(true);
15049                    }
15050                }
15051            }
15052
15053            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15054                pw.flush();
15055                FileOutputStream fout = new FileOutputStream(fd);
15056                BufferedOutputStream str = new BufferedOutputStream(fout);
15057                XmlSerializer serializer = new FastXmlSerializer();
15058                try {
15059                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15060                    serializer.startDocument(null, true);
15061                    serializer.setFeature(
15062                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15063                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15064                    serializer.endDocument();
15065                    serializer.flush();
15066                } catch (IllegalArgumentException e) {
15067                    pw.println("Failed writing: " + e);
15068                } catch (IllegalStateException e) {
15069                    pw.println("Failed writing: " + e);
15070                } catch (IOException e) {
15071                    pw.println("Failed writing: " + e);
15072                }
15073            }
15074
15075            if (!checkin
15076                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15077                    && packageName == null) {
15078                pw.println();
15079                int count = mSettings.mPackages.size();
15080                if (count == 0) {
15081                    pw.println("No applications!");
15082                    pw.println();
15083                } else {
15084                    final String prefix = "  ";
15085                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15086                    if (allPackageSettings.size() == 0) {
15087                        pw.println("No domain preferred apps!");
15088                        pw.println();
15089                    } else {
15090                        pw.println("App verification status:");
15091                        pw.println();
15092                        count = 0;
15093                        for (PackageSetting ps : allPackageSettings) {
15094                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15095                            if (ivi == null || ivi.getPackageName() == null) continue;
15096                            pw.println(prefix + "Package: " + ivi.getPackageName());
15097                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15098                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15099                            pw.println();
15100                            count++;
15101                        }
15102                        if (count == 0) {
15103                            pw.println(prefix + "No app verification established.");
15104                            pw.println();
15105                        }
15106                        for (int userId : sUserManager.getUserIds()) {
15107                            pw.println("App linkages for user " + userId + ":");
15108                            pw.println();
15109                            count = 0;
15110                            for (PackageSetting ps : allPackageSettings) {
15111                                final long status = ps.getDomainVerificationStatusForUser(userId);
15112                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15113                                    continue;
15114                                }
15115                                pw.println(prefix + "Package: " + ps.name);
15116                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15117                                String statusStr = IntentFilterVerificationInfo.
15118                                        getStatusStringFromValue(status);
15119                                pw.println(prefix + "Status:  " + statusStr);
15120                                pw.println();
15121                                count++;
15122                            }
15123                            if (count == 0) {
15124                                pw.println(prefix + "No configured app linkages.");
15125                                pw.println();
15126                            }
15127                        }
15128                    }
15129                }
15130            }
15131
15132            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15133                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15134                if (packageName == null && permissionNames == null) {
15135                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15136                        if (iperm == 0) {
15137                            if (dumpState.onTitlePrinted())
15138                                pw.println();
15139                            pw.println("AppOp Permissions:");
15140                        }
15141                        pw.print("  AppOp Permission ");
15142                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15143                        pw.println(":");
15144                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15145                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15146                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15147                        }
15148                    }
15149                }
15150            }
15151
15152            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15153                boolean printedSomething = false;
15154                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15155                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15156                        continue;
15157                    }
15158                    if (!printedSomething) {
15159                        if (dumpState.onTitlePrinted())
15160                            pw.println();
15161                        pw.println("Registered ContentProviders:");
15162                        printedSomething = true;
15163                    }
15164                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15165                    pw.print("    "); pw.println(p.toString());
15166                }
15167                printedSomething = false;
15168                for (Map.Entry<String, PackageParser.Provider> entry :
15169                        mProvidersByAuthority.entrySet()) {
15170                    PackageParser.Provider p = entry.getValue();
15171                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15172                        continue;
15173                    }
15174                    if (!printedSomething) {
15175                        if (dumpState.onTitlePrinted())
15176                            pw.println();
15177                        pw.println("ContentProvider Authorities:");
15178                        printedSomething = true;
15179                    }
15180                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15181                    pw.print("    "); pw.println(p.toString());
15182                    if (p.info != null && p.info.applicationInfo != null) {
15183                        final String appInfo = p.info.applicationInfo.toString();
15184                        pw.print("      applicationInfo="); pw.println(appInfo);
15185                    }
15186                }
15187            }
15188
15189            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15190                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15191            }
15192
15193            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15194                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15195            }
15196
15197            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15198                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15199            }
15200
15201            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15202                // XXX should handle packageName != null by dumping only install data that
15203                // the given package is involved with.
15204                if (dumpState.onTitlePrinted()) pw.println();
15205                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15206            }
15207
15208            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15209                if (dumpState.onTitlePrinted()) pw.println();
15210                mSettings.dumpReadMessagesLPr(pw, dumpState);
15211
15212                pw.println();
15213                pw.println("Package warning messages:");
15214                BufferedReader in = null;
15215                String line = null;
15216                try {
15217                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15218                    while ((line = in.readLine()) != null) {
15219                        if (line.contains("ignored: updated version")) continue;
15220                        pw.println(line);
15221                    }
15222                } catch (IOException ignored) {
15223                } finally {
15224                    IoUtils.closeQuietly(in);
15225                }
15226            }
15227
15228            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15229                BufferedReader in = null;
15230                String line = null;
15231                try {
15232                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15233                    while ((line = in.readLine()) != null) {
15234                        if (line.contains("ignored: updated version")) continue;
15235                        pw.print("msg,");
15236                        pw.println(line);
15237                    }
15238                } catch (IOException ignored) {
15239                } finally {
15240                    IoUtils.closeQuietly(in);
15241                }
15242            }
15243        }
15244    }
15245
15246    private String dumpDomainString(String packageName) {
15247        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15248        List<IntentFilter> filters = getAllIntentFilters(packageName);
15249
15250        ArraySet<String> result = new ArraySet<>();
15251        if (iviList.size() > 0) {
15252            for (IntentFilterVerificationInfo ivi : iviList) {
15253                for (String host : ivi.getDomains()) {
15254                    result.add(host);
15255                }
15256            }
15257        }
15258        if (filters != null && filters.size() > 0) {
15259            for (IntentFilter filter : filters) {
15260                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15261                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15262                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15263                    result.addAll(filter.getHostsList());
15264                }
15265            }
15266        }
15267
15268        StringBuilder sb = new StringBuilder(result.size() * 16);
15269        for (String domain : result) {
15270            if (sb.length() > 0) sb.append(" ");
15271            sb.append(domain);
15272        }
15273        return sb.toString();
15274    }
15275
15276    // ------- apps on sdcard specific code -------
15277    static final boolean DEBUG_SD_INSTALL = false;
15278
15279    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15280
15281    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15282
15283    private boolean mMediaMounted = false;
15284
15285    static String getEncryptKey() {
15286        try {
15287            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15288                    SD_ENCRYPTION_KEYSTORE_NAME);
15289            if (sdEncKey == null) {
15290                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15291                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15292                if (sdEncKey == null) {
15293                    Slog.e(TAG, "Failed to create encryption keys");
15294                    return null;
15295                }
15296            }
15297            return sdEncKey;
15298        } catch (NoSuchAlgorithmException nsae) {
15299            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15300            return null;
15301        } catch (IOException ioe) {
15302            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15303            return null;
15304        }
15305    }
15306
15307    /*
15308     * Update media status on PackageManager.
15309     */
15310    @Override
15311    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15312        int callingUid = Binder.getCallingUid();
15313        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15314            throw new SecurityException("Media status can only be updated by the system");
15315        }
15316        // reader; this apparently protects mMediaMounted, but should probably
15317        // be a different lock in that case.
15318        synchronized (mPackages) {
15319            Log.i(TAG, "Updating external media status from "
15320                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15321                    + (mediaStatus ? "mounted" : "unmounted"));
15322            if (DEBUG_SD_INSTALL)
15323                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15324                        + ", mMediaMounted=" + mMediaMounted);
15325            if (mediaStatus == mMediaMounted) {
15326                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15327                        : 0, -1);
15328                mHandler.sendMessage(msg);
15329                return;
15330            }
15331            mMediaMounted = mediaStatus;
15332        }
15333        // Queue up an async operation since the package installation may take a
15334        // little while.
15335        mHandler.post(new Runnable() {
15336            public void run() {
15337                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15338            }
15339        });
15340    }
15341
15342    /**
15343     * Called by MountService when the initial ASECs to scan are available.
15344     * Should block until all the ASEC containers are finished being scanned.
15345     */
15346    public void scanAvailableAsecs() {
15347        updateExternalMediaStatusInner(true, false, false);
15348        if (mShouldRestoreconData) {
15349            SELinuxMMAC.setRestoreconDone();
15350            mShouldRestoreconData = false;
15351        }
15352    }
15353
15354    /*
15355     * Collect information of applications on external media, map them against
15356     * existing containers and update information based on current mount status.
15357     * Please note that we always have to report status if reportStatus has been
15358     * set to true especially when unloading packages.
15359     */
15360    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15361            boolean externalStorage) {
15362        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15363        int[] uidArr = EmptyArray.INT;
15364
15365        final String[] list = PackageHelper.getSecureContainerList();
15366        if (ArrayUtils.isEmpty(list)) {
15367            Log.i(TAG, "No secure containers found");
15368        } else {
15369            // Process list of secure containers and categorize them
15370            // as active or stale based on their package internal state.
15371
15372            // reader
15373            synchronized (mPackages) {
15374                for (String cid : list) {
15375                    // Leave stages untouched for now; installer service owns them
15376                    if (PackageInstallerService.isStageName(cid)) continue;
15377
15378                    if (DEBUG_SD_INSTALL)
15379                        Log.i(TAG, "Processing container " + cid);
15380                    String pkgName = getAsecPackageName(cid);
15381                    if (pkgName == null) {
15382                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15383                        continue;
15384                    }
15385                    if (DEBUG_SD_INSTALL)
15386                        Log.i(TAG, "Looking for pkg : " + pkgName);
15387
15388                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15389                    if (ps == null) {
15390                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15391                        continue;
15392                    }
15393
15394                    /*
15395                     * Skip packages that are not external if we're unmounting
15396                     * external storage.
15397                     */
15398                    if (externalStorage && !isMounted && !isExternal(ps)) {
15399                        continue;
15400                    }
15401
15402                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15403                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15404                    // The package status is changed only if the code path
15405                    // matches between settings and the container id.
15406                    if (ps.codePathString != null
15407                            && ps.codePathString.startsWith(args.getCodePath())) {
15408                        if (DEBUG_SD_INSTALL) {
15409                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15410                                    + " at code path: " + ps.codePathString);
15411                        }
15412
15413                        // We do have a valid package installed on sdcard
15414                        processCids.put(args, ps.codePathString);
15415                        final int uid = ps.appId;
15416                        if (uid != -1) {
15417                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15418                        }
15419                    } else {
15420                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15421                                + ps.codePathString);
15422                    }
15423                }
15424            }
15425
15426            Arrays.sort(uidArr);
15427        }
15428
15429        // Process packages with valid entries.
15430        if (isMounted) {
15431            if (DEBUG_SD_INSTALL)
15432                Log.i(TAG, "Loading packages");
15433            loadMediaPackages(processCids, uidArr);
15434            startCleaningPackages();
15435            mInstallerService.onSecureContainersAvailable();
15436        } else {
15437            if (DEBUG_SD_INSTALL)
15438                Log.i(TAG, "Unloading packages");
15439            unloadMediaPackages(processCids, uidArr, reportStatus);
15440        }
15441    }
15442
15443    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15444            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15445        final int size = infos.size();
15446        final String[] packageNames = new String[size];
15447        final int[] packageUids = new int[size];
15448        for (int i = 0; i < size; i++) {
15449            final ApplicationInfo info = infos.get(i);
15450            packageNames[i] = info.packageName;
15451            packageUids[i] = info.uid;
15452        }
15453        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15454                finishedReceiver);
15455    }
15456
15457    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15458            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15459        sendResourcesChangedBroadcast(mediaStatus, replacing,
15460                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15461    }
15462
15463    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15464            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15465        int size = pkgList.length;
15466        if (size > 0) {
15467            // Send broadcasts here
15468            Bundle extras = new Bundle();
15469            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15470            if (uidArr != null) {
15471                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15472            }
15473            if (replacing) {
15474                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15475            }
15476            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15477                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15478            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15479        }
15480    }
15481
15482   /*
15483     * Look at potentially valid container ids from processCids If package
15484     * information doesn't match the one on record or package scanning fails,
15485     * the cid is added to list of removeCids. We currently don't delete stale
15486     * containers.
15487     */
15488    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15489        ArrayList<String> pkgList = new ArrayList<String>();
15490        Set<AsecInstallArgs> keys = processCids.keySet();
15491
15492        for (AsecInstallArgs args : keys) {
15493            String codePath = processCids.get(args);
15494            if (DEBUG_SD_INSTALL)
15495                Log.i(TAG, "Loading container : " + args.cid);
15496            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15497            try {
15498                // Make sure there are no container errors first.
15499                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15500                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15501                            + " when installing from sdcard");
15502                    continue;
15503                }
15504                // Check code path here.
15505                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15506                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15507                            + " does not match one in settings " + codePath);
15508                    continue;
15509                }
15510                // Parse package
15511                int parseFlags = mDefParseFlags;
15512                if (args.isExternalAsec()) {
15513                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15514                }
15515                if (args.isFwdLocked()) {
15516                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15517                }
15518
15519                synchronized (mInstallLock) {
15520                    PackageParser.Package pkg = null;
15521                    try {
15522                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15523                    } catch (PackageManagerException e) {
15524                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15525                    }
15526                    // Scan the package
15527                    if (pkg != null) {
15528                        /*
15529                         * TODO why is the lock being held? doPostInstall is
15530                         * called in other places without the lock. This needs
15531                         * to be straightened out.
15532                         */
15533                        // writer
15534                        synchronized (mPackages) {
15535                            retCode = PackageManager.INSTALL_SUCCEEDED;
15536                            pkgList.add(pkg.packageName);
15537                            // Post process args
15538                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15539                                    pkg.applicationInfo.uid);
15540                        }
15541                    } else {
15542                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15543                    }
15544                }
15545
15546            } finally {
15547                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15548                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15549                }
15550            }
15551        }
15552        // writer
15553        synchronized (mPackages) {
15554            // If the platform SDK has changed since the last time we booted,
15555            // we need to re-grant app permission to catch any new ones that
15556            // appear. This is really a hack, and means that apps can in some
15557            // cases get permissions that the user didn't initially explicitly
15558            // allow... it would be nice to have some better way to handle
15559            // this situation.
15560            final VersionInfo ver = mSettings.getExternalVersion();
15561
15562            int updateFlags = UPDATE_PERMISSIONS_ALL;
15563            if (ver.sdkVersion != mSdkVersion) {
15564                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15565                        + mSdkVersion + "; regranting permissions for external");
15566                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15567            }
15568            updatePermissionsLPw(null, null, updateFlags);
15569
15570            // Yay, everything is now upgraded
15571            ver.forceCurrent();
15572
15573            // can downgrade to reader
15574            // Persist settings
15575            mSettings.writeLPr();
15576        }
15577        // Send a broadcast to let everyone know we are done processing
15578        if (pkgList.size() > 0) {
15579            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15580        }
15581    }
15582
15583   /*
15584     * Utility method to unload a list of specified containers
15585     */
15586    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15587        // Just unmount all valid containers.
15588        for (AsecInstallArgs arg : cidArgs) {
15589            synchronized (mInstallLock) {
15590                arg.doPostDeleteLI(false);
15591           }
15592       }
15593   }
15594
15595    /*
15596     * Unload packages mounted on external media. This involves deleting package
15597     * data from internal structures, sending broadcasts about diabled packages,
15598     * gc'ing to free up references, unmounting all secure containers
15599     * corresponding to packages on external media, and posting a
15600     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15601     * that we always have to post this message if status has been requested no
15602     * matter what.
15603     */
15604    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15605            final boolean reportStatus) {
15606        if (DEBUG_SD_INSTALL)
15607            Log.i(TAG, "unloading media packages");
15608        ArrayList<String> pkgList = new ArrayList<String>();
15609        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15610        final Set<AsecInstallArgs> keys = processCids.keySet();
15611        for (AsecInstallArgs args : keys) {
15612            String pkgName = args.getPackageName();
15613            if (DEBUG_SD_INSTALL)
15614                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15615            // Delete package internally
15616            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15617            synchronized (mInstallLock) {
15618                boolean res = deletePackageLI(pkgName, null, false, null, null,
15619                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15620                if (res) {
15621                    pkgList.add(pkgName);
15622                } else {
15623                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15624                    failedList.add(args);
15625                }
15626            }
15627        }
15628
15629        // reader
15630        synchronized (mPackages) {
15631            // We didn't update the settings after removing each package;
15632            // write them now for all packages.
15633            mSettings.writeLPr();
15634        }
15635
15636        // We have to absolutely send UPDATED_MEDIA_STATUS only
15637        // after confirming that all the receivers processed the ordered
15638        // broadcast when packages get disabled, force a gc to clean things up.
15639        // and unload all the containers.
15640        if (pkgList.size() > 0) {
15641            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15642                    new IIntentReceiver.Stub() {
15643                public void performReceive(Intent intent, int resultCode, String data,
15644                        Bundle extras, boolean ordered, boolean sticky,
15645                        int sendingUser) throws RemoteException {
15646                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15647                            reportStatus ? 1 : 0, 1, keys);
15648                    mHandler.sendMessage(msg);
15649                }
15650            });
15651        } else {
15652            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15653                    keys);
15654            mHandler.sendMessage(msg);
15655        }
15656    }
15657
15658    private void loadPrivatePackages(final VolumeInfo vol) {
15659        mHandler.post(new Runnable() {
15660            @Override
15661            public void run() {
15662                loadPrivatePackagesInner(vol);
15663            }
15664        });
15665    }
15666
15667    private void loadPrivatePackagesInner(VolumeInfo vol) {
15668        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15669        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15670
15671        final VersionInfo ver;
15672        final List<PackageSetting> packages;
15673        synchronized (mPackages) {
15674            ver = mSettings.findOrCreateVersion(vol.fsUuid);
15675            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15676        }
15677
15678        for (PackageSetting ps : packages) {
15679            synchronized (mInstallLock) {
15680                final PackageParser.Package pkg;
15681                try {
15682                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15683                    loaded.add(pkg.applicationInfo);
15684                } catch (PackageManagerException e) {
15685                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15686                }
15687
15688                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15689                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15690                }
15691            }
15692        }
15693
15694        synchronized (mPackages) {
15695            int updateFlags = UPDATE_PERMISSIONS_ALL;
15696            if (ver.sdkVersion != mSdkVersion) {
15697                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15698                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15699                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15700            }
15701            updatePermissionsLPw(null, null, updateFlags);
15702
15703            // Yay, everything is now upgraded
15704            ver.forceCurrent();
15705
15706            mSettings.writeLPr();
15707        }
15708
15709        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15710        sendResourcesChangedBroadcast(true, false, loaded, null);
15711    }
15712
15713    private void unloadPrivatePackages(final VolumeInfo vol) {
15714        mHandler.post(new Runnable() {
15715            @Override
15716            public void run() {
15717                unloadPrivatePackagesInner(vol);
15718            }
15719        });
15720    }
15721
15722    private void unloadPrivatePackagesInner(VolumeInfo vol) {
15723        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15724        synchronized (mInstallLock) {
15725        synchronized (mPackages) {
15726            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15727            for (PackageSetting ps : packages) {
15728                if (ps.pkg == null) continue;
15729
15730                final ApplicationInfo info = ps.pkg.applicationInfo;
15731                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15732                if (deletePackageLI(ps.name, null, false, null, null,
15733                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15734                    unloaded.add(info);
15735                } else {
15736                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15737                }
15738            }
15739
15740            mSettings.writeLPr();
15741        }
15742        }
15743
15744        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15745        sendResourcesChangedBroadcast(false, false, unloaded, null);
15746    }
15747
15748    /**
15749     * Examine all users present on given mounted volume, and destroy data
15750     * belonging to users that are no longer valid, or whose user ID has been
15751     * recycled.
15752     */
15753    private void reconcileUsers(String volumeUuid) {
15754        final File[] files = FileUtils
15755                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15756        for (File file : files) {
15757            if (!file.isDirectory()) continue;
15758
15759            final int userId;
15760            final UserInfo info;
15761            try {
15762                userId = Integer.parseInt(file.getName());
15763                info = sUserManager.getUserInfo(userId);
15764            } catch (NumberFormatException e) {
15765                Slog.w(TAG, "Invalid user directory " + file);
15766                continue;
15767            }
15768
15769            boolean destroyUser = false;
15770            if (info == null) {
15771                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15772                        + " because no matching user was found");
15773                destroyUser = true;
15774            } else {
15775                try {
15776                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15777                } catch (IOException e) {
15778                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15779                            + " because we failed to enforce serial number: " + e);
15780                    destroyUser = true;
15781                }
15782            }
15783
15784            if (destroyUser) {
15785                synchronized (mInstallLock) {
15786                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15787                }
15788            }
15789        }
15790
15791        final UserManager um = mContext.getSystemService(UserManager.class);
15792        for (UserInfo user : um.getUsers()) {
15793            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15794            if (userDir.exists()) continue;
15795
15796            try {
15797                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15798                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15799            } catch (IOException e) {
15800                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15801            }
15802        }
15803    }
15804
15805    /**
15806     * Examine all apps present on given mounted volume, and destroy apps that
15807     * aren't expected, either due to uninstallation or reinstallation on
15808     * another volume.
15809     */
15810    private void reconcileApps(String volumeUuid) {
15811        final File[] files = FileUtils
15812                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15813        for (File file : files) {
15814            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15815                    && !PackageInstallerService.isStageName(file.getName());
15816            if (!isPackage) {
15817                // Ignore entries which are not packages
15818                continue;
15819            }
15820
15821            boolean destroyApp = false;
15822            String packageName = null;
15823            try {
15824                final PackageLite pkg = PackageParser.parsePackageLite(file,
15825                        PackageParser.PARSE_MUST_BE_APK);
15826                packageName = pkg.packageName;
15827
15828                synchronized (mPackages) {
15829                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15830                    if (ps == null) {
15831                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15832                                + volumeUuid + " because we found no install record");
15833                        destroyApp = true;
15834                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15835                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15836                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15837                        destroyApp = true;
15838                    }
15839                }
15840
15841            } catch (PackageParserException e) {
15842                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15843                destroyApp = true;
15844            }
15845
15846            if (destroyApp) {
15847                synchronized (mInstallLock) {
15848                    if (packageName != null) {
15849                        removeDataDirsLI(volumeUuid, packageName);
15850                    }
15851                    if (file.isDirectory()) {
15852                        mInstaller.rmPackageDir(file.getAbsolutePath());
15853                    } else {
15854                        file.delete();
15855                    }
15856                }
15857            }
15858        }
15859    }
15860
15861    private void unfreezePackage(String packageName) {
15862        synchronized (mPackages) {
15863            final PackageSetting ps = mSettings.mPackages.get(packageName);
15864            if (ps != null) {
15865                ps.frozen = false;
15866            }
15867        }
15868    }
15869
15870    @Override
15871    public int movePackage(final String packageName, final String volumeUuid) {
15872        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15873
15874        final int moveId = mNextMoveId.getAndIncrement();
15875        try {
15876            movePackageInternal(packageName, volumeUuid, moveId);
15877        } catch (PackageManagerException e) {
15878            Slog.w(TAG, "Failed to move " + packageName, e);
15879            mMoveCallbacks.notifyStatusChanged(moveId,
15880                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15881        }
15882        return moveId;
15883    }
15884
15885    private void movePackageInternal(final String packageName, final String volumeUuid,
15886            final int moveId) throws PackageManagerException {
15887        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15888        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15889        final PackageManager pm = mContext.getPackageManager();
15890
15891        final boolean currentAsec;
15892        final String currentVolumeUuid;
15893        final File codeFile;
15894        final String installerPackageName;
15895        final String packageAbiOverride;
15896        final int appId;
15897        final String seinfo;
15898        final String label;
15899
15900        // reader
15901        synchronized (mPackages) {
15902            final PackageParser.Package pkg = mPackages.get(packageName);
15903            final PackageSetting ps = mSettings.mPackages.get(packageName);
15904            if (pkg == null || ps == null) {
15905                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15906            }
15907
15908            if (pkg.applicationInfo.isSystemApp()) {
15909                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15910                        "Cannot move system application");
15911            }
15912
15913            if (pkg.applicationInfo.isExternalAsec()) {
15914                currentAsec = true;
15915                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
15916            } else if (pkg.applicationInfo.isForwardLocked()) {
15917                currentAsec = true;
15918                currentVolumeUuid = "forward_locked";
15919            } else {
15920                currentAsec = false;
15921                currentVolumeUuid = ps.volumeUuid;
15922
15923                final File probe = new File(pkg.codePath);
15924                final File probeOat = new File(probe, "oat");
15925                if (!probe.isDirectory() || !probeOat.isDirectory()) {
15926                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15927                            "Move only supported for modern cluster style installs");
15928                }
15929            }
15930
15931            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
15932                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15933                        "Package already moved to " + volumeUuid);
15934            }
15935
15936            if (ps.frozen) {
15937                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15938                        "Failed to move already frozen package");
15939            }
15940            ps.frozen = true;
15941
15942            codeFile = new File(pkg.codePath);
15943            installerPackageName = ps.installerPackageName;
15944            packageAbiOverride = ps.cpuAbiOverrideString;
15945            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15946            seinfo = pkg.applicationInfo.seinfo;
15947            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15948        }
15949
15950        // Now that we're guarded by frozen state, kill app during move
15951        final long token = Binder.clearCallingIdentity();
15952        try {
15953            killApplication(packageName, appId, "move pkg");
15954        } finally {
15955            Binder.restoreCallingIdentity(token);
15956        }
15957
15958        final Bundle extras = new Bundle();
15959        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15960        extras.putString(Intent.EXTRA_TITLE, label);
15961        mMoveCallbacks.notifyCreated(moveId, extras);
15962
15963        int installFlags;
15964        final boolean moveCompleteApp;
15965        final File measurePath;
15966
15967        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15968            installFlags = INSTALL_INTERNAL;
15969            moveCompleteApp = !currentAsec;
15970            measurePath = Environment.getDataAppDirectory(volumeUuid);
15971        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15972            installFlags = INSTALL_EXTERNAL;
15973            moveCompleteApp = false;
15974            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15975        } else {
15976            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15977            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15978                    || !volume.isMountedWritable()) {
15979                unfreezePackage(packageName);
15980                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15981                        "Move location not mounted private volume");
15982            }
15983
15984            Preconditions.checkState(!currentAsec);
15985
15986            installFlags = INSTALL_INTERNAL;
15987            moveCompleteApp = true;
15988            measurePath = Environment.getDataAppDirectory(volumeUuid);
15989        }
15990
15991        final PackageStats stats = new PackageStats(null, -1);
15992        synchronized (mInstaller) {
15993            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15994                unfreezePackage(packageName);
15995                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15996                        "Failed to measure package size");
15997            }
15998        }
15999
16000        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16001                + stats.dataSize);
16002
16003        final long startFreeBytes = measurePath.getFreeSpace();
16004        final long sizeBytes;
16005        if (moveCompleteApp) {
16006            sizeBytes = stats.codeSize + stats.dataSize;
16007        } else {
16008            sizeBytes = stats.codeSize;
16009        }
16010
16011        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16012            unfreezePackage(packageName);
16013            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16014                    "Not enough free space to move");
16015        }
16016
16017        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16018
16019        final CountDownLatch installedLatch = new CountDownLatch(1);
16020        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16021            @Override
16022            public void onUserActionRequired(Intent intent) throws RemoteException {
16023                throw new IllegalStateException();
16024            }
16025
16026            @Override
16027            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16028                    Bundle extras) throws RemoteException {
16029                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16030                        + PackageManager.installStatusToString(returnCode, msg));
16031
16032                installedLatch.countDown();
16033
16034                // Regardless of success or failure of the move operation,
16035                // always unfreeze the package
16036                unfreezePackage(packageName);
16037
16038                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16039                switch (status) {
16040                    case PackageInstaller.STATUS_SUCCESS:
16041                        mMoveCallbacks.notifyStatusChanged(moveId,
16042                                PackageManager.MOVE_SUCCEEDED);
16043                        break;
16044                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16045                        mMoveCallbacks.notifyStatusChanged(moveId,
16046                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16047                        break;
16048                    default:
16049                        mMoveCallbacks.notifyStatusChanged(moveId,
16050                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16051                        break;
16052                }
16053            }
16054        };
16055
16056        final MoveInfo move;
16057        if (moveCompleteApp) {
16058            // Kick off a thread to report progress estimates
16059            new Thread() {
16060                @Override
16061                public void run() {
16062                    while (true) {
16063                        try {
16064                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16065                                break;
16066                            }
16067                        } catch (InterruptedException ignored) {
16068                        }
16069
16070                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16071                        final int progress = 10 + (int) MathUtils.constrain(
16072                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16073                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16074                    }
16075                }
16076            }.start();
16077
16078            final String dataAppName = codeFile.getName();
16079            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16080                    dataAppName, appId, seinfo);
16081        } else {
16082            move = null;
16083        }
16084
16085        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16086
16087        final Message msg = mHandler.obtainMessage(INIT_COPY);
16088        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16089        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
16090                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16091        mHandler.sendMessage(msg);
16092    }
16093
16094    @Override
16095    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16096        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16097
16098        final int realMoveId = mNextMoveId.getAndIncrement();
16099        final Bundle extras = new Bundle();
16100        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16101        mMoveCallbacks.notifyCreated(realMoveId, extras);
16102
16103        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16104            @Override
16105            public void onCreated(int moveId, Bundle extras) {
16106                // Ignored
16107            }
16108
16109            @Override
16110            public void onStatusChanged(int moveId, int status, long estMillis) {
16111                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16112            }
16113        };
16114
16115        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16116        storage.setPrimaryStorageUuid(volumeUuid, callback);
16117        return realMoveId;
16118    }
16119
16120    @Override
16121    public int getMoveStatus(int moveId) {
16122        mContext.enforceCallingOrSelfPermission(
16123                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16124        return mMoveCallbacks.mLastStatus.get(moveId);
16125    }
16126
16127    @Override
16128    public void registerMoveCallback(IPackageMoveObserver callback) {
16129        mContext.enforceCallingOrSelfPermission(
16130                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16131        mMoveCallbacks.register(callback);
16132    }
16133
16134    @Override
16135    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16136        mContext.enforceCallingOrSelfPermission(
16137                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16138        mMoveCallbacks.unregister(callback);
16139    }
16140
16141    @Override
16142    public boolean setInstallLocation(int loc) {
16143        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16144                null);
16145        if (getInstallLocation() == loc) {
16146            return true;
16147        }
16148        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16149                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16150            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16151                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16152            return true;
16153        }
16154        return false;
16155   }
16156
16157    @Override
16158    public int getInstallLocation() {
16159        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16160                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16161                PackageHelper.APP_INSTALL_AUTO);
16162    }
16163
16164    /** Called by UserManagerService */
16165    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16166        mDirtyUsers.remove(userHandle);
16167        mSettings.removeUserLPw(userHandle);
16168        mPendingBroadcasts.remove(userHandle);
16169        if (mInstaller != null) {
16170            // Technically, we shouldn't be doing this with the package lock
16171            // held.  However, this is very rare, and there is already so much
16172            // other disk I/O going on, that we'll let it slide for now.
16173            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16174            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16175                final String volumeUuid = vol.getFsUuid();
16176                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16177                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16178            }
16179        }
16180        mUserNeedsBadging.delete(userHandle);
16181        removeUnusedPackagesLILPw(userManager, userHandle);
16182    }
16183
16184    /**
16185     * We're removing userHandle and would like to remove any downloaded packages
16186     * that are no longer in use by any other user.
16187     * @param userHandle the user being removed
16188     */
16189    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16190        final boolean DEBUG_CLEAN_APKS = false;
16191        int [] users = userManager.getUserIdsLPr();
16192        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16193        while (psit.hasNext()) {
16194            PackageSetting ps = psit.next();
16195            if (ps.pkg == null) {
16196                continue;
16197            }
16198            final String packageName = ps.pkg.packageName;
16199            // Skip over if system app
16200            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16201                continue;
16202            }
16203            if (DEBUG_CLEAN_APKS) {
16204                Slog.i(TAG, "Checking package " + packageName);
16205            }
16206            boolean keep = false;
16207            for (int i = 0; i < users.length; i++) {
16208                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16209                    keep = true;
16210                    if (DEBUG_CLEAN_APKS) {
16211                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16212                                + users[i]);
16213                    }
16214                    break;
16215                }
16216            }
16217            if (!keep) {
16218                if (DEBUG_CLEAN_APKS) {
16219                    Slog.i(TAG, "  Removing package " + packageName);
16220                }
16221                mHandler.post(new Runnable() {
16222                    public void run() {
16223                        deletePackageX(packageName, userHandle, 0);
16224                    } //end run
16225                });
16226            }
16227        }
16228    }
16229
16230    /** Called by UserManagerService */
16231    void createNewUserLILPw(int userHandle) {
16232        if (mInstaller != null) {
16233            mInstaller.createUserConfig(userHandle);
16234            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16235            applyFactoryDefaultBrowserLPw(userHandle);
16236            primeDomainVerificationsLPw(userHandle);
16237        }
16238    }
16239
16240    void newUserCreated(final int userHandle) {
16241        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16242    }
16243
16244    @Override
16245    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16246        mContext.enforceCallingOrSelfPermission(
16247                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16248                "Only package verification agents can read the verifier device identity");
16249
16250        synchronized (mPackages) {
16251            return mSettings.getVerifierDeviceIdentityLPw();
16252        }
16253    }
16254
16255    @Override
16256    public void setPermissionEnforced(String permission, boolean enforced) {
16257        // TODO: Now that we no longer change GID for storage, this should to away.
16258        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16259                "setPermissionEnforced");
16260        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16261            synchronized (mPackages) {
16262                if (mSettings.mReadExternalStorageEnforced == null
16263                        || mSettings.mReadExternalStorageEnforced != enforced) {
16264                    mSettings.mReadExternalStorageEnforced = enforced;
16265                    mSettings.writeLPr();
16266                }
16267            }
16268            // kill any non-foreground processes so we restart them and
16269            // grant/revoke the GID.
16270            final IActivityManager am = ActivityManagerNative.getDefault();
16271            if (am != null) {
16272                final long token = Binder.clearCallingIdentity();
16273                try {
16274                    am.killProcessesBelowForeground("setPermissionEnforcement");
16275                } catch (RemoteException e) {
16276                } finally {
16277                    Binder.restoreCallingIdentity(token);
16278                }
16279            }
16280        } else {
16281            throw new IllegalArgumentException("No selective enforcement for " + permission);
16282        }
16283    }
16284
16285    @Override
16286    @Deprecated
16287    public boolean isPermissionEnforced(String permission) {
16288        return true;
16289    }
16290
16291    @Override
16292    public boolean isStorageLow() {
16293        final long token = Binder.clearCallingIdentity();
16294        try {
16295            final DeviceStorageMonitorInternal
16296                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16297            if (dsm != null) {
16298                return dsm.isMemoryLow();
16299            } else {
16300                return false;
16301            }
16302        } finally {
16303            Binder.restoreCallingIdentity(token);
16304        }
16305    }
16306
16307    @Override
16308    public IPackageInstaller getPackageInstaller() {
16309        return mInstallerService;
16310    }
16311
16312    private boolean userNeedsBadging(int userId) {
16313        int index = mUserNeedsBadging.indexOfKey(userId);
16314        if (index < 0) {
16315            final UserInfo userInfo;
16316            final long token = Binder.clearCallingIdentity();
16317            try {
16318                userInfo = sUserManager.getUserInfo(userId);
16319            } finally {
16320                Binder.restoreCallingIdentity(token);
16321            }
16322            final boolean b;
16323            if (userInfo != null && userInfo.isManagedProfile()) {
16324                b = true;
16325            } else {
16326                b = false;
16327            }
16328            mUserNeedsBadging.put(userId, b);
16329            return b;
16330        }
16331        return mUserNeedsBadging.valueAt(index);
16332    }
16333
16334    @Override
16335    public KeySet getKeySetByAlias(String packageName, String alias) {
16336        if (packageName == null || alias == null) {
16337            return null;
16338        }
16339        synchronized(mPackages) {
16340            final PackageParser.Package pkg = mPackages.get(packageName);
16341            if (pkg == null) {
16342                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16343                throw new IllegalArgumentException("Unknown package: " + packageName);
16344            }
16345            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16346            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16347        }
16348    }
16349
16350    @Override
16351    public KeySet getSigningKeySet(String packageName) {
16352        if (packageName == null) {
16353            return null;
16354        }
16355        synchronized(mPackages) {
16356            final PackageParser.Package pkg = mPackages.get(packageName);
16357            if (pkg == null) {
16358                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16359                throw new IllegalArgumentException("Unknown package: " + packageName);
16360            }
16361            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16362                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16363                throw new SecurityException("May not access signing KeySet of other apps.");
16364            }
16365            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16366            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16367        }
16368    }
16369
16370    @Override
16371    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16372        if (packageName == null || ks == null) {
16373            return false;
16374        }
16375        synchronized(mPackages) {
16376            final PackageParser.Package pkg = mPackages.get(packageName);
16377            if (pkg == null) {
16378                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16379                throw new IllegalArgumentException("Unknown package: " + packageName);
16380            }
16381            IBinder ksh = ks.getToken();
16382            if (ksh instanceof KeySetHandle) {
16383                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16384                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16385            }
16386            return false;
16387        }
16388    }
16389
16390    @Override
16391    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16392        if (packageName == null || ks == null) {
16393            return false;
16394        }
16395        synchronized(mPackages) {
16396            final PackageParser.Package pkg = mPackages.get(packageName);
16397            if (pkg == null) {
16398                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16399                throw new IllegalArgumentException("Unknown package: " + packageName);
16400            }
16401            IBinder ksh = ks.getToken();
16402            if (ksh instanceof KeySetHandle) {
16403                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16404                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16405            }
16406            return false;
16407        }
16408    }
16409
16410    public void getUsageStatsIfNoPackageUsageInfo() {
16411        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16412            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16413            if (usm == null) {
16414                throw new IllegalStateException("UsageStatsManager must be initialized");
16415            }
16416            long now = System.currentTimeMillis();
16417            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16418            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16419                String packageName = entry.getKey();
16420                PackageParser.Package pkg = mPackages.get(packageName);
16421                if (pkg == null) {
16422                    continue;
16423                }
16424                UsageStats usage = entry.getValue();
16425                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16426                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16427            }
16428        }
16429    }
16430
16431    /**
16432     * Check and throw if the given before/after packages would be considered a
16433     * downgrade.
16434     */
16435    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16436            throws PackageManagerException {
16437        if (after.versionCode < before.mVersionCode) {
16438            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16439                    "Update version code " + after.versionCode + " is older than current "
16440                    + before.mVersionCode);
16441        } else if (after.versionCode == before.mVersionCode) {
16442            if (after.baseRevisionCode < before.baseRevisionCode) {
16443                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16444                        "Update base revision code " + after.baseRevisionCode
16445                        + " is older than current " + before.baseRevisionCode);
16446            }
16447
16448            if (!ArrayUtils.isEmpty(after.splitNames)) {
16449                for (int i = 0; i < after.splitNames.length; i++) {
16450                    final String splitName = after.splitNames[i];
16451                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16452                    if (j != -1) {
16453                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16454                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16455                                    "Update split " + splitName + " revision code "
16456                                    + after.splitRevisionCodes[i] + " is older than current "
16457                                    + before.splitRevisionCodes[j]);
16458                        }
16459                    }
16460                }
16461            }
16462        }
16463    }
16464
16465    private static class MoveCallbacks extends Handler {
16466        private static final int MSG_CREATED = 1;
16467        private static final int MSG_STATUS_CHANGED = 2;
16468
16469        private final RemoteCallbackList<IPackageMoveObserver>
16470                mCallbacks = new RemoteCallbackList<>();
16471
16472        private final SparseIntArray mLastStatus = new SparseIntArray();
16473
16474        public MoveCallbacks(Looper looper) {
16475            super(looper);
16476        }
16477
16478        public void register(IPackageMoveObserver callback) {
16479            mCallbacks.register(callback);
16480        }
16481
16482        public void unregister(IPackageMoveObserver callback) {
16483            mCallbacks.unregister(callback);
16484        }
16485
16486        @Override
16487        public void handleMessage(Message msg) {
16488            final SomeArgs args = (SomeArgs) msg.obj;
16489            final int n = mCallbacks.beginBroadcast();
16490            for (int i = 0; i < n; i++) {
16491                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16492                try {
16493                    invokeCallback(callback, msg.what, args);
16494                } catch (RemoteException ignored) {
16495                }
16496            }
16497            mCallbacks.finishBroadcast();
16498            args.recycle();
16499        }
16500
16501        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16502                throws RemoteException {
16503            switch (what) {
16504                case MSG_CREATED: {
16505                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16506                    break;
16507                }
16508                case MSG_STATUS_CHANGED: {
16509                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16510                    break;
16511                }
16512            }
16513        }
16514
16515        private void notifyCreated(int moveId, Bundle extras) {
16516            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16517
16518            final SomeArgs args = SomeArgs.obtain();
16519            args.argi1 = moveId;
16520            args.arg2 = extras;
16521            obtainMessage(MSG_CREATED, args).sendToTarget();
16522        }
16523
16524        private void notifyStatusChanged(int moveId, int status) {
16525            notifyStatusChanged(moveId, status, -1);
16526        }
16527
16528        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16529            Slog.v(TAG, "Move " + moveId + " status " + status);
16530
16531            final SomeArgs args = SomeArgs.obtain();
16532            args.argi1 = moveId;
16533            args.argi2 = status;
16534            args.arg3 = estMillis;
16535            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16536
16537            synchronized (mLastStatus) {
16538                mLastStatus.put(moveId, status);
16539            }
16540        }
16541    }
16542
16543    private final class OnPermissionChangeListeners extends Handler {
16544        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16545
16546        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16547                new RemoteCallbackList<>();
16548
16549        public OnPermissionChangeListeners(Looper looper) {
16550            super(looper);
16551        }
16552
16553        @Override
16554        public void handleMessage(Message msg) {
16555            switch (msg.what) {
16556                case MSG_ON_PERMISSIONS_CHANGED: {
16557                    final int uid = msg.arg1;
16558                    handleOnPermissionsChanged(uid);
16559                } break;
16560            }
16561        }
16562
16563        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16564            mPermissionListeners.register(listener);
16565
16566        }
16567
16568        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16569            mPermissionListeners.unregister(listener);
16570        }
16571
16572        public void onPermissionsChanged(int uid) {
16573            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16574                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16575            }
16576        }
16577
16578        private void handleOnPermissionsChanged(int uid) {
16579            final int count = mPermissionListeners.beginBroadcast();
16580            try {
16581                for (int i = 0; i < count; i++) {
16582                    IOnPermissionsChangeListener callback = mPermissionListeners
16583                            .getBroadcastItem(i);
16584                    try {
16585                        callback.onPermissionsChanged(uid);
16586                    } catch (RemoteException e) {
16587                        Log.e(TAG, "Permission listener is dead", e);
16588                    }
16589                }
16590            } finally {
16591                mPermissionListeners.finishBroadcast();
16592            }
16593        }
16594    }
16595
16596    private class PackageManagerInternalImpl extends PackageManagerInternal {
16597        @Override
16598        public void setLocationPackagesProvider(PackagesProvider provider) {
16599            synchronized (mPackages) {
16600                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16601            }
16602        }
16603
16604        @Override
16605        public void setImePackagesProvider(PackagesProvider provider) {
16606            synchronized (mPackages) {
16607                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16608            }
16609        }
16610
16611        @Override
16612        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16613            synchronized (mPackages) {
16614                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16615            }
16616        }
16617
16618        @Override
16619        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16620            synchronized (mPackages) {
16621                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16622            }
16623        }
16624
16625        @Override
16626        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16627            synchronized (mPackages) {
16628                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16629            }
16630        }
16631
16632        @Override
16633        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16634            synchronized (mPackages) {
16635                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16636            }
16637        }
16638
16639        @Override
16640        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16641            synchronized (mPackages) {
16642                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16643            }
16644        }
16645
16646        @Override
16647        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16648            synchronized (mPackages) {
16649                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16650                        packageName, userId);
16651            }
16652        }
16653
16654        @Override
16655        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16656            synchronized (mPackages) {
16657                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16658                        packageName, userId);
16659            }
16660        }
16661        @Override
16662        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16663            synchronized (mPackages) {
16664                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16665                        packageName, userId);
16666            }
16667        }
16668    }
16669
16670    @Override
16671    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16672        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16673        synchronized (mPackages) {
16674            final long identity = Binder.clearCallingIdentity();
16675            try {
16676                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16677                        packageNames, userId);
16678            } finally {
16679                Binder.restoreCallingIdentity(identity);
16680            }
16681        }
16682    }
16683
16684    private static void enforceSystemOrPhoneCaller(String tag) {
16685        int callingUid = Binder.getCallingUid();
16686        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16687            throw new SecurityException(
16688                    "Cannot call " + tag + " from UID " + callingUid);
16689        }
16690    }
16691}
16692