PackageManagerService.java revision e1be56cdfff431985ffd931bdd7c001e4c87478d
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, StorageManager.UUID_PRIVATE_INTERNAL, 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            } else {
4779                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4780                result.addAll(undefinedList);
4781                // Maybe add one for the other profile.
4782                if (xpDomainInfo != null && (
4783                        xpDomainInfo.bestDomainVerificationStatus
4784                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
4785                    result.add(xpDomainInfo.resolveInfo);
4786                }
4787                includeBrowser = true;
4788            }
4789
4790            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4791            // If there were 'always' entries their preferred order has been set, so we also
4792            // back that off to make the alternatives equivalent
4793            if (alwaysAskList.size() > 0) {
4794                for (ResolveInfo i : result) {
4795                    i.preferredOrder = 0;
4796                }
4797                result.addAll(alwaysAskList);
4798                includeBrowser = true;
4799            }
4800
4801            if (includeBrowser) {
4802                // Also add browsers (all of them or only the default one)
4803                if (DEBUG_DOMAIN_VERIFICATION) {
4804                    Slog.v(TAG, "   ...including browsers in candidate set");
4805                }
4806                if ((matchFlags & MATCH_ALL) != 0) {
4807                    result.addAll(matchAllList);
4808                } else {
4809                    // Browser/generic handling case.  If there's a default browser, go straight
4810                    // to that (but only if there is no other higher-priority match).
4811                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4812                    int maxMatchPrio = 0;
4813                    ResolveInfo defaultBrowserMatch = null;
4814                    final int numCandidates = matchAllList.size();
4815                    for (int n = 0; n < numCandidates; n++) {
4816                        ResolveInfo info = matchAllList.get(n);
4817                        // track the highest overall match priority...
4818                        if (info.priority > maxMatchPrio) {
4819                            maxMatchPrio = info.priority;
4820                        }
4821                        // ...and the highest-priority default browser match
4822                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4823                            if (defaultBrowserMatch == null
4824                                    || (defaultBrowserMatch.priority < info.priority)) {
4825                                if (debug) {
4826                                    Slog.v(TAG, "Considering default browser match " + info);
4827                                }
4828                                defaultBrowserMatch = info;
4829                            }
4830                        }
4831                    }
4832                    if (defaultBrowserMatch != null
4833                            && defaultBrowserMatch.priority >= maxMatchPrio
4834                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4835                    {
4836                        if (debug) {
4837                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4838                        }
4839                        result.add(defaultBrowserMatch);
4840                    } else {
4841                        result.addAll(matchAllList);
4842                    }
4843                }
4844
4845                // If there is nothing selected, add all candidates and remove the ones that the user
4846                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4847                if (result.size() == 0) {
4848                    result.addAll(candidates);
4849                    result.removeAll(neverList);
4850                }
4851            }
4852        }
4853        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4854            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4855                    result.size());
4856            for (ResolveInfo info : result) {
4857                Slog.v(TAG, "  + " + info.activityInfo);
4858            }
4859        }
4860        return result;
4861    }
4862
4863    // Returns a packed value as a long:
4864    //
4865    // high 'int'-sized word: link status: undefined/ask/never/always.
4866    // low 'int'-sized word: relative priority among 'always' results.
4867    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4868        long result = ps.getDomainVerificationStatusForUser(userId);
4869        // if none available, get the master status
4870        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4871            if (ps.getIntentFilterVerificationInfo() != null) {
4872                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4873            }
4874        }
4875        return result;
4876    }
4877
4878    private ResolveInfo querySkipCurrentProfileIntents(
4879            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4880            int flags, int sourceUserId) {
4881        if (matchingFilters != null) {
4882            int size = matchingFilters.size();
4883            for (int i = 0; i < size; i ++) {
4884                CrossProfileIntentFilter filter = matchingFilters.get(i);
4885                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4886                    // Checking if there are activities in the target user that can handle the
4887                    // intent.
4888                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4889                            flags, sourceUserId);
4890                    if (resolveInfo != null) {
4891                        return resolveInfo;
4892                    }
4893                }
4894            }
4895        }
4896        return null;
4897    }
4898
4899    // Return matching ResolveInfo if any for skip current profile intent filters.
4900    private ResolveInfo queryCrossProfileIntents(
4901            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4902            int flags, int sourceUserId) {
4903        if (matchingFilters != null) {
4904            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4905            // match the same intent. For performance reasons, it is better not to
4906            // run queryIntent twice for the same userId
4907            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4908            int size = matchingFilters.size();
4909            for (int i = 0; i < size; i++) {
4910                CrossProfileIntentFilter filter = matchingFilters.get(i);
4911                int targetUserId = filter.getTargetUserId();
4912                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4913                        && !alreadyTriedUserIds.get(targetUserId)) {
4914                    // Checking if there are activities in the target user that can handle the
4915                    // intent.
4916                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4917                            flags, sourceUserId);
4918                    if (resolveInfo != null) return resolveInfo;
4919                    alreadyTriedUserIds.put(targetUserId, true);
4920                }
4921            }
4922        }
4923        return null;
4924    }
4925
4926    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4927            String resolvedType, int flags, int sourceUserId) {
4928        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4929                resolvedType, flags, filter.getTargetUserId());
4930        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4931            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4932        }
4933        return null;
4934    }
4935
4936    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4937            int sourceUserId, int targetUserId) {
4938        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4939        String className;
4940        if (targetUserId == UserHandle.USER_OWNER) {
4941            className = FORWARD_INTENT_TO_USER_OWNER;
4942        } else {
4943            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4944        }
4945        ComponentName forwardingActivityComponentName = new ComponentName(
4946                mAndroidApplication.packageName, className);
4947        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4948                sourceUserId);
4949        if (targetUserId == UserHandle.USER_OWNER) {
4950            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4951            forwardingResolveInfo.noResourceId = true;
4952        }
4953        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4954        forwardingResolveInfo.priority = 0;
4955        forwardingResolveInfo.preferredOrder = 0;
4956        forwardingResolveInfo.match = 0;
4957        forwardingResolveInfo.isDefault = true;
4958        forwardingResolveInfo.filter = filter;
4959        forwardingResolveInfo.targetUserId = targetUserId;
4960        return forwardingResolveInfo;
4961    }
4962
4963    @Override
4964    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4965            Intent[] specifics, String[] specificTypes, Intent intent,
4966            String resolvedType, int flags, int userId) {
4967        if (!sUserManager.exists(userId)) return Collections.emptyList();
4968        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4969                false, "query intent activity options");
4970        final String resultsAction = intent.getAction();
4971
4972        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4973                | PackageManager.GET_RESOLVED_FILTER, userId);
4974
4975        if (DEBUG_INTENT_MATCHING) {
4976            Log.v(TAG, "Query " + intent + ": " + results);
4977        }
4978
4979        int specificsPos = 0;
4980        int N;
4981
4982        // todo: note that the algorithm used here is O(N^2).  This
4983        // isn't a problem in our current environment, but if we start running
4984        // into situations where we have more than 5 or 10 matches then this
4985        // should probably be changed to something smarter...
4986
4987        // First we go through and resolve each of the specific items
4988        // that were supplied, taking care of removing any corresponding
4989        // duplicate items in the generic resolve list.
4990        if (specifics != null) {
4991            for (int i=0; i<specifics.length; i++) {
4992                final Intent sintent = specifics[i];
4993                if (sintent == null) {
4994                    continue;
4995                }
4996
4997                if (DEBUG_INTENT_MATCHING) {
4998                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4999                }
5000
5001                String action = sintent.getAction();
5002                if (resultsAction != null && resultsAction.equals(action)) {
5003                    // If this action was explicitly requested, then don't
5004                    // remove things that have it.
5005                    action = null;
5006                }
5007
5008                ResolveInfo ri = null;
5009                ActivityInfo ai = null;
5010
5011                ComponentName comp = sintent.getComponent();
5012                if (comp == null) {
5013                    ri = resolveIntent(
5014                        sintent,
5015                        specificTypes != null ? specificTypes[i] : null,
5016                            flags, userId);
5017                    if (ri == null) {
5018                        continue;
5019                    }
5020                    if (ri == mResolveInfo) {
5021                        // ACK!  Must do something better with this.
5022                    }
5023                    ai = ri.activityInfo;
5024                    comp = new ComponentName(ai.applicationInfo.packageName,
5025                            ai.name);
5026                } else {
5027                    ai = getActivityInfo(comp, flags, userId);
5028                    if (ai == null) {
5029                        continue;
5030                    }
5031                }
5032
5033                // Look for any generic query activities that are duplicates
5034                // of this specific one, and remove them from the results.
5035                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5036                N = results.size();
5037                int j;
5038                for (j=specificsPos; j<N; j++) {
5039                    ResolveInfo sri = results.get(j);
5040                    if ((sri.activityInfo.name.equals(comp.getClassName())
5041                            && sri.activityInfo.applicationInfo.packageName.equals(
5042                                    comp.getPackageName()))
5043                        || (action != null && sri.filter.matchAction(action))) {
5044                        results.remove(j);
5045                        if (DEBUG_INTENT_MATCHING) Log.v(
5046                            TAG, "Removing duplicate item from " + j
5047                            + " due to specific " + specificsPos);
5048                        if (ri == null) {
5049                            ri = sri;
5050                        }
5051                        j--;
5052                        N--;
5053                    }
5054                }
5055
5056                // Add this specific item to its proper place.
5057                if (ri == null) {
5058                    ri = new ResolveInfo();
5059                    ri.activityInfo = ai;
5060                }
5061                results.add(specificsPos, ri);
5062                ri.specificIndex = i;
5063                specificsPos++;
5064            }
5065        }
5066
5067        // Now we go through the remaining generic results and remove any
5068        // duplicate actions that are found here.
5069        N = results.size();
5070        for (int i=specificsPos; i<N-1; i++) {
5071            final ResolveInfo rii = results.get(i);
5072            if (rii.filter == null) {
5073                continue;
5074            }
5075
5076            // Iterate over all of the actions of this result's intent
5077            // filter...  typically this should be just one.
5078            final Iterator<String> it = rii.filter.actionsIterator();
5079            if (it == null) {
5080                continue;
5081            }
5082            while (it.hasNext()) {
5083                final String action = it.next();
5084                if (resultsAction != null && resultsAction.equals(action)) {
5085                    // If this action was explicitly requested, then don't
5086                    // remove things that have it.
5087                    continue;
5088                }
5089                for (int j=i+1; j<N; j++) {
5090                    final ResolveInfo rij = results.get(j);
5091                    if (rij.filter != null && rij.filter.hasAction(action)) {
5092                        results.remove(j);
5093                        if (DEBUG_INTENT_MATCHING) Log.v(
5094                            TAG, "Removing duplicate item from " + j
5095                            + " due to action " + action + " at " + i);
5096                        j--;
5097                        N--;
5098                    }
5099                }
5100            }
5101
5102            // If the caller didn't request filter information, drop it now
5103            // so we don't have to marshall/unmarshall it.
5104            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5105                rii.filter = null;
5106            }
5107        }
5108
5109        // Filter out the caller activity if so requested.
5110        if (caller != null) {
5111            N = results.size();
5112            for (int i=0; i<N; i++) {
5113                ActivityInfo ainfo = results.get(i).activityInfo;
5114                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5115                        && caller.getClassName().equals(ainfo.name)) {
5116                    results.remove(i);
5117                    break;
5118                }
5119            }
5120        }
5121
5122        // If the caller didn't request filter information,
5123        // drop them now so we don't have to
5124        // marshall/unmarshall it.
5125        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5126            N = results.size();
5127            for (int i=0; i<N; i++) {
5128                results.get(i).filter = null;
5129            }
5130        }
5131
5132        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5133        return results;
5134    }
5135
5136    @Override
5137    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5138            int userId) {
5139        if (!sUserManager.exists(userId)) return Collections.emptyList();
5140        ComponentName comp = intent.getComponent();
5141        if (comp == null) {
5142            if (intent.getSelector() != null) {
5143                intent = intent.getSelector();
5144                comp = intent.getComponent();
5145            }
5146        }
5147        if (comp != null) {
5148            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5149            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5150            if (ai != null) {
5151                ResolveInfo ri = new ResolveInfo();
5152                ri.activityInfo = ai;
5153                list.add(ri);
5154            }
5155            return list;
5156        }
5157
5158        // reader
5159        synchronized (mPackages) {
5160            String pkgName = intent.getPackage();
5161            if (pkgName == null) {
5162                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5163            }
5164            final PackageParser.Package pkg = mPackages.get(pkgName);
5165            if (pkg != null) {
5166                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5167                        userId);
5168            }
5169            return null;
5170        }
5171    }
5172
5173    @Override
5174    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5175        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5176        if (!sUserManager.exists(userId)) return null;
5177        if (query != null) {
5178            if (query.size() >= 1) {
5179                // If there is more than one service with the same priority,
5180                // just arbitrarily pick the first one.
5181                return query.get(0);
5182            }
5183        }
5184        return null;
5185    }
5186
5187    @Override
5188    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5189            int userId) {
5190        if (!sUserManager.exists(userId)) return Collections.emptyList();
5191        ComponentName comp = intent.getComponent();
5192        if (comp == null) {
5193            if (intent.getSelector() != null) {
5194                intent = intent.getSelector();
5195                comp = intent.getComponent();
5196            }
5197        }
5198        if (comp != null) {
5199            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5200            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5201            if (si != null) {
5202                final ResolveInfo ri = new ResolveInfo();
5203                ri.serviceInfo = si;
5204                list.add(ri);
5205            }
5206            return list;
5207        }
5208
5209        // reader
5210        synchronized (mPackages) {
5211            String pkgName = intent.getPackage();
5212            if (pkgName == null) {
5213                return mServices.queryIntent(intent, resolvedType, flags, userId);
5214            }
5215            final PackageParser.Package pkg = mPackages.get(pkgName);
5216            if (pkg != null) {
5217                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5218                        userId);
5219            }
5220            return null;
5221        }
5222    }
5223
5224    @Override
5225    public List<ResolveInfo> queryIntentContentProviders(
5226            Intent intent, String resolvedType, int flags, int userId) {
5227        if (!sUserManager.exists(userId)) return Collections.emptyList();
5228        ComponentName comp = intent.getComponent();
5229        if (comp == null) {
5230            if (intent.getSelector() != null) {
5231                intent = intent.getSelector();
5232                comp = intent.getComponent();
5233            }
5234        }
5235        if (comp != null) {
5236            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5237            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5238            if (pi != null) {
5239                final ResolveInfo ri = new ResolveInfo();
5240                ri.providerInfo = pi;
5241                list.add(ri);
5242            }
5243            return list;
5244        }
5245
5246        // reader
5247        synchronized (mPackages) {
5248            String pkgName = intent.getPackage();
5249            if (pkgName == null) {
5250                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5251            }
5252            final PackageParser.Package pkg = mPackages.get(pkgName);
5253            if (pkg != null) {
5254                return mProviders.queryIntentForPackage(
5255                        intent, resolvedType, flags, pkg.providers, userId);
5256            }
5257            return null;
5258        }
5259    }
5260
5261    @Override
5262    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5263        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5264
5265        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5266
5267        // writer
5268        synchronized (mPackages) {
5269            ArrayList<PackageInfo> list;
5270            if (listUninstalled) {
5271                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5272                for (PackageSetting ps : mSettings.mPackages.values()) {
5273                    PackageInfo pi;
5274                    if (ps.pkg != null) {
5275                        pi = generatePackageInfo(ps.pkg, flags, userId);
5276                    } else {
5277                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5278                    }
5279                    if (pi != null) {
5280                        list.add(pi);
5281                    }
5282                }
5283            } else {
5284                list = new ArrayList<PackageInfo>(mPackages.size());
5285                for (PackageParser.Package p : mPackages.values()) {
5286                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5287                    if (pi != null) {
5288                        list.add(pi);
5289                    }
5290                }
5291            }
5292
5293            return new ParceledListSlice<PackageInfo>(list);
5294        }
5295    }
5296
5297    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5298            String[] permissions, boolean[] tmp, int flags, int userId) {
5299        int numMatch = 0;
5300        final PermissionsState permissionsState = ps.getPermissionsState();
5301        for (int i=0; i<permissions.length; i++) {
5302            final String permission = permissions[i];
5303            if (permissionsState.hasPermission(permission, userId)) {
5304                tmp[i] = true;
5305                numMatch++;
5306            } else {
5307                tmp[i] = false;
5308            }
5309        }
5310        if (numMatch == 0) {
5311            return;
5312        }
5313        PackageInfo pi;
5314        if (ps.pkg != null) {
5315            pi = generatePackageInfo(ps.pkg, flags, userId);
5316        } else {
5317            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5318        }
5319        // The above might return null in cases of uninstalled apps or install-state
5320        // skew across users/profiles.
5321        if (pi != null) {
5322            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5323                if (numMatch == permissions.length) {
5324                    pi.requestedPermissions = permissions;
5325                } else {
5326                    pi.requestedPermissions = new String[numMatch];
5327                    numMatch = 0;
5328                    for (int i=0; i<permissions.length; i++) {
5329                        if (tmp[i]) {
5330                            pi.requestedPermissions[numMatch] = permissions[i];
5331                            numMatch++;
5332                        }
5333                    }
5334                }
5335            }
5336            list.add(pi);
5337        }
5338    }
5339
5340    @Override
5341    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5342            String[] permissions, int flags, int userId) {
5343        if (!sUserManager.exists(userId)) return null;
5344        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5345
5346        // writer
5347        synchronized (mPackages) {
5348            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5349            boolean[] tmpBools = new boolean[permissions.length];
5350            if (listUninstalled) {
5351                for (PackageSetting ps : mSettings.mPackages.values()) {
5352                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5353                }
5354            } else {
5355                for (PackageParser.Package pkg : mPackages.values()) {
5356                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5357                    if (ps != null) {
5358                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5359                                userId);
5360                    }
5361                }
5362            }
5363
5364            return new ParceledListSlice<PackageInfo>(list);
5365        }
5366    }
5367
5368    @Override
5369    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5370        if (!sUserManager.exists(userId)) return null;
5371        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5372
5373        // writer
5374        synchronized (mPackages) {
5375            ArrayList<ApplicationInfo> list;
5376            if (listUninstalled) {
5377                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5378                for (PackageSetting ps : mSettings.mPackages.values()) {
5379                    ApplicationInfo ai;
5380                    if (ps.pkg != null) {
5381                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5382                                ps.readUserState(userId), userId);
5383                    } else {
5384                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5385                    }
5386                    if (ai != null) {
5387                        list.add(ai);
5388                    }
5389                }
5390            } else {
5391                list = new ArrayList<ApplicationInfo>(mPackages.size());
5392                for (PackageParser.Package p : mPackages.values()) {
5393                    if (p.mExtras != null) {
5394                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5395                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5396                        if (ai != null) {
5397                            list.add(ai);
5398                        }
5399                    }
5400                }
5401            }
5402
5403            return new ParceledListSlice<ApplicationInfo>(list);
5404        }
5405    }
5406
5407    public List<ApplicationInfo> getPersistentApplications(int flags) {
5408        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5409
5410        // reader
5411        synchronized (mPackages) {
5412            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5413            final int userId = UserHandle.getCallingUserId();
5414            while (i.hasNext()) {
5415                final PackageParser.Package p = i.next();
5416                if (p.applicationInfo != null
5417                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5418                        && (!mSafeMode || isSystemApp(p))) {
5419                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5420                    if (ps != null) {
5421                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5422                                ps.readUserState(userId), userId);
5423                        if (ai != null) {
5424                            finalList.add(ai);
5425                        }
5426                    }
5427                }
5428            }
5429        }
5430
5431        return finalList;
5432    }
5433
5434    @Override
5435    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5436        if (!sUserManager.exists(userId)) return null;
5437        // reader
5438        synchronized (mPackages) {
5439            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5440            PackageSetting ps = provider != null
5441                    ? mSettings.mPackages.get(provider.owner.packageName)
5442                    : null;
5443            return ps != null
5444                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5445                    && (!mSafeMode || (provider.info.applicationInfo.flags
5446                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5447                    ? PackageParser.generateProviderInfo(provider, flags,
5448                            ps.readUserState(userId), userId)
5449                    : null;
5450        }
5451    }
5452
5453    /**
5454     * @deprecated
5455     */
5456    @Deprecated
5457    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5458        // reader
5459        synchronized (mPackages) {
5460            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5461                    .entrySet().iterator();
5462            final int userId = UserHandle.getCallingUserId();
5463            while (i.hasNext()) {
5464                Map.Entry<String, PackageParser.Provider> entry = i.next();
5465                PackageParser.Provider p = entry.getValue();
5466                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5467
5468                if (ps != null && p.syncable
5469                        && (!mSafeMode || (p.info.applicationInfo.flags
5470                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5471                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5472                            ps.readUserState(userId), userId);
5473                    if (info != null) {
5474                        outNames.add(entry.getKey());
5475                        outInfo.add(info);
5476                    }
5477                }
5478            }
5479        }
5480    }
5481
5482    @Override
5483    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5484            int uid, int flags) {
5485        ArrayList<ProviderInfo> finalList = null;
5486        // reader
5487        synchronized (mPackages) {
5488            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5489            final int userId = processName != null ?
5490                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5491            while (i.hasNext()) {
5492                final PackageParser.Provider p = i.next();
5493                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5494                if (ps != null && p.info.authority != null
5495                        && (processName == null
5496                                || (p.info.processName.equals(processName)
5497                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5498                        && mSettings.isEnabledLPr(p.info, flags, userId)
5499                        && (!mSafeMode
5500                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5501                    if (finalList == null) {
5502                        finalList = new ArrayList<ProviderInfo>(3);
5503                    }
5504                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5505                            ps.readUserState(userId), userId);
5506                    if (info != null) {
5507                        finalList.add(info);
5508                    }
5509                }
5510            }
5511        }
5512
5513        if (finalList != null) {
5514            Collections.sort(finalList, mProviderInitOrderSorter);
5515            return new ParceledListSlice<ProviderInfo>(finalList);
5516        }
5517
5518        return null;
5519    }
5520
5521    @Override
5522    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5523            int flags) {
5524        // reader
5525        synchronized (mPackages) {
5526            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5527            return PackageParser.generateInstrumentationInfo(i, flags);
5528        }
5529    }
5530
5531    @Override
5532    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5533            int flags) {
5534        ArrayList<InstrumentationInfo> finalList =
5535            new ArrayList<InstrumentationInfo>();
5536
5537        // reader
5538        synchronized (mPackages) {
5539            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5540            while (i.hasNext()) {
5541                final PackageParser.Instrumentation p = i.next();
5542                if (targetPackage == null
5543                        || targetPackage.equals(p.info.targetPackage)) {
5544                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5545                            flags);
5546                    if (ii != null) {
5547                        finalList.add(ii);
5548                    }
5549                }
5550            }
5551        }
5552
5553        return finalList;
5554    }
5555
5556    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5557        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5558        if (overlays == null) {
5559            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5560            return;
5561        }
5562        for (PackageParser.Package opkg : overlays.values()) {
5563            // Not much to do if idmap fails: we already logged the error
5564            // and we certainly don't want to abort installation of pkg simply
5565            // because an overlay didn't fit properly. For these reasons,
5566            // ignore the return value of createIdmapForPackagePairLI.
5567            createIdmapForPackagePairLI(pkg, opkg);
5568        }
5569    }
5570
5571    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5572            PackageParser.Package opkg) {
5573        if (!opkg.mTrustedOverlay) {
5574            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5575                    opkg.baseCodePath + ": overlay not trusted");
5576            return false;
5577        }
5578        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5579        if (overlaySet == null) {
5580            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5581                    opkg.baseCodePath + " but target package has no known overlays");
5582            return false;
5583        }
5584        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5585        // TODO: generate idmap for split APKs
5586        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5587            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5588                    + opkg.baseCodePath);
5589            return false;
5590        }
5591        PackageParser.Package[] overlayArray =
5592            overlaySet.values().toArray(new PackageParser.Package[0]);
5593        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5594            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5595                return p1.mOverlayPriority - p2.mOverlayPriority;
5596            }
5597        };
5598        Arrays.sort(overlayArray, cmp);
5599
5600        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5601        int i = 0;
5602        for (PackageParser.Package p : overlayArray) {
5603            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5604        }
5605        return true;
5606    }
5607
5608    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5609        final File[] files = dir.listFiles();
5610        if (ArrayUtils.isEmpty(files)) {
5611            Log.d(TAG, "No files in app dir " + dir);
5612            return;
5613        }
5614
5615        if (DEBUG_PACKAGE_SCANNING) {
5616            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5617                    + " flags=0x" + Integer.toHexString(parseFlags));
5618        }
5619
5620        for (File file : files) {
5621            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5622                    && !PackageInstallerService.isStageName(file.getName());
5623            if (!isPackage) {
5624                // Ignore entries which are not packages
5625                continue;
5626            }
5627            try {
5628                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5629                        scanFlags, currentTime, null);
5630            } catch (PackageManagerException e) {
5631                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5632
5633                // Delete invalid userdata apps
5634                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5635                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5636                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5637                    if (file.isDirectory()) {
5638                        mInstaller.rmPackageDir(file.getAbsolutePath());
5639                    } else {
5640                        file.delete();
5641                    }
5642                }
5643            }
5644        }
5645    }
5646
5647    private static File getSettingsProblemFile() {
5648        File dataDir = Environment.getDataDirectory();
5649        File systemDir = new File(dataDir, "system");
5650        File fname = new File(systemDir, "uiderrors.txt");
5651        return fname;
5652    }
5653
5654    static void reportSettingsProblem(int priority, String msg) {
5655        logCriticalInfo(priority, msg);
5656    }
5657
5658    static void logCriticalInfo(int priority, String msg) {
5659        Slog.println(priority, TAG, msg);
5660        EventLogTags.writePmCriticalInfo(msg);
5661        try {
5662            File fname = getSettingsProblemFile();
5663            FileOutputStream out = new FileOutputStream(fname, true);
5664            PrintWriter pw = new FastPrintWriter(out);
5665            SimpleDateFormat formatter = new SimpleDateFormat();
5666            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5667            pw.println(dateString + ": " + msg);
5668            pw.close();
5669            FileUtils.setPermissions(
5670                    fname.toString(),
5671                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5672                    -1, -1);
5673        } catch (java.io.IOException e) {
5674        }
5675    }
5676
5677    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5678            PackageParser.Package pkg, File srcFile, int parseFlags)
5679            throws PackageManagerException {
5680        if (ps != null
5681                && ps.codePath.equals(srcFile)
5682                && ps.timeStamp == srcFile.lastModified()
5683                && !isCompatSignatureUpdateNeeded(pkg)
5684                && !isRecoverSignatureUpdateNeeded(pkg)) {
5685            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5686            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5687            ArraySet<PublicKey> signingKs;
5688            synchronized (mPackages) {
5689                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5690            }
5691            if (ps.signatures.mSignatures != null
5692                    && ps.signatures.mSignatures.length != 0
5693                    && signingKs != null) {
5694                // Optimization: reuse the existing cached certificates
5695                // if the package appears to be unchanged.
5696                pkg.mSignatures = ps.signatures.mSignatures;
5697                pkg.mSigningKeys = signingKs;
5698                return;
5699            }
5700
5701            Slog.w(TAG, "PackageSetting for " + ps.name
5702                    + " is missing signatures.  Collecting certs again to recover them.");
5703        } else {
5704            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5705        }
5706
5707        try {
5708            pp.collectCertificates(pkg, parseFlags);
5709            pp.collectManifestDigest(pkg);
5710        } catch (PackageParserException e) {
5711            throw PackageManagerException.from(e);
5712        }
5713    }
5714
5715    /*
5716     *  Scan a package and return the newly parsed package.
5717     *  Returns null in case of errors and the error code is stored in mLastScanError
5718     */
5719    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5720            long currentTime, UserHandle user) throws PackageManagerException {
5721        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5722        parseFlags |= mDefParseFlags;
5723        PackageParser pp = new PackageParser();
5724        pp.setSeparateProcesses(mSeparateProcesses);
5725        pp.setOnlyCoreApps(mOnlyCore);
5726        pp.setDisplayMetrics(mMetrics);
5727
5728        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5729            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5730        }
5731
5732        final PackageParser.Package pkg;
5733        try {
5734            pkg = pp.parsePackage(scanFile, parseFlags);
5735        } catch (PackageParserException e) {
5736            throw PackageManagerException.from(e);
5737        }
5738
5739        PackageSetting ps = null;
5740        PackageSetting updatedPkg;
5741        // reader
5742        synchronized (mPackages) {
5743            // Look to see if we already know about this package.
5744            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5745            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5746                // This package has been renamed to its original name.  Let's
5747                // use that.
5748                ps = mSettings.peekPackageLPr(oldName);
5749            }
5750            // If there was no original package, see one for the real package name.
5751            if (ps == null) {
5752                ps = mSettings.peekPackageLPr(pkg.packageName);
5753            }
5754            // Check to see if this package could be hiding/updating a system
5755            // package.  Must look for it either under the original or real
5756            // package name depending on our state.
5757            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5758            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5759        }
5760        boolean updatedPkgBetter = false;
5761        // First check if this is a system package that may involve an update
5762        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5763            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5764            // it needs to drop FLAG_PRIVILEGED.
5765            if (locationIsPrivileged(scanFile)) {
5766                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5767            } else {
5768                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5769            }
5770
5771            if (ps != null && !ps.codePath.equals(scanFile)) {
5772                // The path has changed from what was last scanned...  check the
5773                // version of the new path against what we have stored to determine
5774                // what to do.
5775                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5776                if (pkg.mVersionCode <= ps.versionCode) {
5777                    // The system package has been updated and the code path does not match
5778                    // Ignore entry. Skip it.
5779                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5780                            + " ignored: updated version " + ps.versionCode
5781                            + " better than this " + pkg.mVersionCode);
5782                    if (!updatedPkg.codePath.equals(scanFile)) {
5783                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5784                                + ps.name + " changing from " + updatedPkg.codePathString
5785                                + " to " + scanFile);
5786                        updatedPkg.codePath = scanFile;
5787                        updatedPkg.codePathString = scanFile.toString();
5788                        updatedPkg.resourcePath = scanFile;
5789                        updatedPkg.resourcePathString = scanFile.toString();
5790                    }
5791                    updatedPkg.pkg = pkg;
5792                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5793                            "Package " + ps.name + " at " + scanFile
5794                                    + " ignored: updated version " + ps.versionCode
5795                                    + " better than this " + pkg.mVersionCode);
5796                } else {
5797                    // The current app on the system partition is better than
5798                    // what we have updated to on the data partition; switch
5799                    // back to the system partition version.
5800                    // At this point, its safely assumed that package installation for
5801                    // apps in system partition will go through. If not there won't be a working
5802                    // version of the app
5803                    // writer
5804                    synchronized (mPackages) {
5805                        // Just remove the loaded entries from package lists.
5806                        mPackages.remove(ps.name);
5807                    }
5808
5809                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5810                            + " reverting from " + ps.codePathString
5811                            + ": new version " + pkg.mVersionCode
5812                            + " better than installed " + ps.versionCode);
5813
5814                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5815                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5816                    synchronized (mInstallLock) {
5817                        args.cleanUpResourcesLI();
5818                    }
5819                    synchronized (mPackages) {
5820                        mSettings.enableSystemPackageLPw(ps.name);
5821                    }
5822                    updatedPkgBetter = true;
5823                }
5824            }
5825        }
5826
5827        if (updatedPkg != null) {
5828            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5829            // initially
5830            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5831
5832            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5833            // flag set initially
5834            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5835                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5836            }
5837        }
5838
5839        // Verify certificates against what was last scanned
5840        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5841
5842        /*
5843         * A new system app appeared, but we already had a non-system one of the
5844         * same name installed earlier.
5845         */
5846        boolean shouldHideSystemApp = false;
5847        if (updatedPkg == null && ps != null
5848                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5849            /*
5850             * Check to make sure the signatures match first. If they don't,
5851             * wipe the installed application and its data.
5852             */
5853            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5854                    != PackageManager.SIGNATURE_MATCH) {
5855                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5856                        + " signatures don't match existing userdata copy; removing");
5857                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5858                ps = null;
5859            } else {
5860                /*
5861                 * If the newly-added system app is an older version than the
5862                 * already installed version, hide it. It will be scanned later
5863                 * and re-added like an update.
5864                 */
5865                if (pkg.mVersionCode <= ps.versionCode) {
5866                    shouldHideSystemApp = true;
5867                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5868                            + " but new version " + pkg.mVersionCode + " better than installed "
5869                            + ps.versionCode + "; hiding system");
5870                } else {
5871                    /*
5872                     * The newly found system app is a newer version that the
5873                     * one previously installed. Simply remove the
5874                     * already-installed application and replace it with our own
5875                     * while keeping the application data.
5876                     */
5877                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5878                            + " reverting from " + ps.codePathString + ": new version "
5879                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5880                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5881                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5882                    synchronized (mInstallLock) {
5883                        args.cleanUpResourcesLI();
5884                    }
5885                }
5886            }
5887        }
5888
5889        // The apk is forward locked (not public) if its code and resources
5890        // are kept in different files. (except for app in either system or
5891        // vendor path).
5892        // TODO grab this value from PackageSettings
5893        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5894            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5895                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5896            }
5897        }
5898
5899        // TODO: extend to support forward-locked splits
5900        String resourcePath = null;
5901        String baseResourcePath = null;
5902        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5903            if (ps != null && ps.resourcePathString != null) {
5904                resourcePath = ps.resourcePathString;
5905                baseResourcePath = ps.resourcePathString;
5906            } else {
5907                // Should not happen at all. Just log an error.
5908                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5909            }
5910        } else {
5911            resourcePath = pkg.codePath;
5912            baseResourcePath = pkg.baseCodePath;
5913        }
5914
5915        // Set application objects path explicitly.
5916        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5917        pkg.applicationInfo.setCodePath(pkg.codePath);
5918        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5919        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5920        pkg.applicationInfo.setResourcePath(resourcePath);
5921        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5922        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5923
5924        // Note that we invoke the following method only if we are about to unpack an application
5925        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5926                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5927
5928        /*
5929         * If the system app should be overridden by a previously installed
5930         * data, hide the system app now and let the /data/app scan pick it up
5931         * again.
5932         */
5933        if (shouldHideSystemApp) {
5934            synchronized (mPackages) {
5935                mSettings.disableSystemPackageLPw(pkg.packageName);
5936            }
5937        }
5938
5939        return scannedPkg;
5940    }
5941
5942    private static String fixProcessName(String defProcessName,
5943            String processName, int uid) {
5944        if (processName == null) {
5945            return defProcessName;
5946        }
5947        return processName;
5948    }
5949
5950    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5951            throws PackageManagerException {
5952        if (pkgSetting.signatures.mSignatures != null) {
5953            // Already existing package. Make sure signatures match
5954            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5955                    == PackageManager.SIGNATURE_MATCH;
5956            if (!match) {
5957                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5958                        == PackageManager.SIGNATURE_MATCH;
5959            }
5960            if (!match) {
5961                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5962                        == PackageManager.SIGNATURE_MATCH;
5963            }
5964            if (!match) {
5965                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5966                        + pkg.packageName + " signatures do not match the "
5967                        + "previously installed version; ignoring!");
5968            }
5969        }
5970
5971        // Check for shared user signatures
5972        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5973            // Already existing package. Make sure signatures match
5974            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5975                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5976            if (!match) {
5977                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5978                        == PackageManager.SIGNATURE_MATCH;
5979            }
5980            if (!match) {
5981                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5982                        == PackageManager.SIGNATURE_MATCH;
5983            }
5984            if (!match) {
5985                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5986                        "Package " + pkg.packageName
5987                        + " has no signatures that match those in shared user "
5988                        + pkgSetting.sharedUser.name + "; ignoring!");
5989            }
5990        }
5991    }
5992
5993    /**
5994     * Enforces that only the system UID or root's UID can call a method exposed
5995     * via Binder.
5996     *
5997     * @param message used as message if SecurityException is thrown
5998     * @throws SecurityException if the caller is not system or root
5999     */
6000    private static final void enforceSystemOrRoot(String message) {
6001        final int uid = Binder.getCallingUid();
6002        if (uid != Process.SYSTEM_UID && uid != 0) {
6003            throw new SecurityException(message);
6004        }
6005    }
6006
6007    @Override
6008    public void performBootDexOpt() {
6009        enforceSystemOrRoot("Only the system can request dexopt be performed");
6010
6011        // Before everything else, see whether we need to fstrim.
6012        try {
6013            IMountService ms = PackageHelper.getMountService();
6014            if (ms != null) {
6015                final boolean isUpgrade = isUpgrade();
6016                boolean doTrim = isUpgrade;
6017                if (doTrim) {
6018                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6019                } else {
6020                    final long interval = android.provider.Settings.Global.getLong(
6021                            mContext.getContentResolver(),
6022                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6023                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6024                    if (interval > 0) {
6025                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6026                        if (timeSinceLast > interval) {
6027                            doTrim = true;
6028                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6029                                    + "; running immediately");
6030                        }
6031                    }
6032                }
6033                if (doTrim) {
6034                    if (!isFirstBoot()) {
6035                        try {
6036                            ActivityManagerNative.getDefault().showBootMessage(
6037                                    mContext.getResources().getString(
6038                                            R.string.android_upgrading_fstrim), true);
6039                        } catch (RemoteException e) {
6040                        }
6041                    }
6042                    ms.runMaintenance();
6043                }
6044            } else {
6045                Slog.e(TAG, "Mount service unavailable!");
6046            }
6047        } catch (RemoteException e) {
6048            // Can't happen; MountService is local
6049        }
6050
6051        final ArraySet<PackageParser.Package> pkgs;
6052        synchronized (mPackages) {
6053            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6054        }
6055
6056        if (pkgs != null) {
6057            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6058            // in case the device runs out of space.
6059            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6060            // Give priority to core apps.
6061            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6062                PackageParser.Package pkg = it.next();
6063                if (pkg.coreApp) {
6064                    if (DEBUG_DEXOPT) {
6065                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6066                    }
6067                    sortedPkgs.add(pkg);
6068                    it.remove();
6069                }
6070            }
6071            // Give priority to system apps that listen for pre boot complete.
6072            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6073            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6074            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6075                PackageParser.Package pkg = it.next();
6076                if (pkgNames.contains(pkg.packageName)) {
6077                    if (DEBUG_DEXOPT) {
6078                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6079                    }
6080                    sortedPkgs.add(pkg);
6081                    it.remove();
6082                }
6083            }
6084            // Filter out packages that aren't recently used.
6085            filterRecentlyUsedApps(pkgs);
6086            // Add all remaining apps.
6087            for (PackageParser.Package pkg : pkgs) {
6088                if (DEBUG_DEXOPT) {
6089                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6090                }
6091                sortedPkgs.add(pkg);
6092            }
6093
6094            // If we want to be lazy, filter everything that wasn't recently used.
6095            if (mLazyDexOpt) {
6096                filterRecentlyUsedApps(sortedPkgs);
6097            }
6098
6099            int i = 0;
6100            int total = sortedPkgs.size();
6101            File dataDir = Environment.getDataDirectory();
6102            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6103            if (lowThreshold == 0) {
6104                throw new IllegalStateException("Invalid low memory threshold");
6105            }
6106            for (PackageParser.Package pkg : sortedPkgs) {
6107                long usableSpace = dataDir.getUsableSpace();
6108                if (usableSpace < lowThreshold) {
6109                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6110                    break;
6111                }
6112                performBootDexOpt(pkg, ++i, total);
6113            }
6114        }
6115    }
6116
6117    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6118        // Filter out packages that aren't recently used.
6119        //
6120        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6121        // should do a full dexopt.
6122        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6123            int total = pkgs.size();
6124            int skipped = 0;
6125            long now = System.currentTimeMillis();
6126            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6127                PackageParser.Package pkg = i.next();
6128                long then = pkg.mLastPackageUsageTimeInMills;
6129                if (then + mDexOptLRUThresholdInMills < now) {
6130                    if (DEBUG_DEXOPT) {
6131                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6132                              ((then == 0) ? "never" : new Date(then)));
6133                    }
6134                    i.remove();
6135                    skipped++;
6136                }
6137            }
6138            if (DEBUG_DEXOPT) {
6139                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6140            }
6141        }
6142    }
6143
6144    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6145        List<ResolveInfo> ris = null;
6146        try {
6147            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6148                    intent, null, 0, UserHandle.USER_OWNER);
6149        } catch (RemoteException e) {
6150        }
6151        ArraySet<String> pkgNames = new ArraySet<String>();
6152        if (ris != null) {
6153            for (ResolveInfo ri : ris) {
6154                pkgNames.add(ri.activityInfo.packageName);
6155            }
6156        }
6157        return pkgNames;
6158    }
6159
6160    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6161        if (DEBUG_DEXOPT) {
6162            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6163        }
6164        if (!isFirstBoot()) {
6165            try {
6166                ActivityManagerNative.getDefault().showBootMessage(
6167                        mContext.getResources().getString(R.string.android_upgrading_apk,
6168                                curr, total), true);
6169            } catch (RemoteException e) {
6170            }
6171        }
6172        PackageParser.Package p = pkg;
6173        synchronized (mInstallLock) {
6174            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6175                    false /* force dex */, false /* defer */, true /* include dependencies */,
6176                    false /* boot complete */, false /*useJit*/);
6177        }
6178    }
6179
6180    @Override
6181    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6182        return performDexOpt(packageName, instructionSet, false);
6183    }
6184
6185    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6186        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6187        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6188        if (!dexopt && !updateUsage) {
6189            // We aren't going to dexopt or update usage, so bail early.
6190            return false;
6191        }
6192        PackageParser.Package p;
6193        final String targetInstructionSet;
6194        synchronized (mPackages) {
6195            p = mPackages.get(packageName);
6196            if (p == null) {
6197                return false;
6198            }
6199            if (updateUsage) {
6200                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6201            }
6202            mPackageUsage.write(false);
6203            if (!dexopt) {
6204                // We aren't going to dexopt, so bail early.
6205                return false;
6206            }
6207
6208            targetInstructionSet = instructionSet != null ? instructionSet :
6209                    getPrimaryInstructionSet(p.applicationInfo);
6210            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6211                return false;
6212            }
6213        }
6214        long callingId = Binder.clearCallingIdentity();
6215        try {
6216            synchronized (mInstallLock) {
6217                final String[] instructionSets = new String[] { targetInstructionSet };
6218                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6219                        false /* forceDex */, false /* defer */, true /* inclDependencies */,
6220                        true /* boot complete */, false /*useJit*/);
6221                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6222            }
6223        } finally {
6224            Binder.restoreCallingIdentity(callingId);
6225        }
6226    }
6227
6228    public ArraySet<String> getPackagesThatNeedDexOpt() {
6229        ArraySet<String> pkgs = null;
6230        synchronized (mPackages) {
6231            for (PackageParser.Package p : mPackages.values()) {
6232                if (DEBUG_DEXOPT) {
6233                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6234                }
6235                if (!p.mDexOptPerformed.isEmpty()) {
6236                    continue;
6237                }
6238                if (pkgs == null) {
6239                    pkgs = new ArraySet<String>();
6240                }
6241                pkgs.add(p.packageName);
6242            }
6243        }
6244        return pkgs;
6245    }
6246
6247    public void shutdown() {
6248        mPackageUsage.write(true);
6249    }
6250
6251    @Override
6252    public void forceDexOpt(String packageName) {
6253        enforceSystemOrRoot("forceDexOpt");
6254
6255        PackageParser.Package pkg;
6256        synchronized (mPackages) {
6257            pkg = mPackages.get(packageName);
6258            if (pkg == null) {
6259                throw new IllegalArgumentException("Missing package: " + packageName);
6260            }
6261        }
6262
6263        synchronized (mInstallLock) {
6264            final String[] instructionSets = new String[] {
6265                    getPrimaryInstructionSet(pkg.applicationInfo) };
6266            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6267                    true /*forceDex*/, false /* defer */, true /* inclDependencies */,
6268                    true /* boot complete */, false /*useJit*/);
6269            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6270                throw new IllegalStateException("Failed to dexopt: " + res);
6271            }
6272        }
6273    }
6274
6275    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6276        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6277            Slog.w(TAG, "Unable to update from " + oldPkg.name
6278                    + " to " + newPkg.packageName
6279                    + ": old package not in system partition");
6280            return false;
6281        } else if (mPackages.get(oldPkg.name) != null) {
6282            Slog.w(TAG, "Unable to update from " + oldPkg.name
6283                    + " to " + newPkg.packageName
6284                    + ": old package still exists");
6285            return false;
6286        }
6287        return true;
6288    }
6289
6290    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6291        int[] users = sUserManager.getUserIds();
6292        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6293        if (res < 0) {
6294            return res;
6295        }
6296        for (int user : users) {
6297            if (user != 0) {
6298                res = mInstaller.createUserData(volumeUuid, packageName,
6299                        UserHandle.getUid(user, uid), user, seinfo);
6300                if (res < 0) {
6301                    return res;
6302                }
6303            }
6304        }
6305        return res;
6306    }
6307
6308    private int removeDataDirsLI(String volumeUuid, String packageName) {
6309        int[] users = sUserManager.getUserIds();
6310        int res = 0;
6311        for (int user : users) {
6312            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6313            if (resInner < 0) {
6314                res = resInner;
6315            }
6316        }
6317
6318        return res;
6319    }
6320
6321    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6322        int[] users = sUserManager.getUserIds();
6323        int res = 0;
6324        for (int user : users) {
6325            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6326            if (resInner < 0) {
6327                res = resInner;
6328            }
6329        }
6330        return res;
6331    }
6332
6333    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6334            PackageParser.Package changingLib) {
6335        if (file.path != null) {
6336            usesLibraryFiles.add(file.path);
6337            return;
6338        }
6339        PackageParser.Package p = mPackages.get(file.apk);
6340        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6341            // If we are doing this while in the middle of updating a library apk,
6342            // then we need to make sure to use that new apk for determining the
6343            // dependencies here.  (We haven't yet finished committing the new apk
6344            // to the package manager state.)
6345            if (p == null || p.packageName.equals(changingLib.packageName)) {
6346                p = changingLib;
6347            }
6348        }
6349        if (p != null) {
6350            usesLibraryFiles.addAll(p.getAllCodePaths());
6351        }
6352    }
6353
6354    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6355            PackageParser.Package changingLib) throws PackageManagerException {
6356        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6357            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6358            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6359            for (int i=0; i<N; i++) {
6360                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6361                if (file == null) {
6362                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6363                            "Package " + pkg.packageName + " requires unavailable shared library "
6364                            + pkg.usesLibraries.get(i) + "; failing!");
6365                }
6366                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6367            }
6368            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6369            for (int i=0; i<N; i++) {
6370                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6371                if (file == null) {
6372                    Slog.w(TAG, "Package " + pkg.packageName
6373                            + " desires unavailable shared library "
6374                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6375                } else {
6376                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6377                }
6378            }
6379            N = usesLibraryFiles.size();
6380            if (N > 0) {
6381                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6382            } else {
6383                pkg.usesLibraryFiles = null;
6384            }
6385        }
6386    }
6387
6388    private static boolean hasString(List<String> list, List<String> which) {
6389        if (list == null) {
6390            return false;
6391        }
6392        for (int i=list.size()-1; i>=0; i--) {
6393            for (int j=which.size()-1; j>=0; j--) {
6394                if (which.get(j).equals(list.get(i))) {
6395                    return true;
6396                }
6397            }
6398        }
6399        return false;
6400    }
6401
6402    private void updateAllSharedLibrariesLPw() {
6403        for (PackageParser.Package pkg : mPackages.values()) {
6404            try {
6405                updateSharedLibrariesLPw(pkg, null);
6406            } catch (PackageManagerException e) {
6407                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6408            }
6409        }
6410    }
6411
6412    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6413            PackageParser.Package changingPkg) {
6414        ArrayList<PackageParser.Package> res = null;
6415        for (PackageParser.Package pkg : mPackages.values()) {
6416            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6417                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6418                if (res == null) {
6419                    res = new ArrayList<PackageParser.Package>();
6420                }
6421                res.add(pkg);
6422                try {
6423                    updateSharedLibrariesLPw(pkg, changingPkg);
6424                } catch (PackageManagerException e) {
6425                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6426                }
6427            }
6428        }
6429        return res;
6430    }
6431
6432    /**
6433     * Derive the value of the {@code cpuAbiOverride} based on the provided
6434     * value and an optional stored value from the package settings.
6435     */
6436    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6437        String cpuAbiOverride = null;
6438
6439        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6440            cpuAbiOverride = null;
6441        } else if (abiOverride != null) {
6442            cpuAbiOverride = abiOverride;
6443        } else if (settings != null) {
6444            cpuAbiOverride = settings.cpuAbiOverrideString;
6445        }
6446
6447        return cpuAbiOverride;
6448    }
6449
6450    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6451            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6452        boolean success = false;
6453        try {
6454            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6455                    currentTime, user);
6456            success = true;
6457            return res;
6458        } finally {
6459            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6460                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6461            }
6462        }
6463    }
6464
6465    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6466            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6467        final File scanFile = new File(pkg.codePath);
6468        if (pkg.applicationInfo.getCodePath() == null ||
6469                pkg.applicationInfo.getResourcePath() == null) {
6470            // Bail out. The resource and code paths haven't been set.
6471            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6472                    "Code and resource paths haven't been set correctly");
6473        }
6474
6475        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6476            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6477        } else {
6478            // Only allow system apps to be flagged as core apps.
6479            pkg.coreApp = false;
6480        }
6481
6482        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6483            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6484        }
6485
6486        if (mCustomResolverComponentName != null &&
6487                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6488            setUpCustomResolverActivity(pkg);
6489        }
6490
6491        if (pkg.packageName.equals("android")) {
6492            synchronized (mPackages) {
6493                if (mAndroidApplication != null) {
6494                    Slog.w(TAG, "*************************************************");
6495                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6496                    Slog.w(TAG, " file=" + scanFile);
6497                    Slog.w(TAG, "*************************************************");
6498                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6499                            "Core android package being redefined.  Skipping.");
6500                }
6501
6502                // Set up information for our fall-back user intent resolution activity.
6503                mPlatformPackage = pkg;
6504                pkg.mVersionCode = mSdkVersion;
6505                mAndroidApplication = pkg.applicationInfo;
6506
6507                if (!mResolverReplaced) {
6508                    mResolveActivity.applicationInfo = mAndroidApplication;
6509                    mResolveActivity.name = ResolverActivity.class.getName();
6510                    mResolveActivity.packageName = mAndroidApplication.packageName;
6511                    mResolveActivity.processName = "system:ui";
6512                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6513                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6514                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6515                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6516                    mResolveActivity.exported = true;
6517                    mResolveActivity.enabled = true;
6518                    mResolveInfo.activityInfo = mResolveActivity;
6519                    mResolveInfo.priority = 0;
6520                    mResolveInfo.preferredOrder = 0;
6521                    mResolveInfo.match = 0;
6522                    mResolveComponentName = new ComponentName(
6523                            mAndroidApplication.packageName, mResolveActivity.name);
6524                }
6525            }
6526        }
6527
6528        if (DEBUG_PACKAGE_SCANNING) {
6529            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6530                Log.d(TAG, "Scanning package " + pkg.packageName);
6531        }
6532
6533        if (mPackages.containsKey(pkg.packageName)
6534                || mSharedLibraries.containsKey(pkg.packageName)) {
6535            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6536                    "Application package " + pkg.packageName
6537                    + " already installed.  Skipping duplicate.");
6538        }
6539
6540        // If we're only installing presumed-existing packages, require that the
6541        // scanned APK is both already known and at the path previously established
6542        // for it.  Previously unknown packages we pick up normally, but if we have an
6543        // a priori expectation about this package's install presence, enforce it.
6544        // With a singular exception for new system packages. When an OTA contains
6545        // a new system package, we allow the codepath to change from a system location
6546        // to the user-installed location. If we don't allow this change, any newer,
6547        // user-installed version of the application will be ignored.
6548        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6549            if (mExpectingBetter.containsKey(pkg.packageName)) {
6550                logCriticalInfo(Log.WARN,
6551                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6552            } else {
6553                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6554                if (known != null) {
6555                    if (DEBUG_PACKAGE_SCANNING) {
6556                        Log.d(TAG, "Examining " + pkg.codePath
6557                                + " and requiring known paths " + known.codePathString
6558                                + " & " + known.resourcePathString);
6559                    }
6560                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6561                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6562                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6563                                "Application package " + pkg.packageName
6564                                + " found at " + pkg.applicationInfo.getCodePath()
6565                                + " but expected at " + known.codePathString + "; ignoring.");
6566                    }
6567                }
6568            }
6569        }
6570
6571        // Initialize package source and resource directories
6572        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6573        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6574
6575        SharedUserSetting suid = null;
6576        PackageSetting pkgSetting = null;
6577
6578        if (!isSystemApp(pkg)) {
6579            // Only system apps can use these features.
6580            pkg.mOriginalPackages = null;
6581            pkg.mRealPackage = null;
6582            pkg.mAdoptPermissions = null;
6583        }
6584
6585        // writer
6586        synchronized (mPackages) {
6587            if (pkg.mSharedUserId != null) {
6588                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6589                if (suid == null) {
6590                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6591                            "Creating application package " + pkg.packageName
6592                            + " for shared user failed");
6593                }
6594                if (DEBUG_PACKAGE_SCANNING) {
6595                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6596                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6597                                + "): packages=" + suid.packages);
6598                }
6599            }
6600
6601            // Check if we are renaming from an original package name.
6602            PackageSetting origPackage = null;
6603            String realName = null;
6604            if (pkg.mOriginalPackages != null) {
6605                // This package may need to be renamed to a previously
6606                // installed name.  Let's check on that...
6607                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6608                if (pkg.mOriginalPackages.contains(renamed)) {
6609                    // This package had originally been installed as the
6610                    // original name, and we have already taken care of
6611                    // transitioning to the new one.  Just update the new
6612                    // one to continue using the old name.
6613                    realName = pkg.mRealPackage;
6614                    if (!pkg.packageName.equals(renamed)) {
6615                        // Callers into this function may have already taken
6616                        // care of renaming the package; only do it here if
6617                        // it is not already done.
6618                        pkg.setPackageName(renamed);
6619                    }
6620
6621                } else {
6622                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6623                        if ((origPackage = mSettings.peekPackageLPr(
6624                                pkg.mOriginalPackages.get(i))) != null) {
6625                            // We do have the package already installed under its
6626                            // original name...  should we use it?
6627                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6628                                // New package is not compatible with original.
6629                                origPackage = null;
6630                                continue;
6631                            } else if (origPackage.sharedUser != null) {
6632                                // Make sure uid is compatible between packages.
6633                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6634                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6635                                            + " to " + pkg.packageName + ": old uid "
6636                                            + origPackage.sharedUser.name
6637                                            + " differs from " + pkg.mSharedUserId);
6638                                    origPackage = null;
6639                                    continue;
6640                                }
6641                            } else {
6642                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6643                                        + pkg.packageName + " to old name " + origPackage.name);
6644                            }
6645                            break;
6646                        }
6647                    }
6648                }
6649            }
6650
6651            if (mTransferedPackages.contains(pkg.packageName)) {
6652                Slog.w(TAG, "Package " + pkg.packageName
6653                        + " was transferred to another, but its .apk remains");
6654            }
6655
6656            // Just create the setting, don't add it yet. For already existing packages
6657            // the PkgSetting exists already and doesn't have to be created.
6658            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6659                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6660                    pkg.applicationInfo.primaryCpuAbi,
6661                    pkg.applicationInfo.secondaryCpuAbi,
6662                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6663                    user, false);
6664            if (pkgSetting == null) {
6665                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6666                        "Creating application package " + pkg.packageName + " failed");
6667            }
6668
6669            if (pkgSetting.origPackage != null) {
6670                // If we are first transitioning from an original package,
6671                // fix up the new package's name now.  We need to do this after
6672                // looking up the package under its new name, so getPackageLP
6673                // can take care of fiddling things correctly.
6674                pkg.setPackageName(origPackage.name);
6675
6676                // File a report about this.
6677                String msg = "New package " + pkgSetting.realName
6678                        + " renamed to replace old package " + pkgSetting.name;
6679                reportSettingsProblem(Log.WARN, msg);
6680
6681                // Make a note of it.
6682                mTransferedPackages.add(origPackage.name);
6683
6684                // No longer need to retain this.
6685                pkgSetting.origPackage = null;
6686            }
6687
6688            if (realName != null) {
6689                // Make a note of it.
6690                mTransferedPackages.add(pkg.packageName);
6691            }
6692
6693            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6694                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6695            }
6696
6697            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6698                // Check all shared libraries and map to their actual file path.
6699                // We only do this here for apps not on a system dir, because those
6700                // are the only ones that can fail an install due to this.  We
6701                // will take care of the system apps by updating all of their
6702                // library paths after the scan is done.
6703                updateSharedLibrariesLPw(pkg, null);
6704            }
6705
6706            if (mFoundPolicyFile) {
6707                SELinuxMMAC.assignSeinfoValue(pkg);
6708            }
6709
6710            pkg.applicationInfo.uid = pkgSetting.appId;
6711            pkg.mExtras = pkgSetting;
6712            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6713                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6714                    // We just determined the app is signed correctly, so bring
6715                    // over the latest parsed certs.
6716                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6717                } else {
6718                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6719                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6720                                "Package " + pkg.packageName + " upgrade keys do not match the "
6721                                + "previously installed version");
6722                    } else {
6723                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6724                        String msg = "System package " + pkg.packageName
6725                            + " signature changed; retaining data.";
6726                        reportSettingsProblem(Log.WARN, msg);
6727                    }
6728                }
6729            } else {
6730                try {
6731                    verifySignaturesLP(pkgSetting, pkg);
6732                    // We just determined the app is signed correctly, so bring
6733                    // over the latest parsed certs.
6734                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6735                } catch (PackageManagerException e) {
6736                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6737                        throw e;
6738                    }
6739                    // The signature has changed, but this package is in the system
6740                    // image...  let's recover!
6741                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6742                    // However...  if this package is part of a shared user, but it
6743                    // doesn't match the signature of the shared user, let's fail.
6744                    // What this means is that you can't change the signatures
6745                    // associated with an overall shared user, which doesn't seem all
6746                    // that unreasonable.
6747                    if (pkgSetting.sharedUser != null) {
6748                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6749                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6750                            throw new PackageManagerException(
6751                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6752                                            "Signature mismatch for shared user : "
6753                                            + pkgSetting.sharedUser);
6754                        }
6755                    }
6756                    // File a report about this.
6757                    String msg = "System package " + pkg.packageName
6758                        + " signature changed; retaining data.";
6759                    reportSettingsProblem(Log.WARN, msg);
6760                }
6761            }
6762            // Verify that this new package doesn't have any content providers
6763            // that conflict with existing packages.  Only do this if the
6764            // package isn't already installed, since we don't want to break
6765            // things that are installed.
6766            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6767                final int N = pkg.providers.size();
6768                int i;
6769                for (i=0; i<N; i++) {
6770                    PackageParser.Provider p = pkg.providers.get(i);
6771                    if (p.info.authority != null) {
6772                        String names[] = p.info.authority.split(";");
6773                        for (int j = 0; j < names.length; j++) {
6774                            if (mProvidersByAuthority.containsKey(names[j])) {
6775                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6776                                final String otherPackageName =
6777                                        ((other != null && other.getComponentName() != null) ?
6778                                                other.getComponentName().getPackageName() : "?");
6779                                throw new PackageManagerException(
6780                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6781                                                "Can't install because provider name " + names[j]
6782                                                + " (in package " + pkg.applicationInfo.packageName
6783                                                + ") is already used by " + otherPackageName);
6784                            }
6785                        }
6786                    }
6787                }
6788            }
6789
6790            if (pkg.mAdoptPermissions != null) {
6791                // This package wants to adopt ownership of permissions from
6792                // another package.
6793                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6794                    final String origName = pkg.mAdoptPermissions.get(i);
6795                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6796                    if (orig != null) {
6797                        if (verifyPackageUpdateLPr(orig, pkg)) {
6798                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6799                                    + pkg.packageName);
6800                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6801                        }
6802                    }
6803                }
6804            }
6805        }
6806
6807        final String pkgName = pkg.packageName;
6808
6809        final long scanFileTime = scanFile.lastModified();
6810        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6811        pkg.applicationInfo.processName = fixProcessName(
6812                pkg.applicationInfo.packageName,
6813                pkg.applicationInfo.processName,
6814                pkg.applicationInfo.uid);
6815
6816        File dataPath;
6817        if (mPlatformPackage == pkg) {
6818            // The system package is special.
6819            dataPath = new File(Environment.getDataDirectory(), "system");
6820
6821            pkg.applicationInfo.dataDir = dataPath.getPath();
6822
6823        } else {
6824            // This is a normal package, need to make its data directory.
6825            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6826                    UserHandle.USER_OWNER, pkg.packageName);
6827
6828            boolean uidError = false;
6829            if (dataPath.exists()) {
6830                int currentUid = 0;
6831                try {
6832                    StructStat stat = Os.stat(dataPath.getPath());
6833                    currentUid = stat.st_uid;
6834                } catch (ErrnoException e) {
6835                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6836                }
6837
6838                // If we have mismatched owners for the data path, we have a problem.
6839                if (currentUid != pkg.applicationInfo.uid) {
6840                    boolean recovered = false;
6841                    if (currentUid == 0) {
6842                        // The directory somehow became owned by root.  Wow.
6843                        // This is probably because the system was stopped while
6844                        // installd was in the middle of messing with its libs
6845                        // directory.  Ask installd to fix that.
6846                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6847                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6848                        if (ret >= 0) {
6849                            recovered = true;
6850                            String msg = "Package " + pkg.packageName
6851                                    + " unexpectedly changed to uid 0; recovered to " +
6852                                    + pkg.applicationInfo.uid;
6853                            reportSettingsProblem(Log.WARN, msg);
6854                        }
6855                    }
6856                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6857                            || (scanFlags&SCAN_BOOTING) != 0)) {
6858                        // If this is a system app, we can at least delete its
6859                        // current data so the application will still work.
6860                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6861                        if (ret >= 0) {
6862                            // TODO: Kill the processes first
6863                            // Old data gone!
6864                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6865                                    ? "System package " : "Third party package ";
6866                            String msg = prefix + pkg.packageName
6867                                    + " has changed from uid: "
6868                                    + currentUid + " to "
6869                                    + pkg.applicationInfo.uid + "; old data erased";
6870                            reportSettingsProblem(Log.WARN, msg);
6871                            recovered = true;
6872
6873                            // And now re-install the app.
6874                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6875                                    pkg.applicationInfo.seinfo);
6876                            if (ret == -1) {
6877                                // Ack should not happen!
6878                                msg = prefix + pkg.packageName
6879                                        + " could not have data directory re-created after delete.";
6880                                reportSettingsProblem(Log.WARN, msg);
6881                                throw new PackageManagerException(
6882                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6883                            }
6884                        }
6885                        if (!recovered) {
6886                            mHasSystemUidErrors = true;
6887                        }
6888                    } else if (!recovered) {
6889                        // If we allow this install to proceed, we will be broken.
6890                        // Abort, abort!
6891                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6892                                "scanPackageLI");
6893                    }
6894                    if (!recovered) {
6895                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6896                            + pkg.applicationInfo.uid + "/fs_"
6897                            + currentUid;
6898                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6899                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6900                        String msg = "Package " + pkg.packageName
6901                                + " has mismatched uid: "
6902                                + currentUid + " on disk, "
6903                                + pkg.applicationInfo.uid + " in settings";
6904                        // writer
6905                        synchronized (mPackages) {
6906                            mSettings.mReadMessages.append(msg);
6907                            mSettings.mReadMessages.append('\n');
6908                            uidError = true;
6909                            if (!pkgSetting.uidError) {
6910                                reportSettingsProblem(Log.ERROR, msg);
6911                            }
6912                        }
6913                    }
6914                }
6915                pkg.applicationInfo.dataDir = dataPath.getPath();
6916                if (mShouldRestoreconData) {
6917                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6918                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6919                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6920                }
6921            } else {
6922                if (DEBUG_PACKAGE_SCANNING) {
6923                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6924                        Log.v(TAG, "Want this data dir: " + dataPath);
6925                }
6926                //invoke installer to do the actual installation
6927                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6928                        pkg.applicationInfo.seinfo);
6929                if (ret < 0) {
6930                    // Error from installer
6931                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6932                            "Unable to create data dirs [errorCode=" + ret + "]");
6933                }
6934
6935                if (dataPath.exists()) {
6936                    pkg.applicationInfo.dataDir = dataPath.getPath();
6937                } else {
6938                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6939                    pkg.applicationInfo.dataDir = null;
6940                }
6941            }
6942
6943            pkgSetting.uidError = uidError;
6944        }
6945
6946        final String path = scanFile.getPath();
6947        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6948
6949        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6950            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6951
6952            // Some system apps still use directory structure for native libraries
6953            // in which case we might end up not detecting abi solely based on apk
6954            // structure. Try to detect abi based on directory structure.
6955            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6956                    pkg.applicationInfo.primaryCpuAbi == null) {
6957                setBundledAppAbisAndRoots(pkg, pkgSetting);
6958                setNativeLibraryPaths(pkg);
6959            }
6960
6961        } else {
6962            if ((scanFlags & SCAN_MOVE) != 0) {
6963                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6964                // but we already have this packages package info in the PackageSetting. We just
6965                // use that and derive the native library path based on the new codepath.
6966                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6967                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6968            }
6969
6970            // Set native library paths again. For moves, the path will be updated based on the
6971            // ABIs we've determined above. For non-moves, the path will be updated based on the
6972            // ABIs we determined during compilation, but the path will depend on the final
6973            // package path (after the rename away from the stage path).
6974            setNativeLibraryPaths(pkg);
6975        }
6976
6977        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6978        final int[] userIds = sUserManager.getUserIds();
6979        synchronized (mInstallLock) {
6980            // Make sure all user data directories are ready to roll; we're okay
6981            // if they already exist
6982            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6983                for (int userId : userIds) {
6984                    if (userId != 0) {
6985                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6986                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6987                                pkg.applicationInfo.seinfo);
6988                    }
6989                }
6990            }
6991
6992            // Create a native library symlink only if we have native libraries
6993            // and if the native libraries are 32 bit libraries. We do not provide
6994            // this symlink for 64 bit libraries.
6995            if (pkg.applicationInfo.primaryCpuAbi != null &&
6996                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6997                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6998                for (int userId : userIds) {
6999                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7000                            nativeLibPath, userId) < 0) {
7001                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7002                                "Failed linking native library dir (user=" + userId + ")");
7003                    }
7004                }
7005            }
7006        }
7007
7008        // This is a special case for the "system" package, where the ABI is
7009        // dictated by the zygote configuration (and init.rc). We should keep track
7010        // of this ABI so that we can deal with "normal" applications that run under
7011        // the same UID correctly.
7012        if (mPlatformPackage == pkg) {
7013            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7014                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7015        }
7016
7017        // If there's a mismatch between the abi-override in the package setting
7018        // and the abiOverride specified for the install. Warn about this because we
7019        // would've already compiled the app without taking the package setting into
7020        // account.
7021        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7022            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7023                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7024                        " for package: " + pkg.packageName);
7025            }
7026        }
7027
7028        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7029        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7030        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7031
7032        // Copy the derived override back to the parsed package, so that we can
7033        // update the package settings accordingly.
7034        pkg.cpuAbiOverride = cpuAbiOverride;
7035
7036        if (DEBUG_ABI_SELECTION) {
7037            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7038                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7039                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7040        }
7041
7042        // Push the derived path down into PackageSettings so we know what to
7043        // clean up at uninstall time.
7044        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7045
7046        if (DEBUG_ABI_SELECTION) {
7047            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7048                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7049                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7050        }
7051
7052        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7053            // We don't do this here during boot because we can do it all
7054            // at once after scanning all existing packages.
7055            //
7056            // We also do this *before* we perform dexopt on this package, so that
7057            // we can avoid redundant dexopts, and also to make sure we've got the
7058            // code and package path correct.
7059            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7060                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */);
7061        }
7062
7063        if ((scanFlags & SCAN_NO_DEX) == 0) {
7064            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7065                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */,
7066                    (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/);
7067            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7068                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7069            }
7070        }
7071        if (mFactoryTest && pkg.requestedPermissions.contains(
7072                android.Manifest.permission.FACTORY_TEST)) {
7073            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7074        }
7075
7076        ArrayList<PackageParser.Package> clientLibPkgs = null;
7077
7078        // writer
7079        synchronized (mPackages) {
7080            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7081                // Only system apps can add new shared libraries.
7082                if (pkg.libraryNames != null) {
7083                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7084                        String name = pkg.libraryNames.get(i);
7085                        boolean allowed = false;
7086                        if (pkg.isUpdatedSystemApp()) {
7087                            // New library entries can only be added through the
7088                            // system image.  This is important to get rid of a lot
7089                            // of nasty edge cases: for example if we allowed a non-
7090                            // system update of the app to add a library, then uninstalling
7091                            // the update would make the library go away, and assumptions
7092                            // we made such as through app install filtering would now
7093                            // have allowed apps on the device which aren't compatible
7094                            // with it.  Better to just have the restriction here, be
7095                            // conservative, and create many fewer cases that can negatively
7096                            // impact the user experience.
7097                            final PackageSetting sysPs = mSettings
7098                                    .getDisabledSystemPkgLPr(pkg.packageName);
7099                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7100                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7101                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7102                                        allowed = true;
7103                                        allowed = true;
7104                                        break;
7105                                    }
7106                                }
7107                            }
7108                        } else {
7109                            allowed = true;
7110                        }
7111                        if (allowed) {
7112                            if (!mSharedLibraries.containsKey(name)) {
7113                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7114                            } else if (!name.equals(pkg.packageName)) {
7115                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7116                                        + name + " already exists; skipping");
7117                            }
7118                        } else {
7119                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7120                                    + name + " that is not declared on system image; skipping");
7121                        }
7122                    }
7123                    if ((scanFlags&SCAN_BOOTING) == 0) {
7124                        // If we are not booting, we need to update any applications
7125                        // that are clients of our shared library.  If we are booting,
7126                        // this will all be done once the scan is complete.
7127                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7128                    }
7129                }
7130            }
7131        }
7132
7133        // We also need to dexopt any apps that are dependent on this library.  Note that
7134        // if these fail, we should abort the install since installing the library will
7135        // result in some apps being broken.
7136        if (clientLibPkgs != null) {
7137            if ((scanFlags & SCAN_NO_DEX) == 0) {
7138                for (int i = 0; i < clientLibPkgs.size(); i++) {
7139                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7140                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7141                            null /* instruction sets */, forceDex,
7142                            (scanFlags & SCAN_DEFER_DEX) != 0, false,
7143                            (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/);
7144                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7145                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7146                                "scanPackageLI failed to dexopt clientLibPkgs");
7147                    }
7148                }
7149            }
7150        }
7151
7152        // Request the ActivityManager to kill the process(only for existing packages)
7153        // so that we do not end up in a confused state while the user is still using the older
7154        // version of the application while the new one gets installed.
7155        if ((scanFlags & SCAN_REPLACING) != 0) {
7156            killApplication(pkg.applicationInfo.packageName,
7157                        pkg.applicationInfo.uid, "replace pkg");
7158        }
7159
7160        // Also need to kill any apps that are dependent on the library.
7161        if (clientLibPkgs != null) {
7162            for (int i=0; i<clientLibPkgs.size(); i++) {
7163                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7164                killApplication(clientPkg.applicationInfo.packageName,
7165                        clientPkg.applicationInfo.uid, "update lib");
7166            }
7167        }
7168
7169        // Make sure we're not adding any bogus keyset info
7170        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7171        ksms.assertScannedPackageValid(pkg);
7172
7173        // writer
7174        synchronized (mPackages) {
7175            // We don't expect installation to fail beyond this point
7176
7177            // Add the new setting to mSettings
7178            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7179            // Add the new setting to mPackages
7180            mPackages.put(pkg.applicationInfo.packageName, pkg);
7181            // Make sure we don't accidentally delete its data.
7182            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7183            while (iter.hasNext()) {
7184                PackageCleanItem item = iter.next();
7185                if (pkgName.equals(item.packageName)) {
7186                    iter.remove();
7187                }
7188            }
7189
7190            // Take care of first install / last update times.
7191            if (currentTime != 0) {
7192                if (pkgSetting.firstInstallTime == 0) {
7193                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7194                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7195                    pkgSetting.lastUpdateTime = currentTime;
7196                }
7197            } else if (pkgSetting.firstInstallTime == 0) {
7198                // We need *something*.  Take time time stamp of the file.
7199                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7200            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7201                if (scanFileTime != pkgSetting.timeStamp) {
7202                    // A package on the system image has changed; consider this
7203                    // to be an update.
7204                    pkgSetting.lastUpdateTime = scanFileTime;
7205                }
7206            }
7207
7208            // Add the package's KeySets to the global KeySetManagerService
7209            ksms.addScannedPackageLPw(pkg);
7210
7211            int N = pkg.providers.size();
7212            StringBuilder r = null;
7213            int i;
7214            for (i=0; i<N; i++) {
7215                PackageParser.Provider p = pkg.providers.get(i);
7216                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7217                        p.info.processName, pkg.applicationInfo.uid);
7218                mProviders.addProvider(p);
7219                p.syncable = p.info.isSyncable;
7220                if (p.info.authority != null) {
7221                    String names[] = p.info.authority.split(";");
7222                    p.info.authority = null;
7223                    for (int j = 0; j < names.length; j++) {
7224                        if (j == 1 && p.syncable) {
7225                            // We only want the first authority for a provider to possibly be
7226                            // syncable, so if we already added this provider using a different
7227                            // authority clear the syncable flag. We copy the provider before
7228                            // changing it because the mProviders object contains a reference
7229                            // to a provider that we don't want to change.
7230                            // Only do this for the second authority since the resulting provider
7231                            // object can be the same for all future authorities for this provider.
7232                            p = new PackageParser.Provider(p);
7233                            p.syncable = false;
7234                        }
7235                        if (!mProvidersByAuthority.containsKey(names[j])) {
7236                            mProvidersByAuthority.put(names[j], p);
7237                            if (p.info.authority == null) {
7238                                p.info.authority = names[j];
7239                            } else {
7240                                p.info.authority = p.info.authority + ";" + names[j];
7241                            }
7242                            if (DEBUG_PACKAGE_SCANNING) {
7243                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7244                                    Log.d(TAG, "Registered content provider: " + names[j]
7245                                            + ", className = " + p.info.name + ", isSyncable = "
7246                                            + p.info.isSyncable);
7247                            }
7248                        } else {
7249                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7250                            Slog.w(TAG, "Skipping provider name " + names[j] +
7251                                    " (in package " + pkg.applicationInfo.packageName +
7252                                    "): name already used by "
7253                                    + ((other != null && other.getComponentName() != null)
7254                                            ? other.getComponentName().getPackageName() : "?"));
7255                        }
7256                    }
7257                }
7258                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7259                    if (r == null) {
7260                        r = new StringBuilder(256);
7261                    } else {
7262                        r.append(' ');
7263                    }
7264                    r.append(p.info.name);
7265                }
7266            }
7267            if (r != null) {
7268                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7269            }
7270
7271            N = pkg.services.size();
7272            r = null;
7273            for (i=0; i<N; i++) {
7274                PackageParser.Service s = pkg.services.get(i);
7275                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7276                        s.info.processName, pkg.applicationInfo.uid);
7277                mServices.addService(s);
7278                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7279                    if (r == null) {
7280                        r = new StringBuilder(256);
7281                    } else {
7282                        r.append(' ');
7283                    }
7284                    r.append(s.info.name);
7285                }
7286            }
7287            if (r != null) {
7288                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7289            }
7290
7291            N = pkg.receivers.size();
7292            r = null;
7293            for (i=0; i<N; i++) {
7294                PackageParser.Activity a = pkg.receivers.get(i);
7295                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7296                        a.info.processName, pkg.applicationInfo.uid);
7297                mReceivers.addActivity(a, "receiver");
7298                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7299                    if (r == null) {
7300                        r = new StringBuilder(256);
7301                    } else {
7302                        r.append(' ');
7303                    }
7304                    r.append(a.info.name);
7305                }
7306            }
7307            if (r != null) {
7308                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7309            }
7310
7311            N = pkg.activities.size();
7312            r = null;
7313            for (i=0; i<N; i++) {
7314                PackageParser.Activity a = pkg.activities.get(i);
7315                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7316                        a.info.processName, pkg.applicationInfo.uid);
7317                mActivities.addActivity(a, "activity");
7318                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7319                    if (r == null) {
7320                        r = new StringBuilder(256);
7321                    } else {
7322                        r.append(' ');
7323                    }
7324                    r.append(a.info.name);
7325                }
7326            }
7327            if (r != null) {
7328                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7329            }
7330
7331            N = pkg.permissionGroups.size();
7332            r = null;
7333            for (i=0; i<N; i++) {
7334                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7335                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7336                if (cur == null) {
7337                    mPermissionGroups.put(pg.info.name, pg);
7338                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7339                        if (r == null) {
7340                            r = new StringBuilder(256);
7341                        } else {
7342                            r.append(' ');
7343                        }
7344                        r.append(pg.info.name);
7345                    }
7346                } else {
7347                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7348                            + pg.info.packageName + " ignored: original from "
7349                            + cur.info.packageName);
7350                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7351                        if (r == null) {
7352                            r = new StringBuilder(256);
7353                        } else {
7354                            r.append(' ');
7355                        }
7356                        r.append("DUP:");
7357                        r.append(pg.info.name);
7358                    }
7359                }
7360            }
7361            if (r != null) {
7362                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7363            }
7364
7365            N = pkg.permissions.size();
7366            r = null;
7367            for (i=0; i<N; i++) {
7368                PackageParser.Permission p = pkg.permissions.get(i);
7369
7370                // Assume by default that we did not install this permission into the system.
7371                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7372
7373                // Now that permission groups have a special meaning, we ignore permission
7374                // groups for legacy apps to prevent unexpected behavior. In particular,
7375                // permissions for one app being granted to someone just becuase they happen
7376                // to be in a group defined by another app (before this had no implications).
7377                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7378                    p.group = mPermissionGroups.get(p.info.group);
7379                    // Warn for a permission in an unknown group.
7380                    if (p.info.group != null && p.group == null) {
7381                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7382                                + p.info.packageName + " in an unknown group " + p.info.group);
7383                    }
7384                }
7385
7386                ArrayMap<String, BasePermission> permissionMap =
7387                        p.tree ? mSettings.mPermissionTrees
7388                                : mSettings.mPermissions;
7389                BasePermission bp = permissionMap.get(p.info.name);
7390
7391                // Allow system apps to redefine non-system permissions
7392                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7393                    final boolean currentOwnerIsSystem = (bp.perm != null
7394                            && isSystemApp(bp.perm.owner));
7395                    if (isSystemApp(p.owner)) {
7396                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7397                            // It's a built-in permission and no owner, take ownership now
7398                            bp.packageSetting = pkgSetting;
7399                            bp.perm = p;
7400                            bp.uid = pkg.applicationInfo.uid;
7401                            bp.sourcePackage = p.info.packageName;
7402                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7403                        } else if (!currentOwnerIsSystem) {
7404                            String msg = "New decl " + p.owner + " of permission  "
7405                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7406                            reportSettingsProblem(Log.WARN, msg);
7407                            bp = null;
7408                        }
7409                    }
7410                }
7411
7412                if (bp == null) {
7413                    bp = new BasePermission(p.info.name, p.info.packageName,
7414                            BasePermission.TYPE_NORMAL);
7415                    permissionMap.put(p.info.name, bp);
7416                }
7417
7418                if (bp.perm == null) {
7419                    if (bp.sourcePackage == null
7420                            || bp.sourcePackage.equals(p.info.packageName)) {
7421                        BasePermission tree = findPermissionTreeLP(p.info.name);
7422                        if (tree == null
7423                                || tree.sourcePackage.equals(p.info.packageName)) {
7424                            bp.packageSetting = pkgSetting;
7425                            bp.perm = p;
7426                            bp.uid = pkg.applicationInfo.uid;
7427                            bp.sourcePackage = p.info.packageName;
7428                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7429                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7430                                if (r == null) {
7431                                    r = new StringBuilder(256);
7432                                } else {
7433                                    r.append(' ');
7434                                }
7435                                r.append(p.info.name);
7436                            }
7437                        } else {
7438                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7439                                    + p.info.packageName + " ignored: base tree "
7440                                    + tree.name + " is from package "
7441                                    + tree.sourcePackage);
7442                        }
7443                    } else {
7444                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7445                                + p.info.packageName + " ignored: original from "
7446                                + bp.sourcePackage);
7447                    }
7448                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7449                    if (r == null) {
7450                        r = new StringBuilder(256);
7451                    } else {
7452                        r.append(' ');
7453                    }
7454                    r.append("DUP:");
7455                    r.append(p.info.name);
7456                }
7457                if (bp.perm == p) {
7458                    bp.protectionLevel = p.info.protectionLevel;
7459                }
7460            }
7461
7462            if (r != null) {
7463                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7464            }
7465
7466            N = pkg.instrumentation.size();
7467            r = null;
7468            for (i=0; i<N; i++) {
7469                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7470                a.info.packageName = pkg.applicationInfo.packageName;
7471                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7472                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7473                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7474                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7475                a.info.dataDir = pkg.applicationInfo.dataDir;
7476
7477                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7478                // need other information about the application, like the ABI and what not ?
7479                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7480                mInstrumentation.put(a.getComponentName(), a);
7481                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7482                    if (r == null) {
7483                        r = new StringBuilder(256);
7484                    } else {
7485                        r.append(' ');
7486                    }
7487                    r.append(a.info.name);
7488                }
7489            }
7490            if (r != null) {
7491                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7492            }
7493
7494            if (pkg.protectedBroadcasts != null) {
7495                N = pkg.protectedBroadcasts.size();
7496                for (i=0; i<N; i++) {
7497                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7498                }
7499            }
7500
7501            pkgSetting.setTimeStamp(scanFileTime);
7502
7503            // Create idmap files for pairs of (packages, overlay packages).
7504            // Note: "android", ie framework-res.apk, is handled by native layers.
7505            if (pkg.mOverlayTarget != null) {
7506                // This is an overlay package.
7507                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7508                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7509                        mOverlays.put(pkg.mOverlayTarget,
7510                                new ArrayMap<String, PackageParser.Package>());
7511                    }
7512                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7513                    map.put(pkg.packageName, pkg);
7514                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7515                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7516                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7517                                "scanPackageLI failed to createIdmap");
7518                    }
7519                }
7520            } else if (mOverlays.containsKey(pkg.packageName) &&
7521                    !pkg.packageName.equals("android")) {
7522                // This is a regular package, with one or more known overlay packages.
7523                createIdmapsForPackageLI(pkg);
7524            }
7525        }
7526
7527        return pkg;
7528    }
7529
7530    /**
7531     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7532     * is derived purely on the basis of the contents of {@code scanFile} and
7533     * {@code cpuAbiOverride}.
7534     *
7535     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7536     */
7537    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7538                                 String cpuAbiOverride, boolean extractLibs)
7539            throws PackageManagerException {
7540        // TODO: We can probably be smarter about this stuff. For installed apps,
7541        // we can calculate this information at install time once and for all. For
7542        // system apps, we can probably assume that this information doesn't change
7543        // after the first boot scan. As things stand, we do lots of unnecessary work.
7544
7545        // Give ourselves some initial paths; we'll come back for another
7546        // pass once we've determined ABI below.
7547        setNativeLibraryPaths(pkg);
7548
7549        // We would never need to extract libs for forward-locked and external packages,
7550        // since the container service will do it for us. We shouldn't attempt to
7551        // extract libs from system app when it was not updated.
7552        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7553                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7554            extractLibs = false;
7555        }
7556
7557        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7558        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7559
7560        NativeLibraryHelper.Handle handle = null;
7561        try {
7562            handle = NativeLibraryHelper.Handle.create(scanFile);
7563            // TODO(multiArch): This can be null for apps that didn't go through the
7564            // usual installation process. We can calculate it again, like we
7565            // do during install time.
7566            //
7567            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7568            // unnecessary.
7569            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7570
7571            // Null out the abis so that they can be recalculated.
7572            pkg.applicationInfo.primaryCpuAbi = null;
7573            pkg.applicationInfo.secondaryCpuAbi = null;
7574            if (isMultiArch(pkg.applicationInfo)) {
7575                // Warn if we've set an abiOverride for multi-lib packages..
7576                // By definition, we need to copy both 32 and 64 bit libraries for
7577                // such packages.
7578                if (pkg.cpuAbiOverride != null
7579                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7580                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7581                }
7582
7583                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7584                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7585                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7586                    if (extractLibs) {
7587                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7588                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7589                                useIsaSpecificSubdirs);
7590                    } else {
7591                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7592                    }
7593                }
7594
7595                maybeThrowExceptionForMultiArchCopy(
7596                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7597
7598                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7599                    if (extractLibs) {
7600                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7601                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7602                                useIsaSpecificSubdirs);
7603                    } else {
7604                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7605                    }
7606                }
7607
7608                maybeThrowExceptionForMultiArchCopy(
7609                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7610
7611                if (abi64 >= 0) {
7612                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7613                }
7614
7615                if (abi32 >= 0) {
7616                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7617                    if (abi64 >= 0) {
7618                        pkg.applicationInfo.secondaryCpuAbi = abi;
7619                    } else {
7620                        pkg.applicationInfo.primaryCpuAbi = abi;
7621                    }
7622                }
7623            } else {
7624                String[] abiList = (cpuAbiOverride != null) ?
7625                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7626
7627                // Enable gross and lame hacks for apps that are built with old
7628                // SDK tools. We must scan their APKs for renderscript bitcode and
7629                // not launch them if it's present. Don't bother checking on devices
7630                // that don't have 64 bit support.
7631                boolean needsRenderScriptOverride = false;
7632                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7633                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7634                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7635                    needsRenderScriptOverride = true;
7636                }
7637
7638                final int copyRet;
7639                if (extractLibs) {
7640                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7641                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7642                } else {
7643                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7644                }
7645
7646                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7647                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7648                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7649                }
7650
7651                if (copyRet >= 0) {
7652                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7653                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7654                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7655                } else if (needsRenderScriptOverride) {
7656                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7657                }
7658            }
7659        } catch (IOException ioe) {
7660            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7661        } finally {
7662            IoUtils.closeQuietly(handle);
7663        }
7664
7665        // Now that we've calculated the ABIs and determined if it's an internal app,
7666        // we will go ahead and populate the nativeLibraryPath.
7667        setNativeLibraryPaths(pkg);
7668    }
7669
7670    /**
7671     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7672     * i.e, so that all packages can be run inside a single process if required.
7673     *
7674     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7675     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7676     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7677     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7678     * updating a package that belongs to a shared user.
7679     *
7680     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7681     * adds unnecessary complexity.
7682     */
7683    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7684            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt,
7685            boolean bootComplete) {
7686        String requiredInstructionSet = null;
7687        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7688            requiredInstructionSet = VMRuntime.getInstructionSet(
7689                     scannedPackage.applicationInfo.primaryCpuAbi);
7690        }
7691
7692        PackageSetting requirer = null;
7693        for (PackageSetting ps : packagesForUser) {
7694            // If packagesForUser contains scannedPackage, we skip it. This will happen
7695            // when scannedPackage is an update of an existing package. Without this check,
7696            // we will never be able to change the ABI of any package belonging to a shared
7697            // user, even if it's compatible with other packages.
7698            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7699                if (ps.primaryCpuAbiString == null) {
7700                    continue;
7701                }
7702
7703                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7704                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7705                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7706                    // this but there's not much we can do.
7707                    String errorMessage = "Instruction set mismatch, "
7708                            + ((requirer == null) ? "[caller]" : requirer)
7709                            + " requires " + requiredInstructionSet + " whereas " + ps
7710                            + " requires " + instructionSet;
7711                    Slog.w(TAG, errorMessage);
7712                }
7713
7714                if (requiredInstructionSet == null) {
7715                    requiredInstructionSet = instructionSet;
7716                    requirer = ps;
7717                }
7718            }
7719        }
7720
7721        if (requiredInstructionSet != null) {
7722            String adjustedAbi;
7723            if (requirer != null) {
7724                // requirer != null implies that either scannedPackage was null or that scannedPackage
7725                // did not require an ABI, in which case we have to adjust scannedPackage to match
7726                // the ABI of the set (which is the same as requirer's ABI)
7727                adjustedAbi = requirer.primaryCpuAbiString;
7728                if (scannedPackage != null) {
7729                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7730                }
7731            } else {
7732                // requirer == null implies that we're updating all ABIs in the set to
7733                // match scannedPackage.
7734                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7735            }
7736
7737            for (PackageSetting ps : packagesForUser) {
7738                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7739                    if (ps.primaryCpuAbiString != null) {
7740                        continue;
7741                    }
7742
7743                    ps.primaryCpuAbiString = adjustedAbi;
7744                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7745                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7746                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7747
7748                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7749                                null /* instruction sets */, forceDexOpt, deferDexOpt, true,
7750                                bootComplete, false /*useJit*/);
7751                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7752                            ps.primaryCpuAbiString = null;
7753                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7754                            return;
7755                        } else {
7756                            mInstaller.rmdex(ps.codePathString,
7757                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7758                        }
7759                    }
7760                }
7761            }
7762        }
7763    }
7764
7765    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7766        synchronized (mPackages) {
7767            mResolverReplaced = true;
7768            // Set up information for custom user intent resolution activity.
7769            mResolveActivity.applicationInfo = pkg.applicationInfo;
7770            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7771            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7772            mResolveActivity.processName = pkg.applicationInfo.packageName;
7773            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7774            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7775                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7776            mResolveActivity.theme = 0;
7777            mResolveActivity.exported = true;
7778            mResolveActivity.enabled = true;
7779            mResolveInfo.activityInfo = mResolveActivity;
7780            mResolveInfo.priority = 0;
7781            mResolveInfo.preferredOrder = 0;
7782            mResolveInfo.match = 0;
7783            mResolveComponentName = mCustomResolverComponentName;
7784            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7785                    mResolveComponentName);
7786        }
7787    }
7788
7789    private static String calculateBundledApkRoot(final String codePathString) {
7790        final File codePath = new File(codePathString);
7791        final File codeRoot;
7792        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7793            codeRoot = Environment.getRootDirectory();
7794        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7795            codeRoot = Environment.getOemDirectory();
7796        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7797            codeRoot = Environment.getVendorDirectory();
7798        } else {
7799            // Unrecognized code path; take its top real segment as the apk root:
7800            // e.g. /something/app/blah.apk => /something
7801            try {
7802                File f = codePath.getCanonicalFile();
7803                File parent = f.getParentFile();    // non-null because codePath is a file
7804                File tmp;
7805                while ((tmp = parent.getParentFile()) != null) {
7806                    f = parent;
7807                    parent = tmp;
7808                }
7809                codeRoot = f;
7810                Slog.w(TAG, "Unrecognized code path "
7811                        + codePath + " - using " + codeRoot);
7812            } catch (IOException e) {
7813                // Can't canonicalize the code path -- shenanigans?
7814                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7815                return Environment.getRootDirectory().getPath();
7816            }
7817        }
7818        return codeRoot.getPath();
7819    }
7820
7821    /**
7822     * Derive and set the location of native libraries for the given package,
7823     * which varies depending on where and how the package was installed.
7824     */
7825    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7826        final ApplicationInfo info = pkg.applicationInfo;
7827        final String codePath = pkg.codePath;
7828        final File codeFile = new File(codePath);
7829        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7830        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
7831
7832        info.nativeLibraryRootDir = null;
7833        info.nativeLibraryRootRequiresIsa = false;
7834        info.nativeLibraryDir = null;
7835        info.secondaryNativeLibraryDir = null;
7836
7837        if (isApkFile(codeFile)) {
7838            // Monolithic install
7839            if (bundledApp) {
7840                // If "/system/lib64/apkname" exists, assume that is the per-package
7841                // native library directory to use; otherwise use "/system/lib/apkname".
7842                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7843                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7844                        getPrimaryInstructionSet(info));
7845
7846                // This is a bundled system app so choose the path based on the ABI.
7847                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7848                // is just the default path.
7849                final String apkName = deriveCodePathName(codePath);
7850                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7851                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7852                        apkName).getAbsolutePath();
7853
7854                if (info.secondaryCpuAbi != null) {
7855                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7856                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7857                            secondaryLibDir, apkName).getAbsolutePath();
7858                }
7859            } else if (asecApp) {
7860                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7861                        .getAbsolutePath();
7862            } else {
7863                final String apkName = deriveCodePathName(codePath);
7864                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7865                        .getAbsolutePath();
7866            }
7867
7868            info.nativeLibraryRootRequiresIsa = false;
7869            info.nativeLibraryDir = info.nativeLibraryRootDir;
7870        } else {
7871            // Cluster install
7872            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7873            info.nativeLibraryRootRequiresIsa = true;
7874
7875            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7876                    getPrimaryInstructionSet(info)).getAbsolutePath();
7877
7878            if (info.secondaryCpuAbi != null) {
7879                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7880                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7881            }
7882        }
7883    }
7884
7885    /**
7886     * Calculate the abis and roots for a bundled app. These can uniquely
7887     * be determined from the contents of the system partition, i.e whether
7888     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7889     * of this information, and instead assume that the system was built
7890     * sensibly.
7891     */
7892    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7893                                           PackageSetting pkgSetting) {
7894        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7895
7896        // If "/system/lib64/apkname" exists, assume that is the per-package
7897        // native library directory to use; otherwise use "/system/lib/apkname".
7898        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7899        setBundledAppAbi(pkg, apkRoot, apkName);
7900        // pkgSetting might be null during rescan following uninstall of updates
7901        // to a bundled app, so accommodate that possibility.  The settings in
7902        // that case will be established later from the parsed package.
7903        //
7904        // If the settings aren't null, sync them up with what we've just derived.
7905        // note that apkRoot isn't stored in the package settings.
7906        if (pkgSetting != null) {
7907            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7908            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7909        }
7910    }
7911
7912    /**
7913     * Deduces the ABI of a bundled app and sets the relevant fields on the
7914     * parsed pkg object.
7915     *
7916     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7917     *        under which system libraries are installed.
7918     * @param apkName the name of the installed package.
7919     */
7920    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7921        final File codeFile = new File(pkg.codePath);
7922
7923        final boolean has64BitLibs;
7924        final boolean has32BitLibs;
7925        if (isApkFile(codeFile)) {
7926            // Monolithic install
7927            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7928            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7929        } else {
7930            // Cluster install
7931            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7932            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7933                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7934                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7935                has64BitLibs = (new File(rootDir, isa)).exists();
7936            } else {
7937                has64BitLibs = false;
7938            }
7939            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7940                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7941                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7942                has32BitLibs = (new File(rootDir, isa)).exists();
7943            } else {
7944                has32BitLibs = false;
7945            }
7946        }
7947
7948        if (has64BitLibs && !has32BitLibs) {
7949            // The package has 64 bit libs, but not 32 bit libs. Its primary
7950            // ABI should be 64 bit. We can safely assume here that the bundled
7951            // native libraries correspond to the most preferred ABI in the list.
7952
7953            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7954            pkg.applicationInfo.secondaryCpuAbi = null;
7955        } else if (has32BitLibs && !has64BitLibs) {
7956            // The package has 32 bit libs but not 64 bit libs. Its primary
7957            // ABI should be 32 bit.
7958
7959            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7960            pkg.applicationInfo.secondaryCpuAbi = null;
7961        } else if (has32BitLibs && has64BitLibs) {
7962            // The application has both 64 and 32 bit bundled libraries. We check
7963            // here that the app declares multiArch support, and warn if it doesn't.
7964            //
7965            // We will be lenient here and record both ABIs. The primary will be the
7966            // ABI that's higher on the list, i.e, a device that's configured to prefer
7967            // 64 bit apps will see a 64 bit primary ABI,
7968
7969            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7970                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7971            }
7972
7973            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7974                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7975                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7976            } else {
7977                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7978                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7979            }
7980        } else {
7981            pkg.applicationInfo.primaryCpuAbi = null;
7982            pkg.applicationInfo.secondaryCpuAbi = null;
7983        }
7984    }
7985
7986    private void killApplication(String pkgName, int appId, String reason) {
7987        // Request the ActivityManager to kill the process(only for existing packages)
7988        // so that we do not end up in a confused state while the user is still using the older
7989        // version of the application while the new one gets installed.
7990        IActivityManager am = ActivityManagerNative.getDefault();
7991        if (am != null) {
7992            try {
7993                am.killApplicationWithAppId(pkgName, appId, reason);
7994            } catch (RemoteException e) {
7995            }
7996        }
7997    }
7998
7999    void removePackageLI(PackageSetting ps, boolean chatty) {
8000        if (DEBUG_INSTALL) {
8001            if (chatty)
8002                Log.d(TAG, "Removing package " + ps.name);
8003        }
8004
8005        // writer
8006        synchronized (mPackages) {
8007            mPackages.remove(ps.name);
8008            final PackageParser.Package pkg = ps.pkg;
8009            if (pkg != null) {
8010                cleanPackageDataStructuresLILPw(pkg, chatty);
8011            }
8012        }
8013    }
8014
8015    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8016        if (DEBUG_INSTALL) {
8017            if (chatty)
8018                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8019        }
8020
8021        // writer
8022        synchronized (mPackages) {
8023            mPackages.remove(pkg.applicationInfo.packageName);
8024            cleanPackageDataStructuresLILPw(pkg, chatty);
8025        }
8026    }
8027
8028    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8029        int N = pkg.providers.size();
8030        StringBuilder r = null;
8031        int i;
8032        for (i=0; i<N; i++) {
8033            PackageParser.Provider p = pkg.providers.get(i);
8034            mProviders.removeProvider(p);
8035            if (p.info.authority == null) {
8036
8037                /* There was another ContentProvider with this authority when
8038                 * this app was installed so this authority is null,
8039                 * Ignore it as we don't have to unregister the provider.
8040                 */
8041                continue;
8042            }
8043            String names[] = p.info.authority.split(";");
8044            for (int j = 0; j < names.length; j++) {
8045                if (mProvidersByAuthority.get(names[j]) == p) {
8046                    mProvidersByAuthority.remove(names[j]);
8047                    if (DEBUG_REMOVE) {
8048                        if (chatty)
8049                            Log.d(TAG, "Unregistered content provider: " + names[j]
8050                                    + ", className = " + p.info.name + ", isSyncable = "
8051                                    + p.info.isSyncable);
8052                    }
8053                }
8054            }
8055            if (DEBUG_REMOVE && chatty) {
8056                if (r == null) {
8057                    r = new StringBuilder(256);
8058                } else {
8059                    r.append(' ');
8060                }
8061                r.append(p.info.name);
8062            }
8063        }
8064        if (r != null) {
8065            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8066        }
8067
8068        N = pkg.services.size();
8069        r = null;
8070        for (i=0; i<N; i++) {
8071            PackageParser.Service s = pkg.services.get(i);
8072            mServices.removeService(s);
8073            if (chatty) {
8074                if (r == null) {
8075                    r = new StringBuilder(256);
8076                } else {
8077                    r.append(' ');
8078                }
8079                r.append(s.info.name);
8080            }
8081        }
8082        if (r != null) {
8083            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8084        }
8085
8086        N = pkg.receivers.size();
8087        r = null;
8088        for (i=0; i<N; i++) {
8089            PackageParser.Activity a = pkg.receivers.get(i);
8090            mReceivers.removeActivity(a, "receiver");
8091            if (DEBUG_REMOVE && chatty) {
8092                if (r == null) {
8093                    r = new StringBuilder(256);
8094                } else {
8095                    r.append(' ');
8096                }
8097                r.append(a.info.name);
8098            }
8099        }
8100        if (r != null) {
8101            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8102        }
8103
8104        N = pkg.activities.size();
8105        r = null;
8106        for (i=0; i<N; i++) {
8107            PackageParser.Activity a = pkg.activities.get(i);
8108            mActivities.removeActivity(a, "activity");
8109            if (DEBUG_REMOVE && chatty) {
8110                if (r == null) {
8111                    r = new StringBuilder(256);
8112                } else {
8113                    r.append(' ');
8114                }
8115                r.append(a.info.name);
8116            }
8117        }
8118        if (r != null) {
8119            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8120        }
8121
8122        N = pkg.permissions.size();
8123        r = null;
8124        for (i=0; i<N; i++) {
8125            PackageParser.Permission p = pkg.permissions.get(i);
8126            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8127            if (bp == null) {
8128                bp = mSettings.mPermissionTrees.get(p.info.name);
8129            }
8130            if (bp != null && bp.perm == p) {
8131                bp.perm = null;
8132                if (DEBUG_REMOVE && chatty) {
8133                    if (r == null) {
8134                        r = new StringBuilder(256);
8135                    } else {
8136                        r.append(' ');
8137                    }
8138                    r.append(p.info.name);
8139                }
8140            }
8141            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8142                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8143                if (appOpPerms != null) {
8144                    appOpPerms.remove(pkg.packageName);
8145                }
8146            }
8147        }
8148        if (r != null) {
8149            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8150        }
8151
8152        N = pkg.requestedPermissions.size();
8153        r = null;
8154        for (i=0; i<N; i++) {
8155            String perm = pkg.requestedPermissions.get(i);
8156            BasePermission bp = mSettings.mPermissions.get(perm);
8157            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8158                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8159                if (appOpPerms != null) {
8160                    appOpPerms.remove(pkg.packageName);
8161                    if (appOpPerms.isEmpty()) {
8162                        mAppOpPermissionPackages.remove(perm);
8163                    }
8164                }
8165            }
8166        }
8167        if (r != null) {
8168            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8169        }
8170
8171        N = pkg.instrumentation.size();
8172        r = null;
8173        for (i=0; i<N; i++) {
8174            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8175            mInstrumentation.remove(a.getComponentName());
8176            if (DEBUG_REMOVE && chatty) {
8177                if (r == null) {
8178                    r = new StringBuilder(256);
8179                } else {
8180                    r.append(' ');
8181                }
8182                r.append(a.info.name);
8183            }
8184        }
8185        if (r != null) {
8186            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8187        }
8188
8189        r = null;
8190        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8191            // Only system apps can hold shared libraries.
8192            if (pkg.libraryNames != null) {
8193                for (i=0; i<pkg.libraryNames.size(); i++) {
8194                    String name = pkg.libraryNames.get(i);
8195                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8196                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8197                        mSharedLibraries.remove(name);
8198                        if (DEBUG_REMOVE && chatty) {
8199                            if (r == null) {
8200                                r = new StringBuilder(256);
8201                            } else {
8202                                r.append(' ');
8203                            }
8204                            r.append(name);
8205                        }
8206                    }
8207                }
8208            }
8209        }
8210        if (r != null) {
8211            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8212        }
8213    }
8214
8215    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8216        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8217            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8218                return true;
8219            }
8220        }
8221        return false;
8222    }
8223
8224    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8225    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8226    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8227
8228    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8229            int flags) {
8230        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8231        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8232    }
8233
8234    private void updatePermissionsLPw(String changingPkg,
8235            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8236        // Make sure there are no dangling permission trees.
8237        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8238        while (it.hasNext()) {
8239            final BasePermission bp = it.next();
8240            if (bp.packageSetting == null) {
8241                // We may not yet have parsed the package, so just see if
8242                // we still know about its settings.
8243                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8244            }
8245            if (bp.packageSetting == null) {
8246                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8247                        + " from package " + bp.sourcePackage);
8248                it.remove();
8249            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8250                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8251                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8252                            + " from package " + bp.sourcePackage);
8253                    flags |= UPDATE_PERMISSIONS_ALL;
8254                    it.remove();
8255                }
8256            }
8257        }
8258
8259        // Make sure all dynamic permissions have been assigned to a package,
8260        // and make sure there are no dangling permissions.
8261        it = mSettings.mPermissions.values().iterator();
8262        while (it.hasNext()) {
8263            final BasePermission bp = it.next();
8264            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8265                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8266                        + bp.name + " pkg=" + bp.sourcePackage
8267                        + " info=" + bp.pendingInfo);
8268                if (bp.packageSetting == null && bp.pendingInfo != null) {
8269                    final BasePermission tree = findPermissionTreeLP(bp.name);
8270                    if (tree != null && tree.perm != null) {
8271                        bp.packageSetting = tree.packageSetting;
8272                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8273                                new PermissionInfo(bp.pendingInfo));
8274                        bp.perm.info.packageName = tree.perm.info.packageName;
8275                        bp.perm.info.name = bp.name;
8276                        bp.uid = tree.uid;
8277                    }
8278                }
8279            }
8280            if (bp.packageSetting == null) {
8281                // We may not yet have parsed the package, so just see if
8282                // we still know about its settings.
8283                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8284            }
8285            if (bp.packageSetting == null) {
8286                Slog.w(TAG, "Removing dangling permission: " + bp.name
8287                        + " from package " + bp.sourcePackage);
8288                it.remove();
8289            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8290                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8291                    Slog.i(TAG, "Removing old permission: " + bp.name
8292                            + " from package " + bp.sourcePackage);
8293                    flags |= UPDATE_PERMISSIONS_ALL;
8294                    it.remove();
8295                }
8296            }
8297        }
8298
8299        // Now update the permissions for all packages, in particular
8300        // replace the granted permissions of the system packages.
8301        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8302            for (PackageParser.Package pkg : mPackages.values()) {
8303                if (pkg != pkgInfo) {
8304                    // Only replace for packages on requested volume
8305                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8306                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8307                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8308                    grantPermissionsLPw(pkg, replace, changingPkg);
8309                }
8310            }
8311        }
8312
8313        if (pkgInfo != null) {
8314            // Only replace for packages on requested volume
8315            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8316            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8317                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8318            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8319        }
8320    }
8321
8322    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8323            String packageOfInterest) {
8324        // IMPORTANT: There are two types of permissions: install and runtime.
8325        // Install time permissions are granted when the app is installed to
8326        // all device users and users added in the future. Runtime permissions
8327        // are granted at runtime explicitly to specific users. Normal and signature
8328        // protected permissions are install time permissions. Dangerous permissions
8329        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8330        // otherwise they are runtime permissions. This function does not manage
8331        // runtime permissions except for the case an app targeting Lollipop MR1
8332        // being upgraded to target a newer SDK, in which case dangerous permissions
8333        // are transformed from install time to runtime ones.
8334
8335        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8336        if (ps == null) {
8337            return;
8338        }
8339
8340        PermissionsState permissionsState = ps.getPermissionsState();
8341        PermissionsState origPermissions = permissionsState;
8342
8343        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8344
8345        boolean runtimePermissionsRevoked = false;
8346        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8347
8348        boolean changedInstallPermission = false;
8349
8350        if (replace) {
8351            ps.installPermissionsFixed = false;
8352            if (!ps.isSharedUser()) {
8353                origPermissions = new PermissionsState(permissionsState);
8354                permissionsState.reset();
8355            } else {
8356                // We need to know only about runtime permission changes since the
8357                // calling code always writes the install permissions state but
8358                // the runtime ones are written only if changed. The only cases of
8359                // changed runtime permissions here are promotion of an install to
8360                // runtime and revocation of a runtime from a shared user.
8361                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8362                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8363                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8364                    runtimePermissionsRevoked = true;
8365                }
8366            }
8367        }
8368
8369        permissionsState.setGlobalGids(mGlobalGids);
8370
8371        final int N = pkg.requestedPermissions.size();
8372        for (int i=0; i<N; i++) {
8373            final String name = pkg.requestedPermissions.get(i);
8374            final BasePermission bp = mSettings.mPermissions.get(name);
8375
8376            if (DEBUG_INSTALL) {
8377                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8378            }
8379
8380            if (bp == null || bp.packageSetting == null) {
8381                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8382                    Slog.w(TAG, "Unknown permission " + name
8383                            + " in package " + pkg.packageName);
8384                }
8385                continue;
8386            }
8387
8388            final String perm = bp.name;
8389            boolean allowedSig = false;
8390            int grant = GRANT_DENIED;
8391
8392            // Keep track of app op permissions.
8393            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8394                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8395                if (pkgs == null) {
8396                    pkgs = new ArraySet<>();
8397                    mAppOpPermissionPackages.put(bp.name, pkgs);
8398                }
8399                pkgs.add(pkg.packageName);
8400            }
8401
8402            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8403            switch (level) {
8404                case PermissionInfo.PROTECTION_NORMAL: {
8405                    // For all apps normal permissions are install time ones.
8406                    grant = GRANT_INSTALL;
8407                } break;
8408
8409                case PermissionInfo.PROTECTION_DANGEROUS: {
8410                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8411                        // For legacy apps dangerous permissions are install time ones.
8412                        grant = GRANT_INSTALL_LEGACY;
8413                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8414                        // For legacy apps that became modern, install becomes runtime.
8415                        grant = GRANT_UPGRADE;
8416                    } else if (mPromoteSystemApps
8417                            && isSystemApp(ps)
8418                            && mExistingSystemPackages.contains(ps.name)) {
8419                        // For legacy system apps, install becomes runtime.
8420                        // We cannot check hasInstallPermission() for system apps since those
8421                        // permissions were granted implicitly and not persisted pre-M.
8422                        grant = GRANT_UPGRADE;
8423                    } else {
8424                        // For modern apps keep runtime permissions unchanged.
8425                        grant = GRANT_RUNTIME;
8426                    }
8427                } break;
8428
8429                case PermissionInfo.PROTECTION_SIGNATURE: {
8430                    // For all apps signature permissions are install time ones.
8431                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8432                    if (allowedSig) {
8433                        grant = GRANT_INSTALL;
8434                    }
8435                } break;
8436            }
8437
8438            if (DEBUG_INSTALL) {
8439                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8440            }
8441
8442            if (grant != GRANT_DENIED) {
8443                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8444                    // If this is an existing, non-system package, then
8445                    // we can't add any new permissions to it.
8446                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8447                        // Except...  if this is a permission that was added
8448                        // to the platform (note: need to only do this when
8449                        // updating the platform).
8450                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8451                            grant = GRANT_DENIED;
8452                        }
8453                    }
8454                }
8455
8456                switch (grant) {
8457                    case GRANT_INSTALL: {
8458                        // Revoke this as runtime permission to handle the case of
8459                        // a runtime permission being downgraded to an install one.
8460                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8461                            if (origPermissions.getRuntimePermissionState(
8462                                    bp.name, userId) != null) {
8463                                // Revoke the runtime permission and clear the flags.
8464                                origPermissions.revokeRuntimePermission(bp, userId);
8465                                origPermissions.updatePermissionFlags(bp, userId,
8466                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8467                                // If we revoked a permission permission, we have to write.
8468                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8469                                        changedRuntimePermissionUserIds, userId);
8470                            }
8471                        }
8472                        // Grant an install permission.
8473                        if (permissionsState.grantInstallPermission(bp) !=
8474                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8475                            changedInstallPermission = true;
8476                        }
8477                    } break;
8478
8479                    case GRANT_INSTALL_LEGACY: {
8480                        // Grant an install permission.
8481                        if (permissionsState.grantInstallPermission(bp) !=
8482                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8483                            changedInstallPermission = true;
8484                        }
8485                    } break;
8486
8487                    case GRANT_RUNTIME: {
8488                        // Grant previously granted runtime permissions.
8489                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8490                            PermissionState permissionState = origPermissions
8491                                    .getRuntimePermissionState(bp.name, userId);
8492                            final int flags = permissionState != null
8493                                    ? permissionState.getFlags() : 0;
8494                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8495                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8496                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8497                                    // If we cannot put the permission as it was, we have to write.
8498                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8499                                            changedRuntimePermissionUserIds, userId);
8500                                }
8501                            }
8502                            // Propagate the permission flags.
8503                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8504                        }
8505                    } break;
8506
8507                    case GRANT_UPGRADE: {
8508                        // Grant runtime permissions for a previously held install permission.
8509                        PermissionState permissionState = origPermissions
8510                                .getInstallPermissionState(bp.name);
8511                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8512
8513                        if (origPermissions.revokeInstallPermission(bp)
8514                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8515                            // We will be transferring the permission flags, so clear them.
8516                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8517                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8518                            changedInstallPermission = true;
8519                        }
8520
8521                        // If the permission is not to be promoted to runtime we ignore it and
8522                        // also its other flags as they are not applicable to install permissions.
8523                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8524                            for (int userId : currentUserIds) {
8525                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8526                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8527                                    // Transfer the permission flags.
8528                                    permissionsState.updatePermissionFlags(bp, userId,
8529                                            flags, flags);
8530                                    // If we granted the permission, we have to write.
8531                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8532                                            changedRuntimePermissionUserIds, userId);
8533                                }
8534                            }
8535                        }
8536                    } break;
8537
8538                    default: {
8539                        if (packageOfInterest == null
8540                                || packageOfInterest.equals(pkg.packageName)) {
8541                            Slog.w(TAG, "Not granting permission " + perm
8542                                    + " to package " + pkg.packageName
8543                                    + " because it was previously installed without");
8544                        }
8545                    } break;
8546                }
8547            } else {
8548                if (permissionsState.revokeInstallPermission(bp) !=
8549                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8550                    // Also drop the permission flags.
8551                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8552                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8553                    changedInstallPermission = true;
8554                    Slog.i(TAG, "Un-granting permission " + perm
8555                            + " from package " + pkg.packageName
8556                            + " (protectionLevel=" + bp.protectionLevel
8557                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8558                            + ")");
8559                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8560                    // Don't print warning for app op permissions, since it is fine for them
8561                    // not to be granted, there is a UI for the user to decide.
8562                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8563                        Slog.w(TAG, "Not granting permission " + perm
8564                                + " to package " + pkg.packageName
8565                                + " (protectionLevel=" + bp.protectionLevel
8566                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8567                                + ")");
8568                    }
8569                }
8570            }
8571        }
8572
8573        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8574                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8575            // This is the first that we have heard about this package, so the
8576            // permissions we have now selected are fixed until explicitly
8577            // changed.
8578            ps.installPermissionsFixed = true;
8579        }
8580
8581        // Persist the runtime permissions state for users with changes. If permissions
8582        // were revoked because no app in the shared user declares them we have to
8583        // write synchronously to avoid losing runtime permissions state.
8584        for (int userId : changedRuntimePermissionUserIds) {
8585            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8586        }
8587    }
8588
8589    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8590        boolean allowed = false;
8591        final int NP = PackageParser.NEW_PERMISSIONS.length;
8592        for (int ip=0; ip<NP; ip++) {
8593            final PackageParser.NewPermissionInfo npi
8594                    = PackageParser.NEW_PERMISSIONS[ip];
8595            if (npi.name.equals(perm)
8596                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8597                allowed = true;
8598                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8599                        + pkg.packageName);
8600                break;
8601            }
8602        }
8603        return allowed;
8604    }
8605
8606    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8607            BasePermission bp, PermissionsState origPermissions) {
8608        boolean allowed;
8609        allowed = (compareSignatures(
8610                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8611                        == PackageManager.SIGNATURE_MATCH)
8612                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8613                        == PackageManager.SIGNATURE_MATCH);
8614        if (!allowed && (bp.protectionLevel
8615                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8616            if (isSystemApp(pkg)) {
8617                // For updated system applications, a system permission
8618                // is granted only if it had been defined by the original application.
8619                if (pkg.isUpdatedSystemApp()) {
8620                    final PackageSetting sysPs = mSettings
8621                            .getDisabledSystemPkgLPr(pkg.packageName);
8622                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8623                        // If the original was granted this permission, we take
8624                        // that grant decision as read and propagate it to the
8625                        // update.
8626                        if (sysPs.isPrivileged()) {
8627                            allowed = true;
8628                        }
8629                    } else {
8630                        // The system apk may have been updated with an older
8631                        // version of the one on the data partition, but which
8632                        // granted a new system permission that it didn't have
8633                        // before.  In this case we do want to allow the app to
8634                        // now get the new permission if the ancestral apk is
8635                        // privileged to get it.
8636                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8637                            for (int j=0;
8638                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8639                                if (perm.equals(
8640                                        sysPs.pkg.requestedPermissions.get(j))) {
8641                                    allowed = true;
8642                                    break;
8643                                }
8644                            }
8645                        }
8646                    }
8647                } else {
8648                    allowed = isPrivilegedApp(pkg);
8649                }
8650            }
8651        }
8652        if (!allowed) {
8653            if (!allowed && (bp.protectionLevel
8654                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8655                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8656                // If this was a previously normal/dangerous permission that got moved
8657                // to a system permission as part of the runtime permission redesign, then
8658                // we still want to blindly grant it to old apps.
8659                allowed = true;
8660            }
8661            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8662                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8663                // If this permission is to be granted to the system installer and
8664                // this app is an installer, then it gets the permission.
8665                allowed = true;
8666            }
8667            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8668                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8669                // If this permission is to be granted to the system verifier and
8670                // this app is a verifier, then it gets the permission.
8671                allowed = true;
8672            }
8673            if (!allowed && (bp.protectionLevel
8674                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8675                    && isSystemApp(pkg)) {
8676                // Any pre-installed system app is allowed to get this permission.
8677                allowed = true;
8678            }
8679            if (!allowed && (bp.protectionLevel
8680                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8681                // For development permissions, a development permission
8682                // is granted only if it was already granted.
8683                allowed = origPermissions.hasInstallPermission(perm);
8684            }
8685        }
8686        return allowed;
8687    }
8688
8689    final class ActivityIntentResolver
8690            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8691        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8692                boolean defaultOnly, int userId) {
8693            if (!sUserManager.exists(userId)) return null;
8694            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8695            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8696        }
8697
8698        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8699                int userId) {
8700            if (!sUserManager.exists(userId)) return null;
8701            mFlags = flags;
8702            return super.queryIntent(intent, resolvedType,
8703                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8704        }
8705
8706        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8707                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8708            if (!sUserManager.exists(userId)) return null;
8709            if (packageActivities == null) {
8710                return null;
8711            }
8712            mFlags = flags;
8713            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8714            final int N = packageActivities.size();
8715            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8716                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8717
8718            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8719            for (int i = 0; i < N; ++i) {
8720                intentFilters = packageActivities.get(i).intents;
8721                if (intentFilters != null && intentFilters.size() > 0) {
8722                    PackageParser.ActivityIntentInfo[] array =
8723                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8724                    intentFilters.toArray(array);
8725                    listCut.add(array);
8726                }
8727            }
8728            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8729        }
8730
8731        public final void addActivity(PackageParser.Activity a, String type) {
8732            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8733            mActivities.put(a.getComponentName(), a);
8734            if (DEBUG_SHOW_INFO)
8735                Log.v(
8736                TAG, "  " + type + " " +
8737                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8738            if (DEBUG_SHOW_INFO)
8739                Log.v(TAG, "    Class=" + a.info.name);
8740            final int NI = a.intents.size();
8741            for (int j=0; j<NI; j++) {
8742                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8743                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8744                    intent.setPriority(0);
8745                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8746                            + a.className + " with priority > 0, forcing to 0");
8747                }
8748                if (DEBUG_SHOW_INFO) {
8749                    Log.v(TAG, "    IntentFilter:");
8750                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8751                }
8752                if (!intent.debugCheck()) {
8753                    Log.w(TAG, "==> For Activity " + a.info.name);
8754                }
8755                addFilter(intent);
8756            }
8757        }
8758
8759        public final void removeActivity(PackageParser.Activity a, String type) {
8760            mActivities.remove(a.getComponentName());
8761            if (DEBUG_SHOW_INFO) {
8762                Log.v(TAG, "  " + type + " "
8763                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8764                                : a.info.name) + ":");
8765                Log.v(TAG, "    Class=" + a.info.name);
8766            }
8767            final int NI = a.intents.size();
8768            for (int j=0; j<NI; j++) {
8769                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8770                if (DEBUG_SHOW_INFO) {
8771                    Log.v(TAG, "    IntentFilter:");
8772                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8773                }
8774                removeFilter(intent);
8775            }
8776        }
8777
8778        @Override
8779        protected boolean allowFilterResult(
8780                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8781            ActivityInfo filterAi = filter.activity.info;
8782            for (int i=dest.size()-1; i>=0; i--) {
8783                ActivityInfo destAi = dest.get(i).activityInfo;
8784                if (destAi.name == filterAi.name
8785                        && destAi.packageName == filterAi.packageName) {
8786                    return false;
8787                }
8788            }
8789            return true;
8790        }
8791
8792        @Override
8793        protected ActivityIntentInfo[] newArray(int size) {
8794            return new ActivityIntentInfo[size];
8795        }
8796
8797        @Override
8798        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8799            if (!sUserManager.exists(userId)) return true;
8800            PackageParser.Package p = filter.activity.owner;
8801            if (p != null) {
8802                PackageSetting ps = (PackageSetting)p.mExtras;
8803                if (ps != null) {
8804                    // System apps are never considered stopped for purposes of
8805                    // filtering, because there may be no way for the user to
8806                    // actually re-launch them.
8807                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8808                            && ps.getStopped(userId);
8809                }
8810            }
8811            return false;
8812        }
8813
8814        @Override
8815        protected boolean isPackageForFilter(String packageName,
8816                PackageParser.ActivityIntentInfo info) {
8817            return packageName.equals(info.activity.owner.packageName);
8818        }
8819
8820        @Override
8821        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8822                int match, int userId) {
8823            if (!sUserManager.exists(userId)) return null;
8824            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8825                return null;
8826            }
8827            final PackageParser.Activity activity = info.activity;
8828            if (mSafeMode && (activity.info.applicationInfo.flags
8829                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8830                return null;
8831            }
8832            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8833            if (ps == null) {
8834                return null;
8835            }
8836            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8837                    ps.readUserState(userId), userId);
8838            if (ai == null) {
8839                return null;
8840            }
8841            final ResolveInfo res = new ResolveInfo();
8842            res.activityInfo = ai;
8843            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8844                res.filter = info;
8845            }
8846            if (info != null) {
8847                res.handleAllWebDataURI = info.handleAllWebDataURI();
8848            }
8849            res.priority = info.getPriority();
8850            res.preferredOrder = activity.owner.mPreferredOrder;
8851            //System.out.println("Result: " + res.activityInfo.className +
8852            //                   " = " + res.priority);
8853            res.match = match;
8854            res.isDefault = info.hasDefault;
8855            res.labelRes = info.labelRes;
8856            res.nonLocalizedLabel = info.nonLocalizedLabel;
8857            if (userNeedsBadging(userId)) {
8858                res.noResourceId = true;
8859            } else {
8860                res.icon = info.icon;
8861            }
8862            res.iconResourceId = info.icon;
8863            res.system = res.activityInfo.applicationInfo.isSystemApp();
8864            return res;
8865        }
8866
8867        @Override
8868        protected void sortResults(List<ResolveInfo> results) {
8869            Collections.sort(results, mResolvePrioritySorter);
8870        }
8871
8872        @Override
8873        protected void dumpFilter(PrintWriter out, String prefix,
8874                PackageParser.ActivityIntentInfo filter) {
8875            out.print(prefix); out.print(
8876                    Integer.toHexString(System.identityHashCode(filter.activity)));
8877                    out.print(' ');
8878                    filter.activity.printComponentShortName(out);
8879                    out.print(" filter ");
8880                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8881        }
8882
8883        @Override
8884        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8885            return filter.activity;
8886        }
8887
8888        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8889            PackageParser.Activity activity = (PackageParser.Activity)label;
8890            out.print(prefix); out.print(
8891                    Integer.toHexString(System.identityHashCode(activity)));
8892                    out.print(' ');
8893                    activity.printComponentShortName(out);
8894            if (count > 1) {
8895                out.print(" ("); out.print(count); out.print(" filters)");
8896            }
8897            out.println();
8898        }
8899
8900//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8901//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8902//            final List<ResolveInfo> retList = Lists.newArrayList();
8903//            while (i.hasNext()) {
8904//                final ResolveInfo resolveInfo = i.next();
8905//                if (isEnabledLP(resolveInfo.activityInfo)) {
8906//                    retList.add(resolveInfo);
8907//                }
8908//            }
8909//            return retList;
8910//        }
8911
8912        // Keys are String (activity class name), values are Activity.
8913        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8914                = new ArrayMap<ComponentName, PackageParser.Activity>();
8915        private int mFlags;
8916    }
8917
8918    private final class ServiceIntentResolver
8919            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8920        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8921                boolean defaultOnly, int userId) {
8922            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8923            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8924        }
8925
8926        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8927                int userId) {
8928            if (!sUserManager.exists(userId)) return null;
8929            mFlags = flags;
8930            return super.queryIntent(intent, resolvedType,
8931                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8932        }
8933
8934        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8935                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8936            if (!sUserManager.exists(userId)) return null;
8937            if (packageServices == null) {
8938                return null;
8939            }
8940            mFlags = flags;
8941            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8942            final int N = packageServices.size();
8943            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8944                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8945
8946            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8947            for (int i = 0; i < N; ++i) {
8948                intentFilters = packageServices.get(i).intents;
8949                if (intentFilters != null && intentFilters.size() > 0) {
8950                    PackageParser.ServiceIntentInfo[] array =
8951                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8952                    intentFilters.toArray(array);
8953                    listCut.add(array);
8954                }
8955            }
8956            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8957        }
8958
8959        public final void addService(PackageParser.Service s) {
8960            mServices.put(s.getComponentName(), s);
8961            if (DEBUG_SHOW_INFO) {
8962                Log.v(TAG, "  "
8963                        + (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                if (!intent.debugCheck()) {
8976                    Log.w(TAG, "==> For Service " + s.info.name);
8977                }
8978                addFilter(intent);
8979            }
8980        }
8981
8982        public final void removeService(PackageParser.Service s) {
8983            mServices.remove(s.getComponentName());
8984            if (DEBUG_SHOW_INFO) {
8985                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8986                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8987                Log.v(TAG, "    Class=" + s.info.name);
8988            }
8989            final int NI = s.intents.size();
8990            int j;
8991            for (j=0; j<NI; j++) {
8992                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8993                if (DEBUG_SHOW_INFO) {
8994                    Log.v(TAG, "    IntentFilter:");
8995                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8996                }
8997                removeFilter(intent);
8998            }
8999        }
9000
9001        @Override
9002        protected boolean allowFilterResult(
9003                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9004            ServiceInfo filterSi = filter.service.info;
9005            for (int i=dest.size()-1; i>=0; i--) {
9006                ServiceInfo destAi = dest.get(i).serviceInfo;
9007                if (destAi.name == filterSi.name
9008                        && destAi.packageName == filterSi.packageName) {
9009                    return false;
9010                }
9011            }
9012            return true;
9013        }
9014
9015        @Override
9016        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9017            return new PackageParser.ServiceIntentInfo[size];
9018        }
9019
9020        @Override
9021        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9022            if (!sUserManager.exists(userId)) return true;
9023            PackageParser.Package p = filter.service.owner;
9024            if (p != null) {
9025                PackageSetting ps = (PackageSetting)p.mExtras;
9026                if (ps != null) {
9027                    // System apps are never considered stopped for purposes of
9028                    // filtering, because there may be no way for the user to
9029                    // actually re-launch them.
9030                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9031                            && ps.getStopped(userId);
9032                }
9033            }
9034            return false;
9035        }
9036
9037        @Override
9038        protected boolean isPackageForFilter(String packageName,
9039                PackageParser.ServiceIntentInfo info) {
9040            return packageName.equals(info.service.owner.packageName);
9041        }
9042
9043        @Override
9044        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9045                int match, int userId) {
9046            if (!sUserManager.exists(userId)) return null;
9047            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9048            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9049                return null;
9050            }
9051            final PackageParser.Service service = info.service;
9052            if (mSafeMode && (service.info.applicationInfo.flags
9053                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9054                return null;
9055            }
9056            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9057            if (ps == null) {
9058                return null;
9059            }
9060            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9061                    ps.readUserState(userId), userId);
9062            if (si == null) {
9063                return null;
9064            }
9065            final ResolveInfo res = new ResolveInfo();
9066            res.serviceInfo = si;
9067            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9068                res.filter = filter;
9069            }
9070            res.priority = info.getPriority();
9071            res.preferredOrder = service.owner.mPreferredOrder;
9072            res.match = match;
9073            res.isDefault = info.hasDefault;
9074            res.labelRes = info.labelRes;
9075            res.nonLocalizedLabel = info.nonLocalizedLabel;
9076            res.icon = info.icon;
9077            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9078            return res;
9079        }
9080
9081        @Override
9082        protected void sortResults(List<ResolveInfo> results) {
9083            Collections.sort(results, mResolvePrioritySorter);
9084        }
9085
9086        @Override
9087        protected void dumpFilter(PrintWriter out, String prefix,
9088                PackageParser.ServiceIntentInfo filter) {
9089            out.print(prefix); out.print(
9090                    Integer.toHexString(System.identityHashCode(filter.service)));
9091                    out.print(' ');
9092                    filter.service.printComponentShortName(out);
9093                    out.print(" filter ");
9094                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9095        }
9096
9097        @Override
9098        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9099            return filter.service;
9100        }
9101
9102        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9103            PackageParser.Service service = (PackageParser.Service)label;
9104            out.print(prefix); out.print(
9105                    Integer.toHexString(System.identityHashCode(service)));
9106                    out.print(' ');
9107                    service.printComponentShortName(out);
9108            if (count > 1) {
9109                out.print(" ("); out.print(count); out.print(" filters)");
9110            }
9111            out.println();
9112        }
9113
9114//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9115//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9116//            final List<ResolveInfo> retList = Lists.newArrayList();
9117//            while (i.hasNext()) {
9118//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9119//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9120//                    retList.add(resolveInfo);
9121//                }
9122//            }
9123//            return retList;
9124//        }
9125
9126        // Keys are String (activity class name), values are Activity.
9127        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9128                = new ArrayMap<ComponentName, PackageParser.Service>();
9129        private int mFlags;
9130    };
9131
9132    private final class ProviderIntentResolver
9133            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9134        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9135                boolean defaultOnly, int userId) {
9136            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9137            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9138        }
9139
9140        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9141                int userId) {
9142            if (!sUserManager.exists(userId))
9143                return null;
9144            mFlags = flags;
9145            return super.queryIntent(intent, resolvedType,
9146                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9147        }
9148
9149        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9150                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9151            if (!sUserManager.exists(userId))
9152                return null;
9153            if (packageProviders == null) {
9154                return null;
9155            }
9156            mFlags = flags;
9157            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9158            final int N = packageProviders.size();
9159            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9160                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9161
9162            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9163            for (int i = 0; i < N; ++i) {
9164                intentFilters = packageProviders.get(i).intents;
9165                if (intentFilters != null && intentFilters.size() > 0) {
9166                    PackageParser.ProviderIntentInfo[] array =
9167                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9168                    intentFilters.toArray(array);
9169                    listCut.add(array);
9170                }
9171            }
9172            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9173        }
9174
9175        public final void addProvider(PackageParser.Provider p) {
9176            if (mProviders.containsKey(p.getComponentName())) {
9177                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9178                return;
9179            }
9180
9181            mProviders.put(p.getComponentName(), p);
9182            if (DEBUG_SHOW_INFO) {
9183                Log.v(TAG, "  "
9184                        + (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                if (!intent.debugCheck()) {
9197                    Log.w(TAG, "==> For Provider " + p.info.name);
9198                }
9199                addFilter(intent);
9200            }
9201        }
9202
9203        public final void removeProvider(PackageParser.Provider p) {
9204            mProviders.remove(p.getComponentName());
9205            if (DEBUG_SHOW_INFO) {
9206                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9207                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9208                Log.v(TAG, "    Class=" + p.info.name);
9209            }
9210            final int NI = p.intents.size();
9211            int j;
9212            for (j = 0; j < NI; j++) {
9213                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9214                if (DEBUG_SHOW_INFO) {
9215                    Log.v(TAG, "    IntentFilter:");
9216                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9217                }
9218                removeFilter(intent);
9219            }
9220        }
9221
9222        @Override
9223        protected boolean allowFilterResult(
9224                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9225            ProviderInfo filterPi = filter.provider.info;
9226            for (int i = dest.size() - 1; i >= 0; i--) {
9227                ProviderInfo destPi = dest.get(i).providerInfo;
9228                if (destPi.name == filterPi.name
9229                        && destPi.packageName == filterPi.packageName) {
9230                    return false;
9231                }
9232            }
9233            return true;
9234        }
9235
9236        @Override
9237        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9238            return new PackageParser.ProviderIntentInfo[size];
9239        }
9240
9241        @Override
9242        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9243            if (!sUserManager.exists(userId))
9244                return true;
9245            PackageParser.Package p = filter.provider.owner;
9246            if (p != null) {
9247                PackageSetting ps = (PackageSetting) p.mExtras;
9248                if (ps != null) {
9249                    // System apps are never considered stopped for purposes of
9250                    // filtering, because there may be no way for the user to
9251                    // actually re-launch them.
9252                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9253                            && ps.getStopped(userId);
9254                }
9255            }
9256            return false;
9257        }
9258
9259        @Override
9260        protected boolean isPackageForFilter(String packageName,
9261                PackageParser.ProviderIntentInfo info) {
9262            return packageName.equals(info.provider.owner.packageName);
9263        }
9264
9265        @Override
9266        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9267                int match, int userId) {
9268            if (!sUserManager.exists(userId))
9269                return null;
9270            final PackageParser.ProviderIntentInfo info = filter;
9271            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9272                return null;
9273            }
9274            final PackageParser.Provider provider = info.provider;
9275            if (mSafeMode && (provider.info.applicationInfo.flags
9276                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9277                return null;
9278            }
9279            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9280            if (ps == null) {
9281                return null;
9282            }
9283            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9284                    ps.readUserState(userId), userId);
9285            if (pi == null) {
9286                return null;
9287            }
9288            final ResolveInfo res = new ResolveInfo();
9289            res.providerInfo = pi;
9290            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9291                res.filter = filter;
9292            }
9293            res.priority = info.getPriority();
9294            res.preferredOrder = provider.owner.mPreferredOrder;
9295            res.match = match;
9296            res.isDefault = info.hasDefault;
9297            res.labelRes = info.labelRes;
9298            res.nonLocalizedLabel = info.nonLocalizedLabel;
9299            res.icon = info.icon;
9300            res.system = res.providerInfo.applicationInfo.isSystemApp();
9301            return res;
9302        }
9303
9304        @Override
9305        protected void sortResults(List<ResolveInfo> results) {
9306            Collections.sort(results, mResolvePrioritySorter);
9307        }
9308
9309        @Override
9310        protected void dumpFilter(PrintWriter out, String prefix,
9311                PackageParser.ProviderIntentInfo filter) {
9312            out.print(prefix);
9313            out.print(
9314                    Integer.toHexString(System.identityHashCode(filter.provider)));
9315            out.print(' ');
9316            filter.provider.printComponentShortName(out);
9317            out.print(" filter ");
9318            out.println(Integer.toHexString(System.identityHashCode(filter)));
9319        }
9320
9321        @Override
9322        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9323            return filter.provider;
9324        }
9325
9326        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9327            PackageParser.Provider provider = (PackageParser.Provider)label;
9328            out.print(prefix); out.print(
9329                    Integer.toHexString(System.identityHashCode(provider)));
9330                    out.print(' ');
9331                    provider.printComponentShortName(out);
9332            if (count > 1) {
9333                out.print(" ("); out.print(count); out.print(" filters)");
9334            }
9335            out.println();
9336        }
9337
9338        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9339                = new ArrayMap<ComponentName, PackageParser.Provider>();
9340        private int mFlags;
9341    };
9342
9343    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9344            new Comparator<ResolveInfo>() {
9345        public int compare(ResolveInfo r1, ResolveInfo r2) {
9346            int v1 = r1.priority;
9347            int v2 = r2.priority;
9348            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9349            if (v1 != v2) {
9350                return (v1 > v2) ? -1 : 1;
9351            }
9352            v1 = r1.preferredOrder;
9353            v2 = r2.preferredOrder;
9354            if (v1 != v2) {
9355                return (v1 > v2) ? -1 : 1;
9356            }
9357            if (r1.isDefault != r2.isDefault) {
9358                return r1.isDefault ? -1 : 1;
9359            }
9360            v1 = r1.match;
9361            v2 = r2.match;
9362            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9363            if (v1 != v2) {
9364                return (v1 > v2) ? -1 : 1;
9365            }
9366            if (r1.system != r2.system) {
9367                return r1.system ? -1 : 1;
9368            }
9369            return 0;
9370        }
9371    };
9372
9373    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9374            new Comparator<ProviderInfo>() {
9375        public int compare(ProviderInfo p1, ProviderInfo p2) {
9376            final int v1 = p1.initOrder;
9377            final int v2 = p2.initOrder;
9378            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9379        }
9380    };
9381
9382    final void sendPackageBroadcast(final String action, final String pkg,
9383            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9384            final int[] userIds) {
9385        mHandler.post(new Runnable() {
9386            @Override
9387            public void run() {
9388                try {
9389                    final IActivityManager am = ActivityManagerNative.getDefault();
9390                    if (am == null) return;
9391                    final int[] resolvedUserIds;
9392                    if (userIds == null) {
9393                        resolvedUserIds = am.getRunningUserIds();
9394                    } else {
9395                        resolvedUserIds = userIds;
9396                    }
9397                    for (int id : resolvedUserIds) {
9398                        final Intent intent = new Intent(action,
9399                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9400                        if (extras != null) {
9401                            intent.putExtras(extras);
9402                        }
9403                        if (targetPkg != null) {
9404                            intent.setPackage(targetPkg);
9405                        }
9406                        // Modify the UID when posting to other users
9407                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9408                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9409                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9410                            intent.putExtra(Intent.EXTRA_UID, uid);
9411                        }
9412                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9413                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9414                        if (DEBUG_BROADCASTS) {
9415                            RuntimeException here = new RuntimeException("here");
9416                            here.fillInStackTrace();
9417                            Slog.d(TAG, "Sending to user " + id + ": "
9418                                    + intent.toShortString(false, true, false, false)
9419                                    + " " + intent.getExtras(), here);
9420                        }
9421                        am.broadcastIntent(null, intent, null, finishedReceiver,
9422                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9423                                null, finishedReceiver != null, false, id);
9424                    }
9425                } catch (RemoteException ex) {
9426                }
9427            }
9428        });
9429    }
9430
9431    /**
9432     * Check if the external storage media is available. This is true if there
9433     * is a mounted external storage medium or if the external storage is
9434     * emulated.
9435     */
9436    private boolean isExternalMediaAvailable() {
9437        return mMediaMounted || Environment.isExternalStorageEmulated();
9438    }
9439
9440    @Override
9441    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9442        // writer
9443        synchronized (mPackages) {
9444            if (!isExternalMediaAvailable()) {
9445                // If the external storage is no longer mounted at this point,
9446                // the caller may not have been able to delete all of this
9447                // packages files and can not delete any more.  Bail.
9448                return null;
9449            }
9450            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9451            if (lastPackage != null) {
9452                pkgs.remove(lastPackage);
9453            }
9454            if (pkgs.size() > 0) {
9455                return pkgs.get(0);
9456            }
9457        }
9458        return null;
9459    }
9460
9461    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9462        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9463                userId, andCode ? 1 : 0, packageName);
9464        if (mSystemReady) {
9465            msg.sendToTarget();
9466        } else {
9467            if (mPostSystemReadyMessages == null) {
9468                mPostSystemReadyMessages = new ArrayList<>();
9469            }
9470            mPostSystemReadyMessages.add(msg);
9471        }
9472    }
9473
9474    void startCleaningPackages() {
9475        // reader
9476        synchronized (mPackages) {
9477            if (!isExternalMediaAvailable()) {
9478                return;
9479            }
9480            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9481                return;
9482            }
9483        }
9484        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9485        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9486        IActivityManager am = ActivityManagerNative.getDefault();
9487        if (am != null) {
9488            try {
9489                am.startService(null, intent, null, mContext.getOpPackageName(),
9490                        UserHandle.USER_OWNER);
9491            } catch (RemoteException e) {
9492            }
9493        }
9494    }
9495
9496    @Override
9497    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9498            int installFlags, String installerPackageName, VerificationParams verificationParams,
9499            String packageAbiOverride) {
9500        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9501                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9502    }
9503
9504    @Override
9505    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9506            int installFlags, String installerPackageName, VerificationParams verificationParams,
9507            String packageAbiOverride, int userId) {
9508        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9509
9510        final int callingUid = Binder.getCallingUid();
9511        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9512
9513        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9514            try {
9515                if (observer != null) {
9516                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9517                }
9518            } catch (RemoteException re) {
9519            }
9520            return;
9521        }
9522
9523        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9524            installFlags |= PackageManager.INSTALL_FROM_ADB;
9525
9526        } else {
9527            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9528            // about installerPackageName.
9529
9530            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9531            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9532        }
9533
9534        UserHandle user;
9535        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9536            user = UserHandle.ALL;
9537        } else {
9538            user = new UserHandle(userId);
9539        }
9540
9541        // Only system components can circumvent runtime permissions when installing.
9542        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9543                && mContext.checkCallingOrSelfPermission(Manifest.permission
9544                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9545            throw new SecurityException("You need the "
9546                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9547                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9548        }
9549
9550        verificationParams.setInstallerUid(callingUid);
9551
9552        final File originFile = new File(originPath);
9553        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9554
9555        final Message msg = mHandler.obtainMessage(INIT_COPY);
9556        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9557                null, verificationParams, user, packageAbiOverride, null);
9558        mHandler.sendMessage(msg);
9559    }
9560
9561    void installStage(String packageName, File stagedDir, String stagedCid,
9562            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9563            String installerPackageName, int installerUid, UserHandle user) {
9564        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9565                params.referrerUri, installerUid, null);
9566        verifParams.setInstallerUid(installerUid);
9567
9568        final OriginInfo origin;
9569        if (stagedDir != null) {
9570            origin = OriginInfo.fromStagedFile(stagedDir);
9571        } else {
9572            origin = OriginInfo.fromStagedContainer(stagedCid);
9573        }
9574
9575        final Message msg = mHandler.obtainMessage(INIT_COPY);
9576        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9577                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9578                params.grantedRuntimePermissions);
9579        mHandler.sendMessage(msg);
9580    }
9581
9582    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9583        Bundle extras = new Bundle(1);
9584        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9585
9586        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9587                packageName, extras, null, null, new int[] {userId});
9588        try {
9589            IActivityManager am = ActivityManagerNative.getDefault();
9590            final boolean isSystem =
9591                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9592            if (isSystem && am.isUserRunning(userId, false)) {
9593                // The just-installed/enabled app is bundled on the system, so presumed
9594                // to be able to run automatically without needing an explicit launch.
9595                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9596                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9597                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9598                        .setPackage(packageName);
9599                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9600                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9601            }
9602        } catch (RemoteException e) {
9603            // shouldn't happen
9604            Slog.w(TAG, "Unable to bootstrap installed package", e);
9605        }
9606    }
9607
9608    @Override
9609    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9610            int userId) {
9611        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9612        PackageSetting pkgSetting;
9613        final int uid = Binder.getCallingUid();
9614        enforceCrossUserPermission(uid, userId, true, true,
9615                "setApplicationHiddenSetting for user " + userId);
9616
9617        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9618            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9619            return false;
9620        }
9621
9622        long callingId = Binder.clearCallingIdentity();
9623        try {
9624            boolean sendAdded = false;
9625            boolean sendRemoved = false;
9626            // writer
9627            synchronized (mPackages) {
9628                pkgSetting = mSettings.mPackages.get(packageName);
9629                if (pkgSetting == null) {
9630                    return false;
9631                }
9632                if (pkgSetting.getHidden(userId) != hidden) {
9633                    pkgSetting.setHidden(hidden, userId);
9634                    mSettings.writePackageRestrictionsLPr(userId);
9635                    if (hidden) {
9636                        sendRemoved = true;
9637                    } else {
9638                        sendAdded = true;
9639                    }
9640                }
9641            }
9642            if (sendAdded) {
9643                sendPackageAddedForUser(packageName, pkgSetting, userId);
9644                return true;
9645            }
9646            if (sendRemoved) {
9647                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9648                        "hiding pkg");
9649                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9650                return true;
9651            }
9652        } finally {
9653            Binder.restoreCallingIdentity(callingId);
9654        }
9655        return false;
9656    }
9657
9658    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9659            int userId) {
9660        final PackageRemovedInfo info = new PackageRemovedInfo();
9661        info.removedPackage = packageName;
9662        info.removedUsers = new int[] {userId};
9663        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9664        info.sendBroadcast(false, false, false);
9665    }
9666
9667    /**
9668     * Returns true if application is not found or there was an error. Otherwise it returns
9669     * the hidden state of the package for the given user.
9670     */
9671    @Override
9672    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9673        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9674        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9675                false, "getApplicationHidden for user " + userId);
9676        PackageSetting pkgSetting;
9677        long callingId = Binder.clearCallingIdentity();
9678        try {
9679            // writer
9680            synchronized (mPackages) {
9681                pkgSetting = mSettings.mPackages.get(packageName);
9682                if (pkgSetting == null) {
9683                    return true;
9684                }
9685                return pkgSetting.getHidden(userId);
9686            }
9687        } finally {
9688            Binder.restoreCallingIdentity(callingId);
9689        }
9690    }
9691
9692    /**
9693     * @hide
9694     */
9695    @Override
9696    public int installExistingPackageAsUser(String packageName, int userId) {
9697        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9698                null);
9699        PackageSetting pkgSetting;
9700        final int uid = Binder.getCallingUid();
9701        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9702                + userId);
9703        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9704            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9705        }
9706
9707        long callingId = Binder.clearCallingIdentity();
9708        try {
9709            boolean sendAdded = false;
9710
9711            // writer
9712            synchronized (mPackages) {
9713                pkgSetting = mSettings.mPackages.get(packageName);
9714                if (pkgSetting == null) {
9715                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9716                }
9717                if (!pkgSetting.getInstalled(userId)) {
9718                    pkgSetting.setInstalled(true, userId);
9719                    pkgSetting.setHidden(false, userId);
9720                    mSettings.writePackageRestrictionsLPr(userId);
9721                    sendAdded = true;
9722                }
9723            }
9724
9725            if (sendAdded) {
9726                sendPackageAddedForUser(packageName, pkgSetting, userId);
9727            }
9728        } finally {
9729            Binder.restoreCallingIdentity(callingId);
9730        }
9731
9732        return PackageManager.INSTALL_SUCCEEDED;
9733    }
9734
9735    boolean isUserRestricted(int userId, String restrictionKey) {
9736        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9737        if (restrictions.getBoolean(restrictionKey, false)) {
9738            Log.w(TAG, "User is restricted: " + restrictionKey);
9739            return true;
9740        }
9741        return false;
9742    }
9743
9744    @Override
9745    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9746        mContext.enforceCallingOrSelfPermission(
9747                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9748                "Only package verification agents can verify applications");
9749
9750        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9751        final PackageVerificationResponse response = new PackageVerificationResponse(
9752                verificationCode, Binder.getCallingUid());
9753        msg.arg1 = id;
9754        msg.obj = response;
9755        mHandler.sendMessage(msg);
9756    }
9757
9758    @Override
9759    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9760            long millisecondsToDelay) {
9761        mContext.enforceCallingOrSelfPermission(
9762                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9763                "Only package verification agents can extend verification timeouts");
9764
9765        final PackageVerificationState state = mPendingVerification.get(id);
9766        final PackageVerificationResponse response = new PackageVerificationResponse(
9767                verificationCodeAtTimeout, Binder.getCallingUid());
9768
9769        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9770            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9771        }
9772        if (millisecondsToDelay < 0) {
9773            millisecondsToDelay = 0;
9774        }
9775        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9776                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9777            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9778        }
9779
9780        if ((state != null) && !state.timeoutExtended()) {
9781            state.extendTimeout();
9782
9783            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9784            msg.arg1 = id;
9785            msg.obj = response;
9786            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9787        }
9788    }
9789
9790    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9791            int verificationCode, UserHandle user) {
9792        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9793        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9794        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9795        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9796        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9797
9798        mContext.sendBroadcastAsUser(intent, user,
9799                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9800    }
9801
9802    private ComponentName matchComponentForVerifier(String packageName,
9803            List<ResolveInfo> receivers) {
9804        ActivityInfo targetReceiver = null;
9805
9806        final int NR = receivers.size();
9807        for (int i = 0; i < NR; i++) {
9808            final ResolveInfo info = receivers.get(i);
9809            if (info.activityInfo == null) {
9810                continue;
9811            }
9812
9813            if (packageName.equals(info.activityInfo.packageName)) {
9814                targetReceiver = info.activityInfo;
9815                break;
9816            }
9817        }
9818
9819        if (targetReceiver == null) {
9820            return null;
9821        }
9822
9823        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9824    }
9825
9826    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9827            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9828        if (pkgInfo.verifiers.length == 0) {
9829            return null;
9830        }
9831
9832        final int N = pkgInfo.verifiers.length;
9833        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9834        for (int i = 0; i < N; i++) {
9835            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9836
9837            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9838                    receivers);
9839            if (comp == null) {
9840                continue;
9841            }
9842
9843            final int verifierUid = getUidForVerifier(verifierInfo);
9844            if (verifierUid == -1) {
9845                continue;
9846            }
9847
9848            if (DEBUG_VERIFY) {
9849                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9850                        + " with the correct signature");
9851            }
9852            sufficientVerifiers.add(comp);
9853            verificationState.addSufficientVerifier(verifierUid);
9854        }
9855
9856        return sufficientVerifiers;
9857    }
9858
9859    private int getUidForVerifier(VerifierInfo verifierInfo) {
9860        synchronized (mPackages) {
9861            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9862            if (pkg == null) {
9863                return -1;
9864            } else if (pkg.mSignatures.length != 1) {
9865                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9866                        + " has more than one signature; ignoring");
9867                return -1;
9868            }
9869
9870            /*
9871             * If the public key of the package's signature does not match
9872             * our expected public key, then this is a different package and
9873             * we should skip.
9874             */
9875
9876            final byte[] expectedPublicKey;
9877            try {
9878                final Signature verifierSig = pkg.mSignatures[0];
9879                final PublicKey publicKey = verifierSig.getPublicKey();
9880                expectedPublicKey = publicKey.getEncoded();
9881            } catch (CertificateException e) {
9882                return -1;
9883            }
9884
9885            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9886
9887            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9888                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9889                        + " does not have the expected public key; ignoring");
9890                return -1;
9891            }
9892
9893            return pkg.applicationInfo.uid;
9894        }
9895    }
9896
9897    @Override
9898    public void finishPackageInstall(int token) {
9899        enforceSystemOrRoot("Only the system is allowed to finish installs");
9900
9901        if (DEBUG_INSTALL) {
9902            Slog.v(TAG, "BM finishing package install for " + token);
9903        }
9904
9905        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9906        mHandler.sendMessage(msg);
9907    }
9908
9909    /**
9910     * Get the verification agent timeout.
9911     *
9912     * @return verification timeout in milliseconds
9913     */
9914    private long getVerificationTimeout() {
9915        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9916                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9917                DEFAULT_VERIFICATION_TIMEOUT);
9918    }
9919
9920    /**
9921     * Get the default verification agent response code.
9922     *
9923     * @return default verification response code
9924     */
9925    private int getDefaultVerificationResponse() {
9926        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9927                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9928                DEFAULT_VERIFICATION_RESPONSE);
9929    }
9930
9931    /**
9932     * Check whether or not package verification has been enabled.
9933     *
9934     * @return true if verification should be performed
9935     */
9936    private boolean isVerificationEnabled(int userId, int installFlags) {
9937        if (!DEFAULT_VERIFY_ENABLE) {
9938            return false;
9939        }
9940
9941        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9942
9943        // Check if installing from ADB
9944        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9945            // Do not run verification in a test harness environment
9946            if (ActivityManager.isRunningInTestHarness()) {
9947                return false;
9948            }
9949            if (ensureVerifyAppsEnabled) {
9950                return true;
9951            }
9952            // Check if the developer does not want package verification for ADB installs
9953            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9954                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9955                return false;
9956            }
9957        }
9958
9959        if (ensureVerifyAppsEnabled) {
9960            return true;
9961        }
9962
9963        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9964                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9965    }
9966
9967    @Override
9968    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9969            throws RemoteException {
9970        mContext.enforceCallingOrSelfPermission(
9971                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9972                "Only intentfilter verification agents can verify applications");
9973
9974        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9975        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9976                Binder.getCallingUid(), verificationCode, failedDomains);
9977        msg.arg1 = id;
9978        msg.obj = response;
9979        mHandler.sendMessage(msg);
9980    }
9981
9982    @Override
9983    public int getIntentVerificationStatus(String packageName, int userId) {
9984        synchronized (mPackages) {
9985            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9986        }
9987    }
9988
9989    @Override
9990    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9991        mContext.enforceCallingOrSelfPermission(
9992                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9993
9994        boolean result = false;
9995        synchronized (mPackages) {
9996            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9997        }
9998        if (result) {
9999            scheduleWritePackageRestrictionsLocked(userId);
10000        }
10001        return result;
10002    }
10003
10004    @Override
10005    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10006        synchronized (mPackages) {
10007            return mSettings.getIntentFilterVerificationsLPr(packageName);
10008        }
10009    }
10010
10011    @Override
10012    public List<IntentFilter> getAllIntentFilters(String packageName) {
10013        if (TextUtils.isEmpty(packageName)) {
10014            return Collections.<IntentFilter>emptyList();
10015        }
10016        synchronized (mPackages) {
10017            PackageParser.Package pkg = mPackages.get(packageName);
10018            if (pkg == null || pkg.activities == null) {
10019                return Collections.<IntentFilter>emptyList();
10020            }
10021            final int count = pkg.activities.size();
10022            ArrayList<IntentFilter> result = new ArrayList<>();
10023            for (int n=0; n<count; n++) {
10024                PackageParser.Activity activity = pkg.activities.get(n);
10025                if (activity.intents != null || activity.intents.size() > 0) {
10026                    result.addAll(activity.intents);
10027                }
10028            }
10029            return result;
10030        }
10031    }
10032
10033    @Override
10034    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10035        mContext.enforceCallingOrSelfPermission(
10036                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10037
10038        synchronized (mPackages) {
10039            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10040            if (packageName != null) {
10041                result |= updateIntentVerificationStatus(packageName,
10042                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10043                        userId);
10044                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10045                        packageName, userId);
10046            }
10047            return result;
10048        }
10049    }
10050
10051    @Override
10052    public String getDefaultBrowserPackageName(int userId) {
10053        synchronized (mPackages) {
10054            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10055        }
10056    }
10057
10058    /**
10059     * Get the "allow unknown sources" setting.
10060     *
10061     * @return the current "allow unknown sources" setting
10062     */
10063    private int getUnknownSourcesSettings() {
10064        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10065                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10066                -1);
10067    }
10068
10069    @Override
10070    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10071        final int uid = Binder.getCallingUid();
10072        // writer
10073        synchronized (mPackages) {
10074            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10075            if (targetPackageSetting == null) {
10076                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10077            }
10078
10079            PackageSetting installerPackageSetting;
10080            if (installerPackageName != null) {
10081                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10082                if (installerPackageSetting == null) {
10083                    throw new IllegalArgumentException("Unknown installer package: "
10084                            + installerPackageName);
10085                }
10086            } else {
10087                installerPackageSetting = null;
10088            }
10089
10090            Signature[] callerSignature;
10091            Object obj = mSettings.getUserIdLPr(uid);
10092            if (obj != null) {
10093                if (obj instanceof SharedUserSetting) {
10094                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10095                } else if (obj instanceof PackageSetting) {
10096                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10097                } else {
10098                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10099                }
10100            } else {
10101                throw new SecurityException("Unknown calling uid " + uid);
10102            }
10103
10104            // Verify: can't set installerPackageName to a package that is
10105            // not signed with the same cert as the caller.
10106            if (installerPackageSetting != null) {
10107                if (compareSignatures(callerSignature,
10108                        installerPackageSetting.signatures.mSignatures)
10109                        != PackageManager.SIGNATURE_MATCH) {
10110                    throw new SecurityException(
10111                            "Caller does not have same cert as new installer package "
10112                            + installerPackageName);
10113                }
10114            }
10115
10116            // Verify: if target already has an installer package, it must
10117            // be signed with the same cert as the caller.
10118            if (targetPackageSetting.installerPackageName != null) {
10119                PackageSetting setting = mSettings.mPackages.get(
10120                        targetPackageSetting.installerPackageName);
10121                // If the currently set package isn't valid, then it's always
10122                // okay to change it.
10123                if (setting != null) {
10124                    if (compareSignatures(callerSignature,
10125                            setting.signatures.mSignatures)
10126                            != PackageManager.SIGNATURE_MATCH) {
10127                        throw new SecurityException(
10128                                "Caller does not have same cert as old installer package "
10129                                + targetPackageSetting.installerPackageName);
10130                    }
10131                }
10132            }
10133
10134            // Okay!
10135            targetPackageSetting.installerPackageName = installerPackageName;
10136            scheduleWriteSettingsLocked();
10137        }
10138    }
10139
10140    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10141        // Queue up an async operation since the package installation may take a little while.
10142        mHandler.post(new Runnable() {
10143            public void run() {
10144                mHandler.removeCallbacks(this);
10145                 // Result object to be returned
10146                PackageInstalledInfo res = new PackageInstalledInfo();
10147                res.returnCode = currentStatus;
10148                res.uid = -1;
10149                res.pkg = null;
10150                res.removedInfo = new PackageRemovedInfo();
10151                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10152                    args.doPreInstall(res.returnCode);
10153                    synchronized (mInstallLock) {
10154                        installPackageLI(args, res);
10155                    }
10156                    args.doPostInstall(res.returnCode, res.uid);
10157                }
10158
10159                // A restore should be performed at this point if (a) the install
10160                // succeeded, (b) the operation is not an update, and (c) the new
10161                // package has not opted out of backup participation.
10162                final boolean update = res.removedInfo.removedPackage != null;
10163                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10164                boolean doRestore = !update
10165                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10166
10167                // Set up the post-install work request bookkeeping.  This will be used
10168                // and cleaned up by the post-install event handling regardless of whether
10169                // there's a restore pass performed.  Token values are >= 1.
10170                int token;
10171                if (mNextInstallToken < 0) mNextInstallToken = 1;
10172                token = mNextInstallToken++;
10173
10174                PostInstallData data = new PostInstallData(args, res);
10175                mRunningInstalls.put(token, data);
10176                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10177
10178                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10179                    // Pass responsibility to the Backup Manager.  It will perform a
10180                    // restore if appropriate, then pass responsibility back to the
10181                    // Package Manager to run the post-install observer callbacks
10182                    // and broadcasts.
10183                    IBackupManager bm = IBackupManager.Stub.asInterface(
10184                            ServiceManager.getService(Context.BACKUP_SERVICE));
10185                    if (bm != null) {
10186                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10187                                + " to BM for possible restore");
10188                        try {
10189                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10190                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10191                            } else {
10192                                doRestore = false;
10193                            }
10194                        } catch (RemoteException e) {
10195                            // can't happen; the backup manager is local
10196                        } catch (Exception e) {
10197                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10198                            doRestore = false;
10199                        }
10200                    } else {
10201                        Slog.e(TAG, "Backup Manager not found!");
10202                        doRestore = false;
10203                    }
10204                }
10205
10206                if (!doRestore) {
10207                    // No restore possible, or the Backup Manager was mysteriously not
10208                    // available -- just fire the post-install work request directly.
10209                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10210                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10211                    mHandler.sendMessage(msg);
10212                }
10213            }
10214        });
10215    }
10216
10217    private abstract class HandlerParams {
10218        private static final int MAX_RETRIES = 4;
10219
10220        /**
10221         * Number of times startCopy() has been attempted and had a non-fatal
10222         * error.
10223         */
10224        private int mRetries = 0;
10225
10226        /** User handle for the user requesting the information or installation. */
10227        private final UserHandle mUser;
10228
10229        HandlerParams(UserHandle user) {
10230            mUser = user;
10231        }
10232
10233        UserHandle getUser() {
10234            return mUser;
10235        }
10236
10237        final boolean startCopy() {
10238            boolean res;
10239            try {
10240                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10241
10242                if (++mRetries > MAX_RETRIES) {
10243                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10244                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10245                    handleServiceError();
10246                    return false;
10247                } else {
10248                    handleStartCopy();
10249                    res = true;
10250                }
10251            } catch (RemoteException e) {
10252                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10253                mHandler.sendEmptyMessage(MCS_RECONNECT);
10254                res = false;
10255            }
10256            handleReturnCode();
10257            return res;
10258        }
10259
10260        final void serviceError() {
10261            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10262            handleServiceError();
10263            handleReturnCode();
10264        }
10265
10266        abstract void handleStartCopy() throws RemoteException;
10267        abstract void handleServiceError();
10268        abstract void handleReturnCode();
10269    }
10270
10271    class MeasureParams extends HandlerParams {
10272        private final PackageStats mStats;
10273        private boolean mSuccess;
10274
10275        private final IPackageStatsObserver mObserver;
10276
10277        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10278            super(new UserHandle(stats.userHandle));
10279            mObserver = observer;
10280            mStats = stats;
10281        }
10282
10283        @Override
10284        public String toString() {
10285            return "MeasureParams{"
10286                + Integer.toHexString(System.identityHashCode(this))
10287                + " " + mStats.packageName + "}";
10288        }
10289
10290        @Override
10291        void handleStartCopy() throws RemoteException {
10292            synchronized (mInstallLock) {
10293                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10294            }
10295
10296            if (mSuccess) {
10297                final boolean mounted;
10298                if (Environment.isExternalStorageEmulated()) {
10299                    mounted = true;
10300                } else {
10301                    final String status = Environment.getExternalStorageState();
10302                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10303                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10304                }
10305
10306                if (mounted) {
10307                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10308
10309                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10310                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10311
10312                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10313                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10314
10315                    // Always subtract cache size, since it's a subdirectory
10316                    mStats.externalDataSize -= mStats.externalCacheSize;
10317
10318                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10319                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10320
10321                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10322                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10323                }
10324            }
10325        }
10326
10327        @Override
10328        void handleReturnCode() {
10329            if (mObserver != null) {
10330                try {
10331                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10332                } catch (RemoteException e) {
10333                    Slog.i(TAG, "Observer no longer exists.");
10334                }
10335            }
10336        }
10337
10338        @Override
10339        void handleServiceError() {
10340            Slog.e(TAG, "Could not measure application " + mStats.packageName
10341                            + " external storage");
10342        }
10343    }
10344
10345    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10346            throws RemoteException {
10347        long result = 0;
10348        for (File path : paths) {
10349            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10350        }
10351        return result;
10352    }
10353
10354    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10355        for (File path : paths) {
10356            try {
10357                mcs.clearDirectory(path.getAbsolutePath());
10358            } catch (RemoteException e) {
10359            }
10360        }
10361    }
10362
10363    static class OriginInfo {
10364        /**
10365         * Location where install is coming from, before it has been
10366         * copied/renamed into place. This could be a single monolithic APK
10367         * file, or a cluster directory. This location may be untrusted.
10368         */
10369        final File file;
10370        final String cid;
10371
10372        /**
10373         * Flag indicating that {@link #file} or {@link #cid} has already been
10374         * staged, meaning downstream users don't need to defensively copy the
10375         * contents.
10376         */
10377        final boolean staged;
10378
10379        /**
10380         * Flag indicating that {@link #file} or {@link #cid} is an already
10381         * installed app that is being moved.
10382         */
10383        final boolean existing;
10384
10385        final String resolvedPath;
10386        final File resolvedFile;
10387
10388        static OriginInfo fromNothing() {
10389            return new OriginInfo(null, null, false, false);
10390        }
10391
10392        static OriginInfo fromUntrustedFile(File file) {
10393            return new OriginInfo(file, null, false, false);
10394        }
10395
10396        static OriginInfo fromExistingFile(File file) {
10397            return new OriginInfo(file, null, false, true);
10398        }
10399
10400        static OriginInfo fromStagedFile(File file) {
10401            return new OriginInfo(file, null, true, false);
10402        }
10403
10404        static OriginInfo fromStagedContainer(String cid) {
10405            return new OriginInfo(null, cid, true, false);
10406        }
10407
10408        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10409            this.file = file;
10410            this.cid = cid;
10411            this.staged = staged;
10412            this.existing = existing;
10413
10414            if (cid != null) {
10415                resolvedPath = PackageHelper.getSdDir(cid);
10416                resolvedFile = new File(resolvedPath);
10417            } else if (file != null) {
10418                resolvedPath = file.getAbsolutePath();
10419                resolvedFile = file;
10420            } else {
10421                resolvedPath = null;
10422                resolvedFile = null;
10423            }
10424        }
10425    }
10426
10427    class MoveInfo {
10428        final int moveId;
10429        final String fromUuid;
10430        final String toUuid;
10431        final String packageName;
10432        final String dataAppName;
10433        final int appId;
10434        final String seinfo;
10435
10436        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10437                String dataAppName, int appId, String seinfo) {
10438            this.moveId = moveId;
10439            this.fromUuid = fromUuid;
10440            this.toUuid = toUuid;
10441            this.packageName = packageName;
10442            this.dataAppName = dataAppName;
10443            this.appId = appId;
10444            this.seinfo = seinfo;
10445        }
10446    }
10447
10448    class InstallParams extends HandlerParams {
10449        final OriginInfo origin;
10450        final MoveInfo move;
10451        final IPackageInstallObserver2 observer;
10452        int installFlags;
10453        final String installerPackageName;
10454        final String volumeUuid;
10455        final VerificationParams verificationParams;
10456        private InstallArgs mArgs;
10457        private int mRet;
10458        final String packageAbiOverride;
10459        final String[] grantedRuntimePermissions;
10460
10461
10462        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10463                int installFlags, String installerPackageName, String volumeUuid,
10464                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10465                String[] grantedPermissions) {
10466            super(user);
10467            this.origin = origin;
10468            this.move = move;
10469            this.observer = observer;
10470            this.installFlags = installFlags;
10471            this.installerPackageName = installerPackageName;
10472            this.volumeUuid = volumeUuid;
10473            this.verificationParams = verificationParams;
10474            this.packageAbiOverride = packageAbiOverride;
10475            this.grantedRuntimePermissions = grantedPermissions;
10476        }
10477
10478        @Override
10479        public String toString() {
10480            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10481                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10482        }
10483
10484        public ManifestDigest getManifestDigest() {
10485            if (verificationParams == null) {
10486                return null;
10487            }
10488            return verificationParams.getManifestDigest();
10489        }
10490
10491        private int installLocationPolicy(PackageInfoLite pkgLite) {
10492            String packageName = pkgLite.packageName;
10493            int installLocation = pkgLite.installLocation;
10494            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10495            // reader
10496            synchronized (mPackages) {
10497                PackageParser.Package pkg = mPackages.get(packageName);
10498                if (pkg != null) {
10499                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10500                        // Check for downgrading.
10501                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10502                            try {
10503                                checkDowngrade(pkg, pkgLite);
10504                            } catch (PackageManagerException e) {
10505                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10506                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10507                            }
10508                        }
10509                        // Check for updated system application.
10510                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10511                            if (onSd) {
10512                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10513                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10514                            }
10515                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10516                        } else {
10517                            if (onSd) {
10518                                // Install flag overrides everything.
10519                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10520                            }
10521                            // If current upgrade specifies particular preference
10522                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10523                                // Application explicitly specified internal.
10524                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10525                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10526                                // App explictly prefers external. Let policy decide
10527                            } else {
10528                                // Prefer previous location
10529                                if (isExternal(pkg)) {
10530                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10531                                }
10532                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10533                            }
10534                        }
10535                    } else {
10536                        // Invalid install. Return error code
10537                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10538                    }
10539                }
10540            }
10541            // All the special cases have been taken care of.
10542            // Return result based on recommended install location.
10543            if (onSd) {
10544                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10545            }
10546            return pkgLite.recommendedInstallLocation;
10547        }
10548
10549        /*
10550         * Invoke remote method to get package information and install
10551         * location values. Override install location based on default
10552         * policy if needed and then create install arguments based
10553         * on the install location.
10554         */
10555        public void handleStartCopy() throws RemoteException {
10556            int ret = PackageManager.INSTALL_SUCCEEDED;
10557
10558            // If we're already staged, we've firmly committed to an install location
10559            if (origin.staged) {
10560                if (origin.file != null) {
10561                    installFlags |= PackageManager.INSTALL_INTERNAL;
10562                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10563                } else if (origin.cid != null) {
10564                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10565                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10566                } else {
10567                    throw new IllegalStateException("Invalid stage location");
10568                }
10569            }
10570
10571            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10572            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10573
10574            PackageInfoLite pkgLite = null;
10575
10576            if (onInt && onSd) {
10577                // Check if both bits are set.
10578                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10579                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10580            } else {
10581                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10582                        packageAbiOverride);
10583
10584                /*
10585                 * If we have too little free space, try to free cache
10586                 * before giving up.
10587                 */
10588                if (!origin.staged && pkgLite.recommendedInstallLocation
10589                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10590                    // TODO: focus freeing disk space on the target device
10591                    final StorageManager storage = StorageManager.from(mContext);
10592                    final long lowThreshold = storage.getStorageLowBytes(
10593                            Environment.getDataDirectory());
10594
10595                    final long sizeBytes = mContainerService.calculateInstalledSize(
10596                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10597
10598                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10599                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10600                                installFlags, packageAbiOverride);
10601                    }
10602
10603                    /*
10604                     * The cache free must have deleted the file we
10605                     * downloaded to install.
10606                     *
10607                     * TODO: fix the "freeCache" call to not delete
10608                     *       the file we care about.
10609                     */
10610                    if (pkgLite.recommendedInstallLocation
10611                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10612                        pkgLite.recommendedInstallLocation
10613                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10614                    }
10615                }
10616            }
10617
10618            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10619                int loc = pkgLite.recommendedInstallLocation;
10620                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10621                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10622                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10623                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10624                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10625                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10626                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10627                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10628                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10629                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10630                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10631                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10632                } else {
10633                    // Override with defaults if needed.
10634                    loc = installLocationPolicy(pkgLite);
10635                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10636                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10637                    } else if (!onSd && !onInt) {
10638                        // Override install location with flags
10639                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10640                            // Set the flag to install on external media.
10641                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10642                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10643                        } else {
10644                            // Make sure the flag for installing on external
10645                            // media is unset
10646                            installFlags |= PackageManager.INSTALL_INTERNAL;
10647                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10648                        }
10649                    }
10650                }
10651            }
10652
10653            final InstallArgs args = createInstallArgs(this);
10654            mArgs = args;
10655
10656            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10657                 /*
10658                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10659                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10660                 */
10661                int userIdentifier = getUser().getIdentifier();
10662                if (userIdentifier == UserHandle.USER_ALL
10663                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10664                    userIdentifier = UserHandle.USER_OWNER;
10665                }
10666
10667                /*
10668                 * Determine if we have any installed package verifiers. If we
10669                 * do, then we'll defer to them to verify the packages.
10670                 */
10671                final int requiredUid = mRequiredVerifierPackage == null ? -1
10672                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10673                if (!origin.existing && requiredUid != -1
10674                        && isVerificationEnabled(userIdentifier, installFlags)) {
10675                    final Intent verification = new Intent(
10676                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10677                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10678                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10679                            PACKAGE_MIME_TYPE);
10680                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10681
10682                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10683                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10684                            0 /* TODO: Which userId? */);
10685
10686                    if (DEBUG_VERIFY) {
10687                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10688                                + verification.toString() + " with " + pkgLite.verifiers.length
10689                                + " optional verifiers");
10690                    }
10691
10692                    final int verificationId = mPendingVerificationToken++;
10693
10694                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10695
10696                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10697                            installerPackageName);
10698
10699                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10700                            installFlags);
10701
10702                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10703                            pkgLite.packageName);
10704
10705                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10706                            pkgLite.versionCode);
10707
10708                    if (verificationParams != null) {
10709                        if (verificationParams.getVerificationURI() != null) {
10710                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10711                                 verificationParams.getVerificationURI());
10712                        }
10713                        if (verificationParams.getOriginatingURI() != null) {
10714                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10715                                  verificationParams.getOriginatingURI());
10716                        }
10717                        if (verificationParams.getReferrer() != null) {
10718                            verification.putExtra(Intent.EXTRA_REFERRER,
10719                                  verificationParams.getReferrer());
10720                        }
10721                        if (verificationParams.getOriginatingUid() >= 0) {
10722                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10723                                  verificationParams.getOriginatingUid());
10724                        }
10725                        if (verificationParams.getInstallerUid() >= 0) {
10726                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10727                                  verificationParams.getInstallerUid());
10728                        }
10729                    }
10730
10731                    final PackageVerificationState verificationState = new PackageVerificationState(
10732                            requiredUid, args);
10733
10734                    mPendingVerification.append(verificationId, verificationState);
10735
10736                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10737                            receivers, verificationState);
10738
10739                    // Apps installed for "all" users use the device owner to verify the app
10740                    UserHandle verifierUser = getUser();
10741                    if (verifierUser == UserHandle.ALL) {
10742                        verifierUser = UserHandle.OWNER;
10743                    }
10744
10745                    /*
10746                     * If any sufficient verifiers were listed in the package
10747                     * manifest, attempt to ask them.
10748                     */
10749                    if (sufficientVerifiers != null) {
10750                        final int N = sufficientVerifiers.size();
10751                        if (N == 0) {
10752                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10753                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10754                        } else {
10755                            for (int i = 0; i < N; i++) {
10756                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10757
10758                                final Intent sufficientIntent = new Intent(verification);
10759                                sufficientIntent.setComponent(verifierComponent);
10760                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10761                            }
10762                        }
10763                    }
10764
10765                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10766                            mRequiredVerifierPackage, receivers);
10767                    if (ret == PackageManager.INSTALL_SUCCEEDED
10768                            && mRequiredVerifierPackage != null) {
10769                        /*
10770                         * Send the intent to the required verification agent,
10771                         * but only start the verification timeout after the
10772                         * target BroadcastReceivers have run.
10773                         */
10774                        verification.setComponent(requiredVerifierComponent);
10775                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10776                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10777                                new BroadcastReceiver() {
10778                                    @Override
10779                                    public void onReceive(Context context, Intent intent) {
10780                                        final Message msg = mHandler
10781                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10782                                        msg.arg1 = verificationId;
10783                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10784                                    }
10785                                }, null, 0, null, null);
10786
10787                        /*
10788                         * We don't want the copy to proceed until verification
10789                         * succeeds, so null out this field.
10790                         */
10791                        mArgs = null;
10792                    }
10793                } else {
10794                    /*
10795                     * No package verification is enabled, so immediately start
10796                     * the remote call to initiate copy using temporary file.
10797                     */
10798                    ret = args.copyApk(mContainerService, true);
10799                }
10800            }
10801
10802            mRet = ret;
10803        }
10804
10805        @Override
10806        void handleReturnCode() {
10807            // If mArgs is null, then MCS couldn't be reached. When it
10808            // reconnects, it will try again to install. At that point, this
10809            // will succeed.
10810            if (mArgs != null) {
10811                processPendingInstall(mArgs, mRet);
10812            }
10813        }
10814
10815        @Override
10816        void handleServiceError() {
10817            mArgs = createInstallArgs(this);
10818            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10819        }
10820
10821        public boolean isForwardLocked() {
10822            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10823        }
10824    }
10825
10826    /**
10827     * Used during creation of InstallArgs
10828     *
10829     * @param installFlags package installation flags
10830     * @return true if should be installed on external storage
10831     */
10832    private static boolean installOnExternalAsec(int installFlags) {
10833        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10834            return false;
10835        }
10836        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10837            return true;
10838        }
10839        return false;
10840    }
10841
10842    /**
10843     * Used during creation of InstallArgs
10844     *
10845     * @param installFlags package installation flags
10846     * @return true if should be installed as forward locked
10847     */
10848    private static boolean installForwardLocked(int installFlags) {
10849        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10850    }
10851
10852    private InstallArgs createInstallArgs(InstallParams params) {
10853        if (params.move != null) {
10854            return new MoveInstallArgs(params);
10855        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10856            return new AsecInstallArgs(params);
10857        } else {
10858            return new FileInstallArgs(params);
10859        }
10860    }
10861
10862    /**
10863     * Create args that describe an existing installed package. Typically used
10864     * when cleaning up old installs, or used as a move source.
10865     */
10866    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10867            String resourcePath, String[] instructionSets) {
10868        final boolean isInAsec;
10869        if (installOnExternalAsec(installFlags)) {
10870            /* Apps on SD card are always in ASEC containers. */
10871            isInAsec = true;
10872        } else if (installForwardLocked(installFlags)
10873                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10874            /*
10875             * Forward-locked apps are only in ASEC containers if they're the
10876             * new style
10877             */
10878            isInAsec = true;
10879        } else {
10880            isInAsec = false;
10881        }
10882
10883        if (isInAsec) {
10884            return new AsecInstallArgs(codePath, instructionSets,
10885                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10886        } else {
10887            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10888        }
10889    }
10890
10891    static abstract class InstallArgs {
10892        /** @see InstallParams#origin */
10893        final OriginInfo origin;
10894        /** @see InstallParams#move */
10895        final MoveInfo move;
10896
10897        final IPackageInstallObserver2 observer;
10898        // Always refers to PackageManager flags only
10899        final int installFlags;
10900        final String installerPackageName;
10901        final String volumeUuid;
10902        final ManifestDigest manifestDigest;
10903        final UserHandle user;
10904        final String abiOverride;
10905        final String[] installGrantPermissions;
10906
10907        // The list of instruction sets supported by this app. This is currently
10908        // only used during the rmdex() phase to clean up resources. We can get rid of this
10909        // if we move dex files under the common app path.
10910        /* nullable */ String[] instructionSets;
10911
10912        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10913                int installFlags, String installerPackageName, String volumeUuid,
10914                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10915                String abiOverride, String[] installGrantPermissions) {
10916            this.origin = origin;
10917            this.move = move;
10918            this.installFlags = installFlags;
10919            this.observer = observer;
10920            this.installerPackageName = installerPackageName;
10921            this.volumeUuid = volumeUuid;
10922            this.manifestDigest = manifestDigest;
10923            this.user = user;
10924            this.instructionSets = instructionSets;
10925            this.abiOverride = abiOverride;
10926            this.installGrantPermissions = installGrantPermissions;
10927        }
10928
10929        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10930        abstract int doPreInstall(int status);
10931
10932        /**
10933         * Rename package into final resting place. All paths on the given
10934         * scanned package should be updated to reflect the rename.
10935         */
10936        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10937        abstract int doPostInstall(int status, int uid);
10938
10939        /** @see PackageSettingBase#codePathString */
10940        abstract String getCodePath();
10941        /** @see PackageSettingBase#resourcePathString */
10942        abstract String getResourcePath();
10943
10944        // Need installer lock especially for dex file removal.
10945        abstract void cleanUpResourcesLI();
10946        abstract boolean doPostDeleteLI(boolean delete);
10947
10948        /**
10949         * Called before the source arguments are copied. This is used mostly
10950         * for MoveParams when it needs to read the source file to put it in the
10951         * destination.
10952         */
10953        int doPreCopy() {
10954            return PackageManager.INSTALL_SUCCEEDED;
10955        }
10956
10957        /**
10958         * Called after the source arguments are copied. This is used mostly for
10959         * MoveParams when it needs to read the source file to put it in the
10960         * destination.
10961         *
10962         * @return
10963         */
10964        int doPostCopy(int uid) {
10965            return PackageManager.INSTALL_SUCCEEDED;
10966        }
10967
10968        protected boolean isFwdLocked() {
10969            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10970        }
10971
10972        protected boolean isExternalAsec() {
10973            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10974        }
10975
10976        UserHandle getUser() {
10977            return user;
10978        }
10979    }
10980
10981    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10982        if (!allCodePaths.isEmpty()) {
10983            if (instructionSets == null) {
10984                throw new IllegalStateException("instructionSet == null");
10985            }
10986            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10987            for (String codePath : allCodePaths) {
10988                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10989                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10990                    if (retCode < 0) {
10991                        Slog.w(TAG, "Couldn't remove dex file for package: "
10992                                + " at location " + codePath + ", retcode=" + retCode);
10993                        // we don't consider this to be a failure of the core package deletion
10994                    }
10995                }
10996            }
10997        }
10998    }
10999
11000    /**
11001     * Logic to handle installation of non-ASEC applications, including copying
11002     * and renaming logic.
11003     */
11004    class FileInstallArgs extends InstallArgs {
11005        private File codeFile;
11006        private File resourceFile;
11007
11008        // Example topology:
11009        // /data/app/com.example/base.apk
11010        // /data/app/com.example/split_foo.apk
11011        // /data/app/com.example/lib/arm/libfoo.so
11012        // /data/app/com.example/lib/arm64/libfoo.so
11013        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11014
11015        /** New install */
11016        FileInstallArgs(InstallParams params) {
11017            super(params.origin, params.move, params.observer, params.installFlags,
11018                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11019                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11020                    params.grantedRuntimePermissions);
11021            if (isFwdLocked()) {
11022                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11023            }
11024        }
11025
11026        /** Existing install */
11027        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11028            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11029                    null, null);
11030            this.codeFile = (codePath != null) ? new File(codePath) : null;
11031            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11032        }
11033
11034        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11035            if (origin.staged) {
11036                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11037                codeFile = origin.file;
11038                resourceFile = origin.file;
11039                return PackageManager.INSTALL_SUCCEEDED;
11040            }
11041
11042            try {
11043                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11044                codeFile = tempDir;
11045                resourceFile = tempDir;
11046            } catch (IOException e) {
11047                Slog.w(TAG, "Failed to create copy file: " + e);
11048                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11049            }
11050
11051            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11052                @Override
11053                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11054                    if (!FileUtils.isValidExtFilename(name)) {
11055                        throw new IllegalArgumentException("Invalid filename: " + name);
11056                    }
11057                    try {
11058                        final File file = new File(codeFile, name);
11059                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11060                                O_RDWR | O_CREAT, 0644);
11061                        Os.chmod(file.getAbsolutePath(), 0644);
11062                        return new ParcelFileDescriptor(fd);
11063                    } catch (ErrnoException e) {
11064                        throw new RemoteException("Failed to open: " + e.getMessage());
11065                    }
11066                }
11067            };
11068
11069            int ret = PackageManager.INSTALL_SUCCEEDED;
11070            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11071            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11072                Slog.e(TAG, "Failed to copy package");
11073                return ret;
11074            }
11075
11076            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11077            NativeLibraryHelper.Handle handle = null;
11078            try {
11079                handle = NativeLibraryHelper.Handle.create(codeFile);
11080                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11081                        abiOverride);
11082            } catch (IOException e) {
11083                Slog.e(TAG, "Copying native libraries failed", e);
11084                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11085            } finally {
11086                IoUtils.closeQuietly(handle);
11087            }
11088
11089            return ret;
11090        }
11091
11092        int doPreInstall(int status) {
11093            if (status != PackageManager.INSTALL_SUCCEEDED) {
11094                cleanUp();
11095            }
11096            return status;
11097        }
11098
11099        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11100            if (status != PackageManager.INSTALL_SUCCEEDED) {
11101                cleanUp();
11102                return false;
11103            }
11104
11105            final File targetDir = codeFile.getParentFile();
11106            final File beforeCodeFile = codeFile;
11107            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11108
11109            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11110            try {
11111                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11112            } catch (ErrnoException e) {
11113                Slog.w(TAG, "Failed to rename", e);
11114                return false;
11115            }
11116
11117            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11118                Slog.w(TAG, "Failed to restorecon");
11119                return false;
11120            }
11121
11122            // Reflect the rename internally
11123            codeFile = afterCodeFile;
11124            resourceFile = afterCodeFile;
11125
11126            // Reflect the rename in scanned details
11127            pkg.codePath = afterCodeFile.getAbsolutePath();
11128            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11129                    pkg.baseCodePath);
11130            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11131                    pkg.splitCodePaths);
11132
11133            // Reflect the rename in app info
11134            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11135            pkg.applicationInfo.setCodePath(pkg.codePath);
11136            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11137            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11138            pkg.applicationInfo.setResourcePath(pkg.codePath);
11139            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11140            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11141
11142            return true;
11143        }
11144
11145        int doPostInstall(int status, int uid) {
11146            if (status != PackageManager.INSTALL_SUCCEEDED) {
11147                cleanUp();
11148            }
11149            return status;
11150        }
11151
11152        @Override
11153        String getCodePath() {
11154            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11155        }
11156
11157        @Override
11158        String getResourcePath() {
11159            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11160        }
11161
11162        private boolean cleanUp() {
11163            if (codeFile == null || !codeFile.exists()) {
11164                return false;
11165            }
11166
11167            if (codeFile.isDirectory()) {
11168                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11169            } else {
11170                codeFile.delete();
11171            }
11172
11173            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11174                resourceFile.delete();
11175            }
11176
11177            return true;
11178        }
11179
11180        void cleanUpResourcesLI() {
11181            // Try enumerating all code paths before deleting
11182            List<String> allCodePaths = Collections.EMPTY_LIST;
11183            if (codeFile != null && codeFile.exists()) {
11184                try {
11185                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11186                    allCodePaths = pkg.getAllCodePaths();
11187                } catch (PackageParserException e) {
11188                    // Ignored; we tried our best
11189                }
11190            }
11191
11192            cleanUp();
11193            removeDexFiles(allCodePaths, instructionSets);
11194        }
11195
11196        boolean doPostDeleteLI(boolean delete) {
11197            // XXX err, shouldn't we respect the delete flag?
11198            cleanUpResourcesLI();
11199            return true;
11200        }
11201    }
11202
11203    private boolean isAsecExternal(String cid) {
11204        final String asecPath = PackageHelper.getSdFilesystem(cid);
11205        return !asecPath.startsWith(mAsecInternalPath);
11206    }
11207
11208    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11209            PackageManagerException {
11210        if (copyRet < 0) {
11211            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11212                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11213                throw new PackageManagerException(copyRet, message);
11214            }
11215        }
11216    }
11217
11218    /**
11219     * Extract the MountService "container ID" from the full code path of an
11220     * .apk.
11221     */
11222    static String cidFromCodePath(String fullCodePath) {
11223        int eidx = fullCodePath.lastIndexOf("/");
11224        String subStr1 = fullCodePath.substring(0, eidx);
11225        int sidx = subStr1.lastIndexOf("/");
11226        return subStr1.substring(sidx+1, eidx);
11227    }
11228
11229    /**
11230     * Logic to handle installation of ASEC applications, including copying and
11231     * renaming logic.
11232     */
11233    class AsecInstallArgs extends InstallArgs {
11234        static final String RES_FILE_NAME = "pkg.apk";
11235        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11236
11237        String cid;
11238        String packagePath;
11239        String resourcePath;
11240
11241        /** New install */
11242        AsecInstallArgs(InstallParams params) {
11243            super(params.origin, params.move, params.observer, params.installFlags,
11244                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11245                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11246                    params.grantedRuntimePermissions);
11247        }
11248
11249        /** Existing install */
11250        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11251                        boolean isExternal, boolean isForwardLocked) {
11252            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11253                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11254                    instructionSets, null, null);
11255            // Hackily pretend we're still looking at a full code path
11256            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11257                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11258            }
11259
11260            // Extract cid from fullCodePath
11261            int eidx = fullCodePath.lastIndexOf("/");
11262            String subStr1 = fullCodePath.substring(0, eidx);
11263            int sidx = subStr1.lastIndexOf("/");
11264            cid = subStr1.substring(sidx+1, eidx);
11265            setMountPath(subStr1);
11266        }
11267
11268        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11269            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11270                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11271                    instructionSets, null, null);
11272            this.cid = cid;
11273            setMountPath(PackageHelper.getSdDir(cid));
11274        }
11275
11276        void createCopyFile() {
11277            cid = mInstallerService.allocateExternalStageCidLegacy();
11278        }
11279
11280        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11281            if (origin.staged) {
11282                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11283                cid = origin.cid;
11284                setMountPath(PackageHelper.getSdDir(cid));
11285                return PackageManager.INSTALL_SUCCEEDED;
11286            }
11287
11288            if (temp) {
11289                createCopyFile();
11290            } else {
11291                /*
11292                 * Pre-emptively destroy the container since it's destroyed if
11293                 * copying fails due to it existing anyway.
11294                 */
11295                PackageHelper.destroySdDir(cid);
11296            }
11297
11298            final String newMountPath = imcs.copyPackageToContainer(
11299                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11300                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11301
11302            if (newMountPath != null) {
11303                setMountPath(newMountPath);
11304                return PackageManager.INSTALL_SUCCEEDED;
11305            } else {
11306                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11307            }
11308        }
11309
11310        @Override
11311        String getCodePath() {
11312            return packagePath;
11313        }
11314
11315        @Override
11316        String getResourcePath() {
11317            return resourcePath;
11318        }
11319
11320        int doPreInstall(int status) {
11321            if (status != PackageManager.INSTALL_SUCCEEDED) {
11322                // Destroy container
11323                PackageHelper.destroySdDir(cid);
11324            } else {
11325                boolean mounted = PackageHelper.isContainerMounted(cid);
11326                if (!mounted) {
11327                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11328                            Process.SYSTEM_UID);
11329                    if (newMountPath != null) {
11330                        setMountPath(newMountPath);
11331                    } else {
11332                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11333                    }
11334                }
11335            }
11336            return status;
11337        }
11338
11339        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11340            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11341            String newMountPath = null;
11342            if (PackageHelper.isContainerMounted(cid)) {
11343                // Unmount the container
11344                if (!PackageHelper.unMountSdDir(cid)) {
11345                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11346                    return false;
11347                }
11348            }
11349            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11350                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11351                        " which might be stale. Will try to clean up.");
11352                // Clean up the stale container and proceed to recreate.
11353                if (!PackageHelper.destroySdDir(newCacheId)) {
11354                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11355                    return false;
11356                }
11357                // Successfully cleaned up stale container. Try to rename again.
11358                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11359                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11360                            + " inspite of cleaning it up.");
11361                    return false;
11362                }
11363            }
11364            if (!PackageHelper.isContainerMounted(newCacheId)) {
11365                Slog.w(TAG, "Mounting container " + newCacheId);
11366                newMountPath = PackageHelper.mountSdDir(newCacheId,
11367                        getEncryptKey(), Process.SYSTEM_UID);
11368            } else {
11369                newMountPath = PackageHelper.getSdDir(newCacheId);
11370            }
11371            if (newMountPath == null) {
11372                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11373                return false;
11374            }
11375            Log.i(TAG, "Succesfully renamed " + cid +
11376                    " to " + newCacheId +
11377                    " at new path: " + newMountPath);
11378            cid = newCacheId;
11379
11380            final File beforeCodeFile = new File(packagePath);
11381            setMountPath(newMountPath);
11382            final File afterCodeFile = new File(packagePath);
11383
11384            // Reflect the rename in scanned details
11385            pkg.codePath = afterCodeFile.getAbsolutePath();
11386            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11387                    pkg.baseCodePath);
11388            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11389                    pkg.splitCodePaths);
11390
11391            // Reflect the rename in app info
11392            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11393            pkg.applicationInfo.setCodePath(pkg.codePath);
11394            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11395            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11396            pkg.applicationInfo.setResourcePath(pkg.codePath);
11397            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11398            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11399
11400            return true;
11401        }
11402
11403        private void setMountPath(String mountPath) {
11404            final File mountFile = new File(mountPath);
11405
11406            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11407            if (monolithicFile.exists()) {
11408                packagePath = monolithicFile.getAbsolutePath();
11409                if (isFwdLocked()) {
11410                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11411                } else {
11412                    resourcePath = packagePath;
11413                }
11414            } else {
11415                packagePath = mountFile.getAbsolutePath();
11416                resourcePath = packagePath;
11417            }
11418        }
11419
11420        int doPostInstall(int status, int uid) {
11421            if (status != PackageManager.INSTALL_SUCCEEDED) {
11422                cleanUp();
11423            } else {
11424                final int groupOwner;
11425                final String protectedFile;
11426                if (isFwdLocked()) {
11427                    groupOwner = UserHandle.getSharedAppGid(uid);
11428                    protectedFile = RES_FILE_NAME;
11429                } else {
11430                    groupOwner = -1;
11431                    protectedFile = null;
11432                }
11433
11434                if (uid < Process.FIRST_APPLICATION_UID
11435                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11436                    Slog.e(TAG, "Failed to finalize " + cid);
11437                    PackageHelper.destroySdDir(cid);
11438                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11439                }
11440
11441                boolean mounted = PackageHelper.isContainerMounted(cid);
11442                if (!mounted) {
11443                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11444                }
11445            }
11446            return status;
11447        }
11448
11449        private void cleanUp() {
11450            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11451
11452            // Destroy secure container
11453            PackageHelper.destroySdDir(cid);
11454        }
11455
11456        private List<String> getAllCodePaths() {
11457            final File codeFile = new File(getCodePath());
11458            if (codeFile != null && codeFile.exists()) {
11459                try {
11460                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11461                    return pkg.getAllCodePaths();
11462                } catch (PackageParserException e) {
11463                    // Ignored; we tried our best
11464                }
11465            }
11466            return Collections.EMPTY_LIST;
11467        }
11468
11469        void cleanUpResourcesLI() {
11470            // Enumerate all code paths before deleting
11471            cleanUpResourcesLI(getAllCodePaths());
11472        }
11473
11474        private void cleanUpResourcesLI(List<String> allCodePaths) {
11475            cleanUp();
11476            removeDexFiles(allCodePaths, instructionSets);
11477        }
11478
11479        String getPackageName() {
11480            return getAsecPackageName(cid);
11481        }
11482
11483        boolean doPostDeleteLI(boolean delete) {
11484            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11485            final List<String> allCodePaths = getAllCodePaths();
11486            boolean mounted = PackageHelper.isContainerMounted(cid);
11487            if (mounted) {
11488                // Unmount first
11489                if (PackageHelper.unMountSdDir(cid)) {
11490                    mounted = false;
11491                }
11492            }
11493            if (!mounted && delete) {
11494                cleanUpResourcesLI(allCodePaths);
11495            }
11496            return !mounted;
11497        }
11498
11499        @Override
11500        int doPreCopy() {
11501            if (isFwdLocked()) {
11502                if (!PackageHelper.fixSdPermissions(cid,
11503                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11504                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11505                }
11506            }
11507
11508            return PackageManager.INSTALL_SUCCEEDED;
11509        }
11510
11511        @Override
11512        int doPostCopy(int uid) {
11513            if (isFwdLocked()) {
11514                if (uid < Process.FIRST_APPLICATION_UID
11515                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11516                                RES_FILE_NAME)) {
11517                    Slog.e(TAG, "Failed to finalize " + cid);
11518                    PackageHelper.destroySdDir(cid);
11519                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11520                }
11521            }
11522
11523            return PackageManager.INSTALL_SUCCEEDED;
11524        }
11525    }
11526
11527    /**
11528     * Logic to handle movement of existing installed applications.
11529     */
11530    class MoveInstallArgs extends InstallArgs {
11531        private File codeFile;
11532        private File resourceFile;
11533
11534        /** New install */
11535        MoveInstallArgs(InstallParams params) {
11536            super(params.origin, params.move, params.observer, params.installFlags,
11537                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11538                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11539                    params.grantedRuntimePermissions);
11540        }
11541
11542        int copyApk(IMediaContainerService imcs, boolean temp) {
11543            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11544                    + move.fromUuid + " to " + move.toUuid);
11545            synchronized (mInstaller) {
11546                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11547                        move.dataAppName, move.appId, move.seinfo) != 0) {
11548                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11549                }
11550            }
11551
11552            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11553            resourceFile = codeFile;
11554            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11555
11556            return PackageManager.INSTALL_SUCCEEDED;
11557        }
11558
11559        int doPreInstall(int status) {
11560            if (status != PackageManager.INSTALL_SUCCEEDED) {
11561                cleanUp(move.toUuid);
11562            }
11563            return status;
11564        }
11565
11566        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11567            if (status != PackageManager.INSTALL_SUCCEEDED) {
11568                cleanUp(move.toUuid);
11569                return false;
11570            }
11571
11572            // Reflect the move in app info
11573            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11574            pkg.applicationInfo.setCodePath(pkg.codePath);
11575            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11576            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11577            pkg.applicationInfo.setResourcePath(pkg.codePath);
11578            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11579            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11580
11581            return true;
11582        }
11583
11584        int doPostInstall(int status, int uid) {
11585            if (status == PackageManager.INSTALL_SUCCEEDED) {
11586                cleanUp(move.fromUuid);
11587            } else {
11588                cleanUp(move.toUuid);
11589            }
11590            return status;
11591        }
11592
11593        @Override
11594        String getCodePath() {
11595            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11596        }
11597
11598        @Override
11599        String getResourcePath() {
11600            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11601        }
11602
11603        private boolean cleanUp(String volumeUuid) {
11604            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11605                    move.dataAppName);
11606            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11607            synchronized (mInstallLock) {
11608                // Clean up both app data and code
11609                removeDataDirsLI(volumeUuid, move.packageName);
11610                if (codeFile.isDirectory()) {
11611                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11612                } else {
11613                    codeFile.delete();
11614                }
11615            }
11616            return true;
11617        }
11618
11619        void cleanUpResourcesLI() {
11620            throw new UnsupportedOperationException();
11621        }
11622
11623        boolean doPostDeleteLI(boolean delete) {
11624            throw new UnsupportedOperationException();
11625        }
11626    }
11627
11628    static String getAsecPackageName(String packageCid) {
11629        int idx = packageCid.lastIndexOf("-");
11630        if (idx == -1) {
11631            return packageCid;
11632        }
11633        return packageCid.substring(0, idx);
11634    }
11635
11636    // Utility method used to create code paths based on package name and available index.
11637    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11638        String idxStr = "";
11639        int idx = 1;
11640        // Fall back to default value of idx=1 if prefix is not
11641        // part of oldCodePath
11642        if (oldCodePath != null) {
11643            String subStr = oldCodePath;
11644            // Drop the suffix right away
11645            if (suffix != null && subStr.endsWith(suffix)) {
11646                subStr = subStr.substring(0, subStr.length() - suffix.length());
11647            }
11648            // If oldCodePath already contains prefix find out the
11649            // ending index to either increment or decrement.
11650            int sidx = subStr.lastIndexOf(prefix);
11651            if (sidx != -1) {
11652                subStr = subStr.substring(sidx + prefix.length());
11653                if (subStr != null) {
11654                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11655                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11656                    }
11657                    try {
11658                        idx = Integer.parseInt(subStr);
11659                        if (idx <= 1) {
11660                            idx++;
11661                        } else {
11662                            idx--;
11663                        }
11664                    } catch(NumberFormatException e) {
11665                    }
11666                }
11667            }
11668        }
11669        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11670        return prefix + idxStr;
11671    }
11672
11673    private File getNextCodePath(File targetDir, String packageName) {
11674        int suffix = 1;
11675        File result;
11676        do {
11677            result = new File(targetDir, packageName + "-" + suffix);
11678            suffix++;
11679        } while (result.exists());
11680        return result;
11681    }
11682
11683    // Utility method that returns the relative package path with respect
11684    // to the installation directory. Like say for /data/data/com.test-1.apk
11685    // string com.test-1 is returned.
11686    static String deriveCodePathName(String codePath) {
11687        if (codePath == null) {
11688            return null;
11689        }
11690        final File codeFile = new File(codePath);
11691        final String name = codeFile.getName();
11692        if (codeFile.isDirectory()) {
11693            return name;
11694        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11695            final int lastDot = name.lastIndexOf('.');
11696            return name.substring(0, lastDot);
11697        } else {
11698            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11699            return null;
11700        }
11701    }
11702
11703    class PackageInstalledInfo {
11704        String name;
11705        int uid;
11706        // The set of users that originally had this package installed.
11707        int[] origUsers;
11708        // The set of users that now have this package installed.
11709        int[] newUsers;
11710        PackageParser.Package pkg;
11711        int returnCode;
11712        String returnMsg;
11713        PackageRemovedInfo removedInfo;
11714
11715        public void setError(int code, String msg) {
11716            returnCode = code;
11717            returnMsg = msg;
11718            Slog.w(TAG, msg);
11719        }
11720
11721        public void setError(String msg, PackageParserException e) {
11722            returnCode = e.error;
11723            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11724            Slog.w(TAG, msg, e);
11725        }
11726
11727        public void setError(String msg, PackageManagerException e) {
11728            returnCode = e.error;
11729            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11730            Slog.w(TAG, msg, e);
11731        }
11732
11733        // In some error cases we want to convey more info back to the observer
11734        String origPackage;
11735        String origPermission;
11736    }
11737
11738    /*
11739     * Install a non-existing package.
11740     */
11741    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11742            UserHandle user, String installerPackageName, String volumeUuid,
11743            PackageInstalledInfo res) {
11744        // Remember this for later, in case we need to rollback this install
11745        String pkgName = pkg.packageName;
11746
11747        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11748        final boolean dataDirExists = Environment
11749                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11750        synchronized(mPackages) {
11751            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11752                // A package with the same name is already installed, though
11753                // it has been renamed to an older name.  The package we
11754                // are trying to install should be installed as an update to
11755                // the existing one, but that has not been requested, so bail.
11756                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11757                        + " without first uninstalling package running as "
11758                        + mSettings.mRenamedPackages.get(pkgName));
11759                return;
11760            }
11761            if (mPackages.containsKey(pkgName)) {
11762                // Don't allow installation over an existing package with the same name.
11763                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11764                        + " without first uninstalling.");
11765                return;
11766            }
11767        }
11768
11769        try {
11770            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11771                    System.currentTimeMillis(), user);
11772
11773            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11774            // delete the partially installed application. the data directory will have to be
11775            // restored if it was already existing
11776            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11777                // remove package from internal structures.  Note that we want deletePackageX to
11778                // delete the package data and cache directories that it created in
11779                // scanPackageLocked, unless those directories existed before we even tried to
11780                // install.
11781                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11782                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11783                                res.removedInfo, true);
11784            }
11785
11786        } catch (PackageManagerException e) {
11787            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11788        }
11789    }
11790
11791    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11792        // Can't rotate keys during boot or if sharedUser.
11793        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11794                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11795            return false;
11796        }
11797        // app is using upgradeKeySets; make sure all are valid
11798        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11799        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11800        for (int i = 0; i < upgradeKeySets.length; i++) {
11801            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11802                Slog.wtf(TAG, "Package "
11803                         + (oldPs.name != null ? oldPs.name : "<null>")
11804                         + " contains upgrade-key-set reference to unknown key-set: "
11805                         + upgradeKeySets[i]
11806                         + " reverting to signatures check.");
11807                return false;
11808            }
11809        }
11810        return true;
11811    }
11812
11813    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11814        // Upgrade keysets are being used.  Determine if new package has a superset of the
11815        // required keys.
11816        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11817        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11818        for (int i = 0; i < upgradeKeySets.length; i++) {
11819            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11820            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11821                return true;
11822            }
11823        }
11824        return false;
11825    }
11826
11827    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11828            UserHandle user, String installerPackageName, String volumeUuid,
11829            PackageInstalledInfo res) {
11830        final PackageParser.Package oldPackage;
11831        final String pkgName = pkg.packageName;
11832        final int[] allUsers;
11833        final boolean[] perUserInstalled;
11834
11835        // First find the old package info and check signatures
11836        synchronized(mPackages) {
11837            oldPackage = mPackages.get(pkgName);
11838            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11839            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11840            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11841                if(!checkUpgradeKeySetLP(ps, pkg)) {
11842                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11843                            "New package not signed by keys specified by upgrade-keysets: "
11844                            + pkgName);
11845                    return;
11846                }
11847            } else {
11848                // default to original signature matching
11849                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11850                    != PackageManager.SIGNATURE_MATCH) {
11851                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11852                            "New package has a different signature: " + pkgName);
11853                    return;
11854                }
11855            }
11856
11857            // In case of rollback, remember per-user/profile install state
11858            allUsers = sUserManager.getUserIds();
11859            perUserInstalled = new boolean[allUsers.length];
11860            for (int i = 0; i < allUsers.length; i++) {
11861                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11862            }
11863        }
11864
11865        boolean sysPkg = (isSystemApp(oldPackage));
11866        if (sysPkg) {
11867            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11868                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11869        } else {
11870            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11871                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11872        }
11873    }
11874
11875    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11876            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11877            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11878            String volumeUuid, PackageInstalledInfo res) {
11879        String pkgName = deletedPackage.packageName;
11880        boolean deletedPkg = true;
11881        boolean updatedSettings = false;
11882
11883        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11884                + deletedPackage);
11885        long origUpdateTime;
11886        if (pkg.mExtras != null) {
11887            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11888        } else {
11889            origUpdateTime = 0;
11890        }
11891
11892        // First delete the existing package while retaining the data directory
11893        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11894                res.removedInfo, true)) {
11895            // If the existing package wasn't successfully deleted
11896            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11897            deletedPkg = false;
11898        } else {
11899            // Successfully deleted the old package; proceed with replace.
11900
11901            // If deleted package lived in a container, give users a chance to
11902            // relinquish resources before killing.
11903            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11904                if (DEBUG_INSTALL) {
11905                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11906                }
11907                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11908                final ArrayList<String> pkgList = new ArrayList<String>(1);
11909                pkgList.add(deletedPackage.applicationInfo.packageName);
11910                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11911            }
11912
11913            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11914            try {
11915                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11916                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11917                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11918                        perUserInstalled, res, user);
11919                updatedSettings = true;
11920            } catch (PackageManagerException e) {
11921                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11922            }
11923        }
11924
11925        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11926            // remove package from internal structures.  Note that we want deletePackageX to
11927            // delete the package data and cache directories that it created in
11928            // scanPackageLocked, unless those directories existed before we even tried to
11929            // install.
11930            if(updatedSettings) {
11931                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11932                deletePackageLI(
11933                        pkgName, null, true, allUsers, perUserInstalled,
11934                        PackageManager.DELETE_KEEP_DATA,
11935                                res.removedInfo, true);
11936            }
11937            // Since we failed to install the new package we need to restore the old
11938            // package that we deleted.
11939            if (deletedPkg) {
11940                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11941                File restoreFile = new File(deletedPackage.codePath);
11942                // Parse old package
11943                boolean oldExternal = isExternal(deletedPackage);
11944                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11945                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11946                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11947                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11948                try {
11949                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11950                } catch (PackageManagerException e) {
11951                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11952                            + e.getMessage());
11953                    return;
11954                }
11955                // Restore of old package succeeded. Update permissions.
11956                // writer
11957                synchronized (mPackages) {
11958                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11959                            UPDATE_PERMISSIONS_ALL);
11960                    // can downgrade to reader
11961                    mSettings.writeLPr();
11962                }
11963                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11964            }
11965        }
11966    }
11967
11968    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11969            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11970            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11971            String volumeUuid, PackageInstalledInfo res) {
11972        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11973                + ", old=" + deletedPackage);
11974        boolean disabledSystem = false;
11975        boolean updatedSettings = false;
11976        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11977        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11978                != 0) {
11979            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11980        }
11981        String packageName = deletedPackage.packageName;
11982        if (packageName == null) {
11983            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11984                    "Attempt to delete null packageName.");
11985            return;
11986        }
11987        PackageParser.Package oldPkg;
11988        PackageSetting oldPkgSetting;
11989        // reader
11990        synchronized (mPackages) {
11991            oldPkg = mPackages.get(packageName);
11992            oldPkgSetting = mSettings.mPackages.get(packageName);
11993            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11994                    (oldPkgSetting == null)) {
11995                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11996                        "Couldn't find package:" + packageName + " information");
11997                return;
11998            }
11999        }
12000
12001        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12002
12003        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12004        res.removedInfo.removedPackage = packageName;
12005        // Remove existing system package
12006        removePackageLI(oldPkgSetting, true);
12007        // writer
12008        synchronized (mPackages) {
12009            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12010            if (!disabledSystem && deletedPackage != null) {
12011                // We didn't need to disable the .apk as a current system package,
12012                // which means we are replacing another update that is already
12013                // installed.  We need to make sure to delete the older one's .apk.
12014                res.removedInfo.args = createInstallArgsForExisting(0,
12015                        deletedPackage.applicationInfo.getCodePath(),
12016                        deletedPackage.applicationInfo.getResourcePath(),
12017                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12018            } else {
12019                res.removedInfo.args = null;
12020            }
12021        }
12022
12023        // Successfully disabled the old package. Now proceed with re-installation
12024        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12025
12026        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12027        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12028
12029        PackageParser.Package newPackage = null;
12030        try {
12031            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
12032            if (newPackage.mExtras != null) {
12033                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12034                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12035                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12036
12037                // is the update attempting to change shared user? that isn't going to work...
12038                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12039                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12040                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12041                            + " to " + newPkgSetting.sharedUser);
12042                    updatedSettings = true;
12043                }
12044            }
12045
12046            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12047                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12048                        perUserInstalled, res, user);
12049                updatedSettings = true;
12050            }
12051
12052        } catch (PackageManagerException e) {
12053            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12054        }
12055
12056        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12057            // Re installation failed. Restore old information
12058            // Remove new pkg information
12059            if (newPackage != null) {
12060                removeInstalledPackageLI(newPackage, true);
12061            }
12062            // Add back the old system package
12063            try {
12064                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12065            } catch (PackageManagerException e) {
12066                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12067            }
12068            // Restore the old system information in Settings
12069            synchronized (mPackages) {
12070                if (disabledSystem) {
12071                    mSettings.enableSystemPackageLPw(packageName);
12072                }
12073                if (updatedSettings) {
12074                    mSettings.setInstallerPackageName(packageName,
12075                            oldPkgSetting.installerPackageName);
12076                }
12077                mSettings.writeLPr();
12078            }
12079        }
12080    }
12081
12082    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12083        // Collect all used permissions in the UID
12084        ArraySet<String> usedPermissions = new ArraySet<>();
12085        final int packageCount = su.packages.size();
12086        for (int i = 0; i < packageCount; i++) {
12087            PackageSetting ps = su.packages.valueAt(i);
12088            if (ps.pkg == null) {
12089                continue;
12090            }
12091            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12092            for (int j = 0; j < requestedPermCount; j++) {
12093                String permission = ps.pkg.requestedPermissions.get(j);
12094                BasePermission bp = mSettings.mPermissions.get(permission);
12095                if (bp != null) {
12096                    usedPermissions.add(permission);
12097                }
12098            }
12099        }
12100
12101        PermissionsState permissionsState = su.getPermissionsState();
12102        // Prune install permissions
12103        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12104        final int installPermCount = installPermStates.size();
12105        for (int i = installPermCount - 1; i >= 0;  i--) {
12106            PermissionState permissionState = installPermStates.get(i);
12107            if (!usedPermissions.contains(permissionState.getName())) {
12108                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12109                if (bp != null) {
12110                    permissionsState.revokeInstallPermission(bp);
12111                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12112                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12113                }
12114            }
12115        }
12116
12117        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12118
12119        // Prune runtime permissions
12120        for (int userId : allUserIds) {
12121            List<PermissionState> runtimePermStates = permissionsState
12122                    .getRuntimePermissionStates(userId);
12123            final int runtimePermCount = runtimePermStates.size();
12124            for (int i = runtimePermCount - 1; i >= 0; i--) {
12125                PermissionState permissionState = runtimePermStates.get(i);
12126                if (!usedPermissions.contains(permissionState.getName())) {
12127                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12128                    if (bp != null) {
12129                        permissionsState.revokeRuntimePermission(bp, userId);
12130                        permissionsState.updatePermissionFlags(bp, userId,
12131                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12132                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12133                                runtimePermissionChangedUserIds, userId);
12134                    }
12135                }
12136            }
12137        }
12138
12139        return runtimePermissionChangedUserIds;
12140    }
12141
12142    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12143            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12144            UserHandle user) {
12145        String pkgName = newPackage.packageName;
12146        synchronized (mPackages) {
12147            //write settings. the installStatus will be incomplete at this stage.
12148            //note that the new package setting would have already been
12149            //added to mPackages. It hasn't been persisted yet.
12150            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12151            mSettings.writeLPr();
12152        }
12153
12154        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12155
12156        synchronized (mPackages) {
12157            updatePermissionsLPw(newPackage.packageName, newPackage,
12158                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12159                            ? UPDATE_PERMISSIONS_ALL : 0));
12160            // For system-bundled packages, we assume that installing an upgraded version
12161            // of the package implies that the user actually wants to run that new code,
12162            // so we enable the package.
12163            PackageSetting ps = mSettings.mPackages.get(pkgName);
12164            if (ps != null) {
12165                if (isSystemApp(newPackage)) {
12166                    // NB: implicit assumption that system package upgrades apply to all users
12167                    if (DEBUG_INSTALL) {
12168                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12169                    }
12170                    if (res.origUsers != null) {
12171                        for (int userHandle : res.origUsers) {
12172                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12173                                    userHandle, installerPackageName);
12174                        }
12175                    }
12176                    // Also convey the prior install/uninstall state
12177                    if (allUsers != null && perUserInstalled != null) {
12178                        for (int i = 0; i < allUsers.length; i++) {
12179                            if (DEBUG_INSTALL) {
12180                                Slog.d(TAG, "    user " + allUsers[i]
12181                                        + " => " + perUserInstalled[i]);
12182                            }
12183                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12184                        }
12185                        // these install state changes will be persisted in the
12186                        // upcoming call to mSettings.writeLPr().
12187                    }
12188                }
12189                // It's implied that when a user requests installation, they want the app to be
12190                // installed and enabled.
12191                int userId = user.getIdentifier();
12192                if (userId != UserHandle.USER_ALL) {
12193                    ps.setInstalled(true, userId);
12194                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12195                }
12196            }
12197            res.name = pkgName;
12198            res.uid = newPackage.applicationInfo.uid;
12199            res.pkg = newPackage;
12200            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12201            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12202            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12203            //to update install status
12204            mSettings.writeLPr();
12205        }
12206    }
12207
12208    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12209        final int installFlags = args.installFlags;
12210        final String installerPackageName = args.installerPackageName;
12211        final String volumeUuid = args.volumeUuid;
12212        final File tmpPackageFile = new File(args.getCodePath());
12213        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12214        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12215                || (args.volumeUuid != null));
12216        boolean replace = false;
12217        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12218        if (args.move != null) {
12219            // moving a complete application; perfom an initial scan on the new install location
12220            scanFlags |= SCAN_INITIAL;
12221        }
12222        // Result object to be returned
12223        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12224
12225        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12226        // Retrieve PackageSettings and parse package
12227        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12228                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12229                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12230        PackageParser pp = new PackageParser();
12231        pp.setSeparateProcesses(mSeparateProcesses);
12232        pp.setDisplayMetrics(mMetrics);
12233
12234        final PackageParser.Package pkg;
12235        try {
12236            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12237        } catch (PackageParserException e) {
12238            res.setError("Failed parse during installPackageLI", e);
12239            return;
12240        }
12241
12242        // Mark that we have an install time CPU ABI override.
12243        pkg.cpuAbiOverride = args.abiOverride;
12244
12245        String pkgName = res.name = pkg.packageName;
12246        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12247            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12248                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12249                return;
12250            }
12251        }
12252
12253        try {
12254            pp.collectCertificates(pkg, parseFlags);
12255            pp.collectManifestDigest(pkg);
12256        } catch (PackageParserException e) {
12257            res.setError("Failed collect during installPackageLI", e);
12258            return;
12259        }
12260
12261        /* If the installer passed in a manifest digest, compare it now. */
12262        if (args.manifestDigest != null) {
12263            if (DEBUG_INSTALL) {
12264                final String parsedManifest = pkg.manifestDigest == null ? "null"
12265                        : pkg.manifestDigest.toString();
12266                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12267                        + parsedManifest);
12268            }
12269
12270            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12271                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12272                return;
12273            }
12274        } else if (DEBUG_INSTALL) {
12275            final String parsedManifest = pkg.manifestDigest == null
12276                    ? "null" : pkg.manifestDigest.toString();
12277            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12278        }
12279
12280        // Get rid of all references to package scan path via parser.
12281        pp = null;
12282        String oldCodePath = null;
12283        boolean systemApp = false;
12284        synchronized (mPackages) {
12285            // Check if installing already existing package
12286            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12287                String oldName = mSettings.mRenamedPackages.get(pkgName);
12288                if (pkg.mOriginalPackages != null
12289                        && pkg.mOriginalPackages.contains(oldName)
12290                        && mPackages.containsKey(oldName)) {
12291                    // This package is derived from an original package,
12292                    // and this device has been updating from that original
12293                    // name.  We must continue using the original name, so
12294                    // rename the new package here.
12295                    pkg.setPackageName(oldName);
12296                    pkgName = pkg.packageName;
12297                    replace = true;
12298                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12299                            + oldName + " pkgName=" + pkgName);
12300                } else if (mPackages.containsKey(pkgName)) {
12301                    // This package, under its official name, already exists
12302                    // on the device; we should replace it.
12303                    replace = true;
12304                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12305                }
12306
12307                // Prevent apps opting out from runtime permissions
12308                if (replace) {
12309                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12310                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12311                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12312                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12313                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12314                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12315                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12316                                        + " doesn't support runtime permissions but the old"
12317                                        + " target SDK " + oldTargetSdk + " does.");
12318                        return;
12319                    }
12320                }
12321            }
12322
12323            PackageSetting ps = mSettings.mPackages.get(pkgName);
12324            if (ps != null) {
12325                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12326
12327                // Quick sanity check that we're signed correctly if updating;
12328                // we'll check this again later when scanning, but we want to
12329                // bail early here before tripping over redefined permissions.
12330                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12331                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12332                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12333                                + pkg.packageName + " upgrade keys do not match the "
12334                                + "previously installed version");
12335                        return;
12336                    }
12337                } else {
12338                    try {
12339                        verifySignaturesLP(ps, pkg);
12340                    } catch (PackageManagerException e) {
12341                        res.setError(e.error, e.getMessage());
12342                        return;
12343                    }
12344                }
12345
12346                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12347                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12348                    systemApp = (ps.pkg.applicationInfo.flags &
12349                            ApplicationInfo.FLAG_SYSTEM) != 0;
12350                }
12351                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12352            }
12353
12354            // Check whether the newly-scanned package wants to define an already-defined perm
12355            int N = pkg.permissions.size();
12356            for (int i = N-1; i >= 0; i--) {
12357                PackageParser.Permission perm = pkg.permissions.get(i);
12358                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12359                if (bp != null) {
12360                    // If the defining package is signed with our cert, it's okay.  This
12361                    // also includes the "updating the same package" case, of course.
12362                    // "updating same package" could also involve key-rotation.
12363                    final boolean sigsOk;
12364                    if (bp.sourcePackage.equals(pkg.packageName)
12365                            && (bp.packageSetting instanceof PackageSetting)
12366                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12367                                    scanFlags))) {
12368                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12369                    } else {
12370                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12371                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12372                    }
12373                    if (!sigsOk) {
12374                        // If the owning package is the system itself, we log but allow
12375                        // install to proceed; we fail the install on all other permission
12376                        // redefinitions.
12377                        if (!bp.sourcePackage.equals("android")) {
12378                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12379                                    + pkg.packageName + " attempting to redeclare permission "
12380                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12381                            res.origPermission = perm.info.name;
12382                            res.origPackage = bp.sourcePackage;
12383                            return;
12384                        } else {
12385                            Slog.w(TAG, "Package " + pkg.packageName
12386                                    + " attempting to redeclare system permission "
12387                                    + perm.info.name + "; ignoring new declaration");
12388                            pkg.permissions.remove(i);
12389                        }
12390                    }
12391                }
12392            }
12393
12394        }
12395
12396        if (systemApp && onExternal) {
12397            // Disable updates to system apps on sdcard
12398            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12399                    "Cannot install updates to system apps on sdcard");
12400            return;
12401        }
12402
12403        if (args.move != null) {
12404            // We did an in-place move, so dex is ready to roll
12405            scanFlags |= SCAN_NO_DEX;
12406            scanFlags |= SCAN_MOVE;
12407
12408            synchronized (mPackages) {
12409                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12410                if (ps == null) {
12411                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12412                            "Missing settings for moved package " + pkgName);
12413                }
12414
12415                // We moved the entire application as-is, so bring over the
12416                // previously derived ABI information.
12417                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12418                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12419            }
12420
12421        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12422            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12423            scanFlags |= SCAN_NO_DEX;
12424
12425            try {
12426                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12427                        true /* extract libs */);
12428            } catch (PackageManagerException pme) {
12429                Slog.e(TAG, "Error deriving application ABI", pme);
12430                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12431                return;
12432            }
12433
12434            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12435            int result = mPackageDexOptimizer
12436                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12437                            false /* defer */, false /* inclDependencies */,
12438                            true /*bootComplete*/, false /*useJit*/);
12439            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12440                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12441                return;
12442            }
12443        }
12444
12445        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12446            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12447            return;
12448        }
12449
12450        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12451
12452        if (replace) {
12453            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12454                    installerPackageName, volumeUuid, res);
12455        } else {
12456            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12457                    args.user, installerPackageName, volumeUuid, res);
12458        }
12459        synchronized (mPackages) {
12460            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12461            if (ps != null) {
12462                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12463            }
12464        }
12465    }
12466
12467    private void startIntentFilterVerifications(int userId, boolean replacing,
12468            PackageParser.Package pkg) {
12469        if (mIntentFilterVerifierComponent == null) {
12470            Slog.w(TAG, "No IntentFilter verification will not be done as "
12471                    + "there is no IntentFilterVerifier available!");
12472            return;
12473        }
12474
12475        final int verifierUid = getPackageUid(
12476                mIntentFilterVerifierComponent.getPackageName(),
12477                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12478
12479        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12480        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12481        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12482        mHandler.sendMessage(msg);
12483    }
12484
12485    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12486            PackageParser.Package pkg) {
12487        int size = pkg.activities.size();
12488        if (size == 0) {
12489            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12490                    "No activity, so no need to verify any IntentFilter!");
12491            return;
12492        }
12493
12494        final boolean hasDomainURLs = hasDomainURLs(pkg);
12495        if (!hasDomainURLs) {
12496            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12497                    "No domain URLs, so no need to verify any IntentFilter!");
12498            return;
12499        }
12500
12501        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12502                + " if any IntentFilter from the " + size
12503                + " Activities needs verification ...");
12504
12505        int count = 0;
12506        final String packageName = pkg.packageName;
12507
12508        synchronized (mPackages) {
12509            // If this is a new install and we see that we've already run verification for this
12510            // package, we have nothing to do: it means the state was restored from backup.
12511            if (!replacing) {
12512                IntentFilterVerificationInfo ivi =
12513                        mSettings.getIntentFilterVerificationLPr(packageName);
12514                if (ivi != null) {
12515                    if (DEBUG_DOMAIN_VERIFICATION) {
12516                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12517                                + ivi.getStatusString());
12518                    }
12519                    return;
12520                }
12521            }
12522
12523            // If any filters need to be verified, then all need to be.
12524            boolean needToVerify = false;
12525            for (PackageParser.Activity a : pkg.activities) {
12526                for (ActivityIntentInfo filter : a.intents) {
12527                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12528                        if (DEBUG_DOMAIN_VERIFICATION) {
12529                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12530                        }
12531                        needToVerify = true;
12532                        break;
12533                    }
12534                }
12535            }
12536
12537            if (needToVerify) {
12538                final int verificationId = mIntentFilterVerificationToken++;
12539                for (PackageParser.Activity a : pkg.activities) {
12540                    for (ActivityIntentInfo filter : a.intents) {
12541                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12542                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12543                                    "Verification needed for IntentFilter:" + filter.toString());
12544                            mIntentFilterVerifier.addOneIntentFilterVerification(
12545                                    verifierUid, userId, verificationId, filter, packageName);
12546                            count++;
12547                        }
12548                    }
12549                }
12550            }
12551        }
12552
12553        if (count > 0) {
12554            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12555                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12556                    +  " for userId:" + userId);
12557            mIntentFilterVerifier.startVerifications(userId);
12558        } else {
12559            if (DEBUG_DOMAIN_VERIFICATION) {
12560                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12561            }
12562        }
12563    }
12564
12565    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12566        final ComponentName cn  = filter.activity.getComponentName();
12567        final String packageName = cn.getPackageName();
12568
12569        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12570                packageName);
12571        if (ivi == null) {
12572            return true;
12573        }
12574        int status = ivi.getStatus();
12575        switch (status) {
12576            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12577            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12578                return true;
12579
12580            default:
12581                // Nothing to do
12582                return false;
12583        }
12584    }
12585
12586    private static boolean isMultiArch(PackageSetting ps) {
12587        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12588    }
12589
12590    private static boolean isMultiArch(ApplicationInfo info) {
12591        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12592    }
12593
12594    private static boolean isExternal(PackageParser.Package pkg) {
12595        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12596    }
12597
12598    private static boolean isExternal(PackageSetting ps) {
12599        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12600    }
12601
12602    private static boolean isExternal(ApplicationInfo info) {
12603        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12604    }
12605
12606    private static boolean isSystemApp(PackageParser.Package pkg) {
12607        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12608    }
12609
12610    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12611        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12612    }
12613
12614    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12615        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12616    }
12617
12618    private static boolean isSystemApp(PackageSetting ps) {
12619        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12620    }
12621
12622    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12623        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12624    }
12625
12626    private int packageFlagsToInstallFlags(PackageSetting ps) {
12627        int installFlags = 0;
12628        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12629            // This existing package was an external ASEC install when we have
12630            // the external flag without a UUID
12631            installFlags |= PackageManager.INSTALL_EXTERNAL;
12632        }
12633        if (ps.isForwardLocked()) {
12634            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12635        }
12636        return installFlags;
12637    }
12638
12639    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
12640        if (isExternal(pkg)) {
12641            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12642                return StorageManager.UUID_PRIMARY_PHYSICAL;
12643            } else {
12644                return pkg.volumeUuid;
12645            }
12646        } else {
12647            return StorageManager.UUID_PRIVATE_INTERNAL;
12648        }
12649    }
12650
12651    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12652        if (isExternal(pkg)) {
12653            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12654                return mSettings.getExternalVersion();
12655            } else {
12656                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12657            }
12658        } else {
12659            return mSettings.getInternalVersion();
12660        }
12661    }
12662
12663    private void deleteTempPackageFiles() {
12664        final FilenameFilter filter = new FilenameFilter() {
12665            public boolean accept(File dir, String name) {
12666                return name.startsWith("vmdl") && name.endsWith(".tmp");
12667            }
12668        };
12669        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12670            file.delete();
12671        }
12672    }
12673
12674    @Override
12675    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12676            int flags) {
12677        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12678                flags);
12679    }
12680
12681    @Override
12682    public void deletePackage(final String packageName,
12683            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12684        mContext.enforceCallingOrSelfPermission(
12685                android.Manifest.permission.DELETE_PACKAGES, null);
12686        Preconditions.checkNotNull(packageName);
12687        Preconditions.checkNotNull(observer);
12688        final int uid = Binder.getCallingUid();
12689        if (UserHandle.getUserId(uid) != userId) {
12690            mContext.enforceCallingPermission(
12691                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12692                    "deletePackage for user " + userId);
12693        }
12694        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12695            try {
12696                observer.onPackageDeleted(packageName,
12697                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12698            } catch (RemoteException re) {
12699            }
12700            return;
12701        }
12702
12703        boolean uninstallBlocked = false;
12704        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12705            int[] users = sUserManager.getUserIds();
12706            for (int i = 0; i < users.length; ++i) {
12707                if (getBlockUninstallForUser(packageName, users[i])) {
12708                    uninstallBlocked = true;
12709                    break;
12710                }
12711            }
12712        } else {
12713            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12714        }
12715        if (uninstallBlocked) {
12716            try {
12717                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12718                        null);
12719            } catch (RemoteException re) {
12720            }
12721            return;
12722        }
12723
12724        if (DEBUG_REMOVE) {
12725            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12726        }
12727        // Queue up an async operation since the package deletion may take a little while.
12728        mHandler.post(new Runnable() {
12729            public void run() {
12730                mHandler.removeCallbacks(this);
12731                final int returnCode = deletePackageX(packageName, userId, flags);
12732                if (observer != null) {
12733                    try {
12734                        observer.onPackageDeleted(packageName, returnCode, null);
12735                    } catch (RemoteException e) {
12736                        Log.i(TAG, "Observer no longer exists.");
12737                    } //end catch
12738                } //end if
12739            } //end run
12740        });
12741    }
12742
12743    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12744        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12745                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12746        try {
12747            if (dpm != null) {
12748                if (dpm.isDeviceOwner(packageName)) {
12749                    return true;
12750                }
12751                int[] users;
12752                if (userId == UserHandle.USER_ALL) {
12753                    users = sUserManager.getUserIds();
12754                } else {
12755                    users = new int[]{userId};
12756                }
12757                for (int i = 0; i < users.length; ++i) {
12758                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12759                        return true;
12760                    }
12761                }
12762            }
12763        } catch (RemoteException e) {
12764        }
12765        return false;
12766    }
12767
12768    /**
12769     *  This method is an internal method that could be get invoked either
12770     *  to delete an installed package or to clean up a failed installation.
12771     *  After deleting an installed package, a broadcast is sent to notify any
12772     *  listeners that the package has been installed. For cleaning up a failed
12773     *  installation, the broadcast is not necessary since the package's
12774     *  installation wouldn't have sent the initial broadcast either
12775     *  The key steps in deleting a package are
12776     *  deleting the package information in internal structures like mPackages,
12777     *  deleting the packages base directories through installd
12778     *  updating mSettings to reflect current status
12779     *  persisting settings for later use
12780     *  sending a broadcast if necessary
12781     */
12782    private int deletePackageX(String packageName, int userId, int flags) {
12783        final PackageRemovedInfo info = new PackageRemovedInfo();
12784        final boolean res;
12785
12786        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12787                ? UserHandle.ALL : new UserHandle(userId);
12788
12789        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12790            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12791            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12792        }
12793
12794        boolean removedForAllUsers = false;
12795        boolean systemUpdate = false;
12796
12797        // for the uninstall-updates case and restricted profiles, remember the per-
12798        // userhandle installed state
12799        int[] allUsers;
12800        boolean[] perUserInstalled;
12801        synchronized (mPackages) {
12802            PackageSetting ps = mSettings.mPackages.get(packageName);
12803            allUsers = sUserManager.getUserIds();
12804            perUserInstalled = new boolean[allUsers.length];
12805            for (int i = 0; i < allUsers.length; i++) {
12806                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12807            }
12808        }
12809
12810        synchronized (mInstallLock) {
12811            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12812            res = deletePackageLI(packageName, removeForUser,
12813                    true, allUsers, perUserInstalled,
12814                    flags | REMOVE_CHATTY, info, true);
12815            systemUpdate = info.isRemovedPackageSystemUpdate;
12816            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12817                removedForAllUsers = true;
12818            }
12819            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12820                    + " removedForAllUsers=" + removedForAllUsers);
12821        }
12822
12823        if (res) {
12824            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12825
12826            // If the removed package was a system update, the old system package
12827            // was re-enabled; we need to broadcast this information
12828            if (systemUpdate) {
12829                Bundle extras = new Bundle(1);
12830                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12831                        ? info.removedAppId : info.uid);
12832                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12833
12834                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12835                        extras, null, null, null);
12836                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12837                        extras, null, null, null);
12838                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12839                        null, packageName, null, null);
12840            }
12841        }
12842        // Force a gc here.
12843        Runtime.getRuntime().gc();
12844        // Delete the resources here after sending the broadcast to let
12845        // other processes clean up before deleting resources.
12846        if (info.args != null) {
12847            synchronized (mInstallLock) {
12848                info.args.doPostDeleteLI(true);
12849            }
12850        }
12851
12852        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12853    }
12854
12855    class PackageRemovedInfo {
12856        String removedPackage;
12857        int uid = -1;
12858        int removedAppId = -1;
12859        int[] removedUsers = null;
12860        boolean isRemovedPackageSystemUpdate = false;
12861        // Clean up resources deleted packages.
12862        InstallArgs args = null;
12863
12864        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12865            Bundle extras = new Bundle(1);
12866            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12867            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12868            if (replacing) {
12869                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12870            }
12871            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12872            if (removedPackage != null) {
12873                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12874                        extras, null, null, removedUsers);
12875                if (fullRemove && !replacing) {
12876                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12877                            extras, null, null, removedUsers);
12878                }
12879            }
12880            if (removedAppId >= 0) {
12881                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12882                        removedUsers);
12883            }
12884        }
12885    }
12886
12887    /*
12888     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12889     * flag is not set, the data directory is removed as well.
12890     * make sure this flag is set for partially installed apps. If not its meaningless to
12891     * delete a partially installed application.
12892     */
12893    private void removePackageDataLI(PackageSetting ps,
12894            int[] allUserHandles, boolean[] perUserInstalled,
12895            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12896        String packageName = ps.name;
12897        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12898        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12899        // Retrieve object to delete permissions for shared user later on
12900        final PackageSetting deletedPs;
12901        // reader
12902        synchronized (mPackages) {
12903            deletedPs = mSettings.mPackages.get(packageName);
12904            if (outInfo != null) {
12905                outInfo.removedPackage = packageName;
12906                outInfo.removedUsers = deletedPs != null
12907                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12908                        : null;
12909            }
12910        }
12911        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12912            removeDataDirsLI(ps.volumeUuid, packageName);
12913            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12914        }
12915        // writer
12916        synchronized (mPackages) {
12917            if (deletedPs != null) {
12918                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12919                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12920                    clearDefaultBrowserIfNeeded(packageName);
12921                    if (outInfo != null) {
12922                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12923                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12924                    }
12925                    updatePermissionsLPw(deletedPs.name, null, 0);
12926                    if (deletedPs.sharedUser != null) {
12927                        // Remove permissions associated with package. Since runtime
12928                        // permissions are per user we have to kill the removed package
12929                        // or packages running under the shared user of the removed
12930                        // package if revoking the permissions requested only by the removed
12931                        // package is successful and this causes a change in gids.
12932                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12933                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12934                                    userId);
12935                            if (userIdToKill == UserHandle.USER_ALL
12936                                    || userIdToKill >= UserHandle.USER_OWNER) {
12937                                // If gids changed for this user, kill all affected packages.
12938                                mHandler.post(new Runnable() {
12939                                    @Override
12940                                    public void run() {
12941                                        // This has to happen with no lock held.
12942                                        killApplication(deletedPs.name, deletedPs.appId,
12943                                                KILL_APP_REASON_GIDS_CHANGED);
12944                                    }
12945                                });
12946                                break;
12947                            }
12948                        }
12949                    }
12950                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12951                }
12952                // make sure to preserve per-user disabled state if this removal was just
12953                // a downgrade of a system app to the factory package
12954                if (allUserHandles != null && perUserInstalled != null) {
12955                    if (DEBUG_REMOVE) {
12956                        Slog.d(TAG, "Propagating install state across downgrade");
12957                    }
12958                    for (int i = 0; i < allUserHandles.length; i++) {
12959                        if (DEBUG_REMOVE) {
12960                            Slog.d(TAG, "    user " + allUserHandles[i]
12961                                    + " => " + perUserInstalled[i]);
12962                        }
12963                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12964                    }
12965                }
12966            }
12967            // can downgrade to reader
12968            if (writeSettings) {
12969                // Save settings now
12970                mSettings.writeLPr();
12971            }
12972        }
12973        if (outInfo != null) {
12974            // A user ID was deleted here. Go through all users and remove it
12975            // from KeyStore.
12976            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12977        }
12978    }
12979
12980    static boolean locationIsPrivileged(File path) {
12981        try {
12982            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12983                    .getCanonicalPath();
12984            return path.getCanonicalPath().startsWith(privilegedAppDir);
12985        } catch (IOException e) {
12986            Slog.e(TAG, "Unable to access code path " + path);
12987        }
12988        return false;
12989    }
12990
12991    /*
12992     * Tries to delete system package.
12993     */
12994    private boolean deleteSystemPackageLI(PackageSetting newPs,
12995            int[] allUserHandles, boolean[] perUserInstalled,
12996            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12997        final boolean applyUserRestrictions
12998                = (allUserHandles != null) && (perUserInstalled != null);
12999        PackageSetting disabledPs = null;
13000        // Confirm if the system package has been updated
13001        // An updated system app can be deleted. This will also have to restore
13002        // the system pkg from system partition
13003        // reader
13004        synchronized (mPackages) {
13005            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13006        }
13007        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13008                + " disabledPs=" + disabledPs);
13009        if (disabledPs == null) {
13010            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13011            return false;
13012        } else if (DEBUG_REMOVE) {
13013            Slog.d(TAG, "Deleting system pkg from data partition");
13014        }
13015        if (DEBUG_REMOVE) {
13016            if (applyUserRestrictions) {
13017                Slog.d(TAG, "Remembering install states:");
13018                for (int i = 0; i < allUserHandles.length; i++) {
13019                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13020                }
13021            }
13022        }
13023        // Delete the updated package
13024        outInfo.isRemovedPackageSystemUpdate = true;
13025        if (disabledPs.versionCode < newPs.versionCode) {
13026            // Delete data for downgrades
13027            flags &= ~PackageManager.DELETE_KEEP_DATA;
13028        } else {
13029            // Preserve data by setting flag
13030            flags |= PackageManager.DELETE_KEEP_DATA;
13031        }
13032        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13033                allUserHandles, perUserInstalled, outInfo, writeSettings);
13034        if (!ret) {
13035            return false;
13036        }
13037        // writer
13038        synchronized (mPackages) {
13039            // Reinstate the old system package
13040            mSettings.enableSystemPackageLPw(newPs.name);
13041            // Remove any native libraries from the upgraded package.
13042            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13043        }
13044        // Install the system package
13045        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13046        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13047        if (locationIsPrivileged(disabledPs.codePath)) {
13048            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13049        }
13050
13051        final PackageParser.Package newPkg;
13052        try {
13053            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13054        } catch (PackageManagerException e) {
13055            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13056            return false;
13057        }
13058
13059        // writer
13060        synchronized (mPackages) {
13061            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13062
13063            // Propagate the permissions state as we do not want to drop on the floor
13064            // runtime permissions. The update permissions method below will take
13065            // care of removing obsolete permissions and grant install permissions.
13066            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13067            updatePermissionsLPw(newPkg.packageName, newPkg,
13068                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13069
13070            if (applyUserRestrictions) {
13071                if (DEBUG_REMOVE) {
13072                    Slog.d(TAG, "Propagating install state across reinstall");
13073                }
13074                for (int i = 0; i < allUserHandles.length; i++) {
13075                    if (DEBUG_REMOVE) {
13076                        Slog.d(TAG, "    user " + allUserHandles[i]
13077                                + " => " + perUserInstalled[i]);
13078                    }
13079                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13080
13081                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13082                }
13083                // Regardless of writeSettings we need to ensure that this restriction
13084                // state propagation is persisted
13085                mSettings.writeAllUsersPackageRestrictionsLPr();
13086            }
13087            // can downgrade to reader here
13088            if (writeSettings) {
13089                mSettings.writeLPr();
13090            }
13091        }
13092        return true;
13093    }
13094
13095    private boolean deleteInstalledPackageLI(PackageSetting ps,
13096            boolean deleteCodeAndResources, int flags,
13097            int[] allUserHandles, boolean[] perUserInstalled,
13098            PackageRemovedInfo outInfo, boolean writeSettings) {
13099        if (outInfo != null) {
13100            outInfo.uid = ps.appId;
13101        }
13102
13103        // Delete package data from internal structures and also remove data if flag is set
13104        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13105
13106        // Delete application code and resources
13107        if (deleteCodeAndResources && (outInfo != null)) {
13108            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13109                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13110            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13111        }
13112        return true;
13113    }
13114
13115    @Override
13116    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13117            int userId) {
13118        mContext.enforceCallingOrSelfPermission(
13119                android.Manifest.permission.DELETE_PACKAGES, null);
13120        synchronized (mPackages) {
13121            PackageSetting ps = mSettings.mPackages.get(packageName);
13122            if (ps == null) {
13123                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13124                return false;
13125            }
13126            if (!ps.getInstalled(userId)) {
13127                // Can't block uninstall for an app that is not installed or enabled.
13128                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13129                return false;
13130            }
13131            ps.setBlockUninstall(blockUninstall, userId);
13132            mSettings.writePackageRestrictionsLPr(userId);
13133        }
13134        return true;
13135    }
13136
13137    @Override
13138    public boolean getBlockUninstallForUser(String packageName, int userId) {
13139        synchronized (mPackages) {
13140            PackageSetting ps = mSettings.mPackages.get(packageName);
13141            if (ps == null) {
13142                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13143                return false;
13144            }
13145            return ps.getBlockUninstall(userId);
13146        }
13147    }
13148
13149    /*
13150     * This method handles package deletion in general
13151     */
13152    private boolean deletePackageLI(String packageName, UserHandle user,
13153            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13154            int flags, PackageRemovedInfo outInfo,
13155            boolean writeSettings) {
13156        if (packageName == null) {
13157            Slog.w(TAG, "Attempt to delete null packageName.");
13158            return false;
13159        }
13160        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13161        PackageSetting ps;
13162        boolean dataOnly = false;
13163        int removeUser = -1;
13164        int appId = -1;
13165        synchronized (mPackages) {
13166            ps = mSettings.mPackages.get(packageName);
13167            if (ps == null) {
13168                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13169                return false;
13170            }
13171            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13172                    && user.getIdentifier() != UserHandle.USER_ALL) {
13173                // The caller is asking that the package only be deleted for a single
13174                // user.  To do this, we just mark its uninstalled state and delete
13175                // its data.  If this is a system app, we only allow this to happen if
13176                // they have set the special DELETE_SYSTEM_APP which requests different
13177                // semantics than normal for uninstalling system apps.
13178                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13179                final int userId = user.getIdentifier();
13180                ps.setUserState(userId,
13181                        COMPONENT_ENABLED_STATE_DEFAULT,
13182                        false, //installed
13183                        true,  //stopped
13184                        true,  //notLaunched
13185                        false, //hidden
13186                        null, null, null,
13187                        false, // blockUninstall
13188                        ps.readUserState(userId).domainVerificationStatus, 0);
13189                if (!isSystemApp(ps)) {
13190                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13191                        // Other user still have this package installed, so all
13192                        // we need to do is clear this user's data and save that
13193                        // it is uninstalled.
13194                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13195                        removeUser = user.getIdentifier();
13196                        appId = ps.appId;
13197                        scheduleWritePackageRestrictionsLocked(removeUser);
13198                    } else {
13199                        // We need to set it back to 'installed' so the uninstall
13200                        // broadcasts will be sent correctly.
13201                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13202                        ps.setInstalled(true, user.getIdentifier());
13203                    }
13204                } else {
13205                    // This is a system app, so we assume that the
13206                    // other users still have this package installed, so all
13207                    // we need to do is clear this user's data and save that
13208                    // it is uninstalled.
13209                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13210                    removeUser = user.getIdentifier();
13211                    appId = ps.appId;
13212                    scheduleWritePackageRestrictionsLocked(removeUser);
13213                }
13214            }
13215        }
13216
13217        if (removeUser >= 0) {
13218            // From above, we determined that we are deleting this only
13219            // for a single user.  Continue the work here.
13220            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13221            if (outInfo != null) {
13222                outInfo.removedPackage = packageName;
13223                outInfo.removedAppId = appId;
13224                outInfo.removedUsers = new int[] {removeUser};
13225            }
13226            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13227            removeKeystoreDataIfNeeded(removeUser, appId);
13228            schedulePackageCleaning(packageName, removeUser, false);
13229            synchronized (mPackages) {
13230                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13231                    scheduleWritePackageRestrictionsLocked(removeUser);
13232                }
13233                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13234            }
13235            return true;
13236        }
13237
13238        if (dataOnly) {
13239            // Delete application data first
13240            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13241            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13242            return true;
13243        }
13244
13245        boolean ret = false;
13246        if (isSystemApp(ps)) {
13247            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13248            // When an updated system application is deleted we delete the existing resources as well and
13249            // fall back to existing code in system partition
13250            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13251                    flags, outInfo, writeSettings);
13252        } else {
13253            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13254            // Kill application pre-emptively especially for apps on sd.
13255            killApplication(packageName, ps.appId, "uninstall pkg");
13256            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13257                    allUserHandles, perUserInstalled,
13258                    outInfo, writeSettings);
13259        }
13260
13261        return ret;
13262    }
13263
13264    private final class ClearStorageConnection implements ServiceConnection {
13265        IMediaContainerService mContainerService;
13266
13267        @Override
13268        public void onServiceConnected(ComponentName name, IBinder service) {
13269            synchronized (this) {
13270                mContainerService = IMediaContainerService.Stub.asInterface(service);
13271                notifyAll();
13272            }
13273        }
13274
13275        @Override
13276        public void onServiceDisconnected(ComponentName name) {
13277        }
13278    }
13279
13280    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13281        final boolean mounted;
13282        if (Environment.isExternalStorageEmulated()) {
13283            mounted = true;
13284        } else {
13285            final String status = Environment.getExternalStorageState();
13286
13287            mounted = status.equals(Environment.MEDIA_MOUNTED)
13288                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13289        }
13290
13291        if (!mounted) {
13292            return;
13293        }
13294
13295        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13296        int[] users;
13297        if (userId == UserHandle.USER_ALL) {
13298            users = sUserManager.getUserIds();
13299        } else {
13300            users = new int[] { userId };
13301        }
13302        final ClearStorageConnection conn = new ClearStorageConnection();
13303        if (mContext.bindServiceAsUser(
13304                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13305            try {
13306                for (int curUser : users) {
13307                    long timeout = SystemClock.uptimeMillis() + 5000;
13308                    synchronized (conn) {
13309                        long now = SystemClock.uptimeMillis();
13310                        while (conn.mContainerService == null && now < timeout) {
13311                            try {
13312                                conn.wait(timeout - now);
13313                            } catch (InterruptedException e) {
13314                            }
13315                        }
13316                    }
13317                    if (conn.mContainerService == null) {
13318                        return;
13319                    }
13320
13321                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13322                    clearDirectory(conn.mContainerService,
13323                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13324                    if (allData) {
13325                        clearDirectory(conn.mContainerService,
13326                                userEnv.buildExternalStorageAppDataDirs(packageName));
13327                        clearDirectory(conn.mContainerService,
13328                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13329                    }
13330                }
13331            } finally {
13332                mContext.unbindService(conn);
13333            }
13334        }
13335    }
13336
13337    @Override
13338    public void clearApplicationUserData(final String packageName,
13339            final IPackageDataObserver observer, final int userId) {
13340        mContext.enforceCallingOrSelfPermission(
13341                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13342        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13343        // Queue up an async operation since the package deletion may take a little while.
13344        mHandler.post(new Runnable() {
13345            public void run() {
13346                mHandler.removeCallbacks(this);
13347                final boolean succeeded;
13348                synchronized (mInstallLock) {
13349                    succeeded = clearApplicationUserDataLI(packageName, userId);
13350                }
13351                clearExternalStorageDataSync(packageName, userId, true);
13352                if (succeeded) {
13353                    // invoke DeviceStorageMonitor's update method to clear any notifications
13354                    DeviceStorageMonitorInternal
13355                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13356                    if (dsm != null) {
13357                        dsm.checkMemory();
13358                    }
13359                }
13360                if(observer != null) {
13361                    try {
13362                        observer.onRemoveCompleted(packageName, succeeded);
13363                    } catch (RemoteException e) {
13364                        Log.i(TAG, "Observer no longer exists.");
13365                    }
13366                } //end if observer
13367            } //end run
13368        });
13369    }
13370
13371    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13372        if (packageName == null) {
13373            Slog.w(TAG, "Attempt to delete null packageName.");
13374            return false;
13375        }
13376
13377        // Try finding details about the requested package
13378        PackageParser.Package pkg;
13379        synchronized (mPackages) {
13380            pkg = mPackages.get(packageName);
13381            if (pkg == null) {
13382                final PackageSetting ps = mSettings.mPackages.get(packageName);
13383                if (ps != null) {
13384                    pkg = ps.pkg;
13385                }
13386            }
13387
13388            if (pkg == null) {
13389                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13390                return false;
13391            }
13392
13393            PackageSetting ps = (PackageSetting) pkg.mExtras;
13394            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13395        }
13396
13397        // Always delete data directories for package, even if we found no other
13398        // record of app. This helps users recover from UID mismatches without
13399        // resorting to a full data wipe.
13400        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13401        if (retCode < 0) {
13402            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13403            return false;
13404        }
13405
13406        final int appId = pkg.applicationInfo.uid;
13407        removeKeystoreDataIfNeeded(userId, appId);
13408
13409        // Create a native library symlink only if we have native libraries
13410        // and if the native libraries are 32 bit libraries. We do not provide
13411        // this symlink for 64 bit libraries.
13412        if (pkg.applicationInfo.primaryCpuAbi != null &&
13413                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13414            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13415            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13416                    nativeLibPath, userId) < 0) {
13417                Slog.w(TAG, "Failed linking native library dir");
13418                return false;
13419            }
13420        }
13421
13422        return true;
13423    }
13424
13425    /**
13426     * Reverts user permission state changes (permissions and flags) in
13427     * all packages for a given user.
13428     *
13429     * @param userId The device user for which to do a reset.
13430     */
13431    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13432        final int packageCount = mPackages.size();
13433        for (int i = 0; i < packageCount; i++) {
13434            PackageParser.Package pkg = mPackages.valueAt(i);
13435            PackageSetting ps = (PackageSetting) pkg.mExtras;
13436            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13437        }
13438    }
13439
13440    /**
13441     * Reverts user permission state changes (permissions and flags).
13442     *
13443     * @param ps The package for which to reset.
13444     * @param userId The device user for which to do a reset.
13445     */
13446    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13447            final PackageSetting ps, final int userId) {
13448        if (ps.pkg == null) {
13449            return;
13450        }
13451
13452        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13453                | FLAG_PERMISSION_USER_FIXED
13454                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13455
13456        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13457                | FLAG_PERMISSION_POLICY_FIXED;
13458
13459        boolean writeInstallPermissions = false;
13460        boolean writeRuntimePermissions = false;
13461
13462        final int permissionCount = ps.pkg.requestedPermissions.size();
13463        for (int i = 0; i < permissionCount; i++) {
13464            String permission = ps.pkg.requestedPermissions.get(i);
13465
13466            BasePermission bp = mSettings.mPermissions.get(permission);
13467            if (bp == null) {
13468                continue;
13469            }
13470
13471            // If shared user we just reset the state to which only this app contributed.
13472            if (ps.sharedUser != null) {
13473                boolean used = false;
13474                final int packageCount = ps.sharedUser.packages.size();
13475                for (int j = 0; j < packageCount; j++) {
13476                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13477                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13478                            && pkg.pkg.requestedPermissions.contains(permission)) {
13479                        used = true;
13480                        break;
13481                    }
13482                }
13483                if (used) {
13484                    continue;
13485                }
13486            }
13487
13488            PermissionsState permissionsState = ps.getPermissionsState();
13489
13490            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13491
13492            // Always clear the user settable flags.
13493            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13494                    bp.name) != null;
13495            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13496                if (hasInstallState) {
13497                    writeInstallPermissions = true;
13498                } else {
13499                    writeRuntimePermissions = true;
13500                }
13501            }
13502
13503            // Below is only runtime permission handling.
13504            if (!bp.isRuntime()) {
13505                continue;
13506            }
13507
13508            // Never clobber system or policy.
13509            if ((oldFlags & policyOrSystemFlags) != 0) {
13510                continue;
13511            }
13512
13513            // If this permission was granted by default, make sure it is.
13514            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13515                if (permissionsState.grantRuntimePermission(bp, userId)
13516                        != PERMISSION_OPERATION_FAILURE) {
13517                    writeRuntimePermissions = true;
13518                }
13519            } else {
13520                // Otherwise, reset the permission.
13521                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13522                switch (revokeResult) {
13523                    case PERMISSION_OPERATION_SUCCESS: {
13524                        writeRuntimePermissions = true;
13525                    } break;
13526
13527                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13528                        writeRuntimePermissions = true;
13529                        final int appId = ps.appId;
13530                        mHandler.post(new Runnable() {
13531                            @Override
13532                            public void run() {
13533                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13534                            }
13535                        });
13536                    } break;
13537                }
13538            }
13539        }
13540
13541        // Synchronously write as we are taking permissions away.
13542        if (writeRuntimePermissions) {
13543            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13544        }
13545
13546        // Synchronously write as we are taking permissions away.
13547        if (writeInstallPermissions) {
13548            mSettings.writeLPr();
13549        }
13550    }
13551
13552    /**
13553     * Remove entries from the keystore daemon. Will only remove it if the
13554     * {@code appId} is valid.
13555     */
13556    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13557        if (appId < 0) {
13558            return;
13559        }
13560
13561        final KeyStore keyStore = KeyStore.getInstance();
13562        if (keyStore != null) {
13563            if (userId == UserHandle.USER_ALL) {
13564                for (final int individual : sUserManager.getUserIds()) {
13565                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13566                }
13567            } else {
13568                keyStore.clearUid(UserHandle.getUid(userId, appId));
13569            }
13570        } else {
13571            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13572        }
13573    }
13574
13575    @Override
13576    public void deleteApplicationCacheFiles(final String packageName,
13577            final IPackageDataObserver observer) {
13578        mContext.enforceCallingOrSelfPermission(
13579                android.Manifest.permission.DELETE_CACHE_FILES, null);
13580        // Queue up an async operation since the package deletion may take a little while.
13581        final int userId = UserHandle.getCallingUserId();
13582        mHandler.post(new Runnable() {
13583            public void run() {
13584                mHandler.removeCallbacks(this);
13585                final boolean succeded;
13586                synchronized (mInstallLock) {
13587                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13588                }
13589                clearExternalStorageDataSync(packageName, userId, false);
13590                if (observer != null) {
13591                    try {
13592                        observer.onRemoveCompleted(packageName, succeded);
13593                    } catch (RemoteException e) {
13594                        Log.i(TAG, "Observer no longer exists.");
13595                    }
13596                } //end if observer
13597            } //end run
13598        });
13599    }
13600
13601    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13602        if (packageName == null) {
13603            Slog.w(TAG, "Attempt to delete null packageName.");
13604            return false;
13605        }
13606        PackageParser.Package p;
13607        synchronized (mPackages) {
13608            p = mPackages.get(packageName);
13609        }
13610        if (p == null) {
13611            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13612            return false;
13613        }
13614        final ApplicationInfo applicationInfo = p.applicationInfo;
13615        if (applicationInfo == null) {
13616            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13617            return false;
13618        }
13619        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13620        if (retCode < 0) {
13621            Slog.w(TAG, "Couldn't remove cache files for package: "
13622                       + packageName + " u" + userId);
13623            return false;
13624        }
13625        return true;
13626    }
13627
13628    @Override
13629    public void getPackageSizeInfo(final String packageName, int userHandle,
13630            final IPackageStatsObserver observer) {
13631        mContext.enforceCallingOrSelfPermission(
13632                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13633        if (packageName == null) {
13634            throw new IllegalArgumentException("Attempt to get size of null packageName");
13635        }
13636
13637        PackageStats stats = new PackageStats(packageName, userHandle);
13638
13639        /*
13640         * Queue up an async operation since the package measurement may take a
13641         * little while.
13642         */
13643        Message msg = mHandler.obtainMessage(INIT_COPY);
13644        msg.obj = new MeasureParams(stats, observer);
13645        mHandler.sendMessage(msg);
13646    }
13647
13648    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13649            PackageStats pStats) {
13650        if (packageName == null) {
13651            Slog.w(TAG, "Attempt to get size of null packageName.");
13652            return false;
13653        }
13654        PackageParser.Package p;
13655        boolean dataOnly = false;
13656        String libDirRoot = null;
13657        String asecPath = null;
13658        PackageSetting ps = null;
13659        synchronized (mPackages) {
13660            p = mPackages.get(packageName);
13661            ps = mSettings.mPackages.get(packageName);
13662            if(p == null) {
13663                dataOnly = true;
13664                if((ps == null) || (ps.pkg == null)) {
13665                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13666                    return false;
13667                }
13668                p = ps.pkg;
13669            }
13670            if (ps != null) {
13671                libDirRoot = ps.legacyNativeLibraryPathString;
13672            }
13673            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
13674                final long token = Binder.clearCallingIdentity();
13675                try {
13676                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13677                    if (secureContainerId != null) {
13678                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13679                    }
13680                } finally {
13681                    Binder.restoreCallingIdentity(token);
13682                }
13683            }
13684        }
13685        String publicSrcDir = null;
13686        if(!dataOnly) {
13687            final ApplicationInfo applicationInfo = p.applicationInfo;
13688            if (applicationInfo == null) {
13689                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13690                return false;
13691            }
13692            if (p.isForwardLocked()) {
13693                publicSrcDir = applicationInfo.getBaseResourcePath();
13694            }
13695        }
13696        // TODO: extend to measure size of split APKs
13697        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13698        // not just the first level.
13699        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13700        // just the primary.
13701        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13702
13703        String apkPath;
13704        File packageDir = new File(p.codePath);
13705
13706        if (packageDir.isDirectory() && p.canHaveOatDir()) {
13707            apkPath = packageDir.getAbsolutePath();
13708            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
13709            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
13710                libDirRoot = null;
13711            }
13712        } else {
13713            apkPath = p.baseCodePath;
13714        }
13715
13716        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
13717                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13718        if (res < 0) {
13719            return false;
13720        }
13721
13722        // Fix-up for forward-locked applications in ASEC containers.
13723        if (!isExternal(p)) {
13724            pStats.codeSize += pStats.externalCodeSize;
13725            pStats.externalCodeSize = 0L;
13726        }
13727
13728        return true;
13729    }
13730
13731
13732    @Override
13733    public void addPackageToPreferred(String packageName) {
13734        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13735    }
13736
13737    @Override
13738    public void removePackageFromPreferred(String packageName) {
13739        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13740    }
13741
13742    @Override
13743    public List<PackageInfo> getPreferredPackages(int flags) {
13744        return new ArrayList<PackageInfo>();
13745    }
13746
13747    private int getUidTargetSdkVersionLockedLPr(int uid) {
13748        Object obj = mSettings.getUserIdLPr(uid);
13749        if (obj instanceof SharedUserSetting) {
13750            final SharedUserSetting sus = (SharedUserSetting) obj;
13751            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13752            final Iterator<PackageSetting> it = sus.packages.iterator();
13753            while (it.hasNext()) {
13754                final PackageSetting ps = it.next();
13755                if (ps.pkg != null) {
13756                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13757                    if (v < vers) vers = v;
13758                }
13759            }
13760            return vers;
13761        } else if (obj instanceof PackageSetting) {
13762            final PackageSetting ps = (PackageSetting) obj;
13763            if (ps.pkg != null) {
13764                return ps.pkg.applicationInfo.targetSdkVersion;
13765            }
13766        }
13767        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13768    }
13769
13770    @Override
13771    public void addPreferredActivity(IntentFilter filter, int match,
13772            ComponentName[] set, ComponentName activity, int userId) {
13773        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13774                "Adding preferred");
13775    }
13776
13777    private void addPreferredActivityInternal(IntentFilter filter, int match,
13778            ComponentName[] set, ComponentName activity, boolean always, int userId,
13779            String opname) {
13780        // writer
13781        int callingUid = Binder.getCallingUid();
13782        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13783        if (filter.countActions() == 0) {
13784            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13785            return;
13786        }
13787        synchronized (mPackages) {
13788            if (mContext.checkCallingOrSelfPermission(
13789                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13790                    != PackageManager.PERMISSION_GRANTED) {
13791                if (getUidTargetSdkVersionLockedLPr(callingUid)
13792                        < Build.VERSION_CODES.FROYO) {
13793                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13794                            + callingUid);
13795                    return;
13796                }
13797                mContext.enforceCallingOrSelfPermission(
13798                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13799            }
13800
13801            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13802            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13803                    + userId + ":");
13804            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13805            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13806            scheduleWritePackageRestrictionsLocked(userId);
13807        }
13808    }
13809
13810    @Override
13811    public void replacePreferredActivity(IntentFilter filter, int match,
13812            ComponentName[] set, ComponentName activity, int userId) {
13813        if (filter.countActions() != 1) {
13814            throw new IllegalArgumentException(
13815                    "replacePreferredActivity expects filter to have only 1 action.");
13816        }
13817        if (filter.countDataAuthorities() != 0
13818                || filter.countDataPaths() != 0
13819                || filter.countDataSchemes() > 1
13820                || filter.countDataTypes() != 0) {
13821            throw new IllegalArgumentException(
13822                    "replacePreferredActivity expects filter to have no data authorities, " +
13823                    "paths, or types; and at most one scheme.");
13824        }
13825
13826        final int callingUid = Binder.getCallingUid();
13827        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13828        synchronized (mPackages) {
13829            if (mContext.checkCallingOrSelfPermission(
13830                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13831                    != PackageManager.PERMISSION_GRANTED) {
13832                if (getUidTargetSdkVersionLockedLPr(callingUid)
13833                        < Build.VERSION_CODES.FROYO) {
13834                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13835                            + Binder.getCallingUid());
13836                    return;
13837                }
13838                mContext.enforceCallingOrSelfPermission(
13839                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13840            }
13841
13842            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13843            if (pir != null) {
13844                // Get all of the existing entries that exactly match this filter.
13845                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13846                if (existing != null && existing.size() == 1) {
13847                    PreferredActivity cur = existing.get(0);
13848                    if (DEBUG_PREFERRED) {
13849                        Slog.i(TAG, "Checking replace of preferred:");
13850                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13851                        if (!cur.mPref.mAlways) {
13852                            Slog.i(TAG, "  -- CUR; not mAlways!");
13853                        } else {
13854                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13855                            Slog.i(TAG, "  -- CUR: mSet="
13856                                    + Arrays.toString(cur.mPref.mSetComponents));
13857                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13858                            Slog.i(TAG, "  -- NEW: mMatch="
13859                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13860                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13861                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13862                        }
13863                    }
13864                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13865                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13866                            && cur.mPref.sameSet(set)) {
13867                        // Setting the preferred activity to what it happens to be already
13868                        if (DEBUG_PREFERRED) {
13869                            Slog.i(TAG, "Replacing with same preferred activity "
13870                                    + cur.mPref.mShortComponent + " for user "
13871                                    + userId + ":");
13872                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13873                        }
13874                        return;
13875                    }
13876                }
13877
13878                if (existing != null) {
13879                    if (DEBUG_PREFERRED) {
13880                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13881                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13882                    }
13883                    for (int i = 0; i < existing.size(); i++) {
13884                        PreferredActivity pa = existing.get(i);
13885                        if (DEBUG_PREFERRED) {
13886                            Slog.i(TAG, "Removing existing preferred activity "
13887                                    + pa.mPref.mComponent + ":");
13888                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13889                        }
13890                        pir.removeFilter(pa);
13891                    }
13892                }
13893            }
13894            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13895                    "Replacing preferred");
13896        }
13897    }
13898
13899    @Override
13900    public void clearPackagePreferredActivities(String packageName) {
13901        final int uid = Binder.getCallingUid();
13902        // writer
13903        synchronized (mPackages) {
13904            PackageParser.Package pkg = mPackages.get(packageName);
13905            if (pkg == null || pkg.applicationInfo.uid != uid) {
13906                if (mContext.checkCallingOrSelfPermission(
13907                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13908                        != PackageManager.PERMISSION_GRANTED) {
13909                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13910                            < Build.VERSION_CODES.FROYO) {
13911                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13912                                + Binder.getCallingUid());
13913                        return;
13914                    }
13915                    mContext.enforceCallingOrSelfPermission(
13916                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13917                }
13918            }
13919
13920            int user = UserHandle.getCallingUserId();
13921            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13922                scheduleWritePackageRestrictionsLocked(user);
13923            }
13924        }
13925    }
13926
13927    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13928    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13929        ArrayList<PreferredActivity> removed = null;
13930        boolean changed = false;
13931        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13932            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13933            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13934            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13935                continue;
13936            }
13937            Iterator<PreferredActivity> it = pir.filterIterator();
13938            while (it.hasNext()) {
13939                PreferredActivity pa = it.next();
13940                // Mark entry for removal only if it matches the package name
13941                // and the entry is of type "always".
13942                if (packageName == null ||
13943                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13944                                && pa.mPref.mAlways)) {
13945                    if (removed == null) {
13946                        removed = new ArrayList<PreferredActivity>();
13947                    }
13948                    removed.add(pa);
13949                }
13950            }
13951            if (removed != null) {
13952                for (int j=0; j<removed.size(); j++) {
13953                    PreferredActivity pa = removed.get(j);
13954                    pir.removeFilter(pa);
13955                }
13956                changed = true;
13957            }
13958        }
13959        return changed;
13960    }
13961
13962    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13963    private void clearIntentFilterVerificationsLPw(int userId) {
13964        final int packageCount = mPackages.size();
13965        for (int i = 0; i < packageCount; i++) {
13966            PackageParser.Package pkg = mPackages.valueAt(i);
13967            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13968        }
13969    }
13970
13971    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13972    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13973        if (userId == UserHandle.USER_ALL) {
13974            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13975                    sUserManager.getUserIds())) {
13976                for (int oneUserId : sUserManager.getUserIds()) {
13977                    scheduleWritePackageRestrictionsLocked(oneUserId);
13978                }
13979            }
13980        } else {
13981            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13982                scheduleWritePackageRestrictionsLocked(userId);
13983            }
13984        }
13985    }
13986
13987    void clearDefaultBrowserIfNeeded(String packageName) {
13988        for (int oneUserId : sUserManager.getUserIds()) {
13989            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13990            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13991            if (packageName.equals(defaultBrowserPackageName)) {
13992                setDefaultBrowserPackageName(null, oneUserId);
13993            }
13994        }
13995    }
13996
13997    @Override
13998    public void resetApplicationPreferences(int userId) {
13999        mContext.enforceCallingOrSelfPermission(
14000                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14001        // writer
14002        synchronized (mPackages) {
14003            final long identity = Binder.clearCallingIdentity();
14004            try {
14005                clearPackagePreferredActivitiesLPw(null, userId);
14006                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14007                // TODO: We have to reset the default SMS and Phone. This requires
14008                // significant refactoring to keep all default apps in the package
14009                // manager (cleaner but more work) or have the services provide
14010                // callbacks to the package manager to request a default app reset.
14011                applyFactoryDefaultBrowserLPw(userId);
14012                clearIntentFilterVerificationsLPw(userId);
14013                primeDomainVerificationsLPw(userId);
14014                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14015                scheduleWritePackageRestrictionsLocked(userId);
14016            } finally {
14017                Binder.restoreCallingIdentity(identity);
14018            }
14019        }
14020    }
14021
14022    @Override
14023    public int getPreferredActivities(List<IntentFilter> outFilters,
14024            List<ComponentName> outActivities, String packageName) {
14025
14026        int num = 0;
14027        final int userId = UserHandle.getCallingUserId();
14028        // reader
14029        synchronized (mPackages) {
14030            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14031            if (pir != null) {
14032                final Iterator<PreferredActivity> it = pir.filterIterator();
14033                while (it.hasNext()) {
14034                    final PreferredActivity pa = it.next();
14035                    if (packageName == null
14036                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14037                                    && pa.mPref.mAlways)) {
14038                        if (outFilters != null) {
14039                            outFilters.add(new IntentFilter(pa));
14040                        }
14041                        if (outActivities != null) {
14042                            outActivities.add(pa.mPref.mComponent);
14043                        }
14044                    }
14045                }
14046            }
14047        }
14048
14049        return num;
14050    }
14051
14052    @Override
14053    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14054            int userId) {
14055        int callingUid = Binder.getCallingUid();
14056        if (callingUid != Process.SYSTEM_UID) {
14057            throw new SecurityException(
14058                    "addPersistentPreferredActivity can only be run by the system");
14059        }
14060        if (filter.countActions() == 0) {
14061            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14062            return;
14063        }
14064        synchronized (mPackages) {
14065            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14066                    " :");
14067            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14068            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14069                    new PersistentPreferredActivity(filter, activity));
14070            scheduleWritePackageRestrictionsLocked(userId);
14071        }
14072    }
14073
14074    @Override
14075    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14076        int callingUid = Binder.getCallingUid();
14077        if (callingUid != Process.SYSTEM_UID) {
14078            throw new SecurityException(
14079                    "clearPackagePersistentPreferredActivities can only be run by the system");
14080        }
14081        ArrayList<PersistentPreferredActivity> removed = null;
14082        boolean changed = false;
14083        synchronized (mPackages) {
14084            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14085                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14086                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14087                        .valueAt(i);
14088                if (userId != thisUserId) {
14089                    continue;
14090                }
14091                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14092                while (it.hasNext()) {
14093                    PersistentPreferredActivity ppa = it.next();
14094                    // Mark entry for removal only if it matches the package name.
14095                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14096                        if (removed == null) {
14097                            removed = new ArrayList<PersistentPreferredActivity>();
14098                        }
14099                        removed.add(ppa);
14100                    }
14101                }
14102                if (removed != null) {
14103                    for (int j=0; j<removed.size(); j++) {
14104                        PersistentPreferredActivity ppa = removed.get(j);
14105                        ppir.removeFilter(ppa);
14106                    }
14107                    changed = true;
14108                }
14109            }
14110
14111            if (changed) {
14112                scheduleWritePackageRestrictionsLocked(userId);
14113            }
14114        }
14115    }
14116
14117    /**
14118     * Common machinery for picking apart a restored XML blob and passing
14119     * it to a caller-supplied functor to be applied to the running system.
14120     */
14121    private void restoreFromXml(XmlPullParser parser, int userId,
14122            String expectedStartTag, BlobXmlRestorer functor)
14123            throws IOException, XmlPullParserException {
14124        int type;
14125        while ((type = parser.next()) != XmlPullParser.START_TAG
14126                && type != XmlPullParser.END_DOCUMENT) {
14127        }
14128        if (type != XmlPullParser.START_TAG) {
14129            // oops didn't find a start tag?!
14130            if (DEBUG_BACKUP) {
14131                Slog.e(TAG, "Didn't find start tag during restore");
14132            }
14133            return;
14134        }
14135
14136        // this is supposed to be TAG_PREFERRED_BACKUP
14137        if (!expectedStartTag.equals(parser.getName())) {
14138            if (DEBUG_BACKUP) {
14139                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14140            }
14141            return;
14142        }
14143
14144        // skip interfering stuff, then we're aligned with the backing implementation
14145        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14146        functor.apply(parser, userId);
14147    }
14148
14149    private interface BlobXmlRestorer {
14150        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14151    }
14152
14153    /**
14154     * Non-Binder method, support for the backup/restore mechanism: write the
14155     * full set of preferred activities in its canonical XML format.  Returns the
14156     * XML output as a byte array, or null if there is none.
14157     */
14158    @Override
14159    public byte[] getPreferredActivityBackup(int userId) {
14160        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14161            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14162        }
14163
14164        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14165        try {
14166            final XmlSerializer serializer = new FastXmlSerializer();
14167            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14168            serializer.startDocument(null, true);
14169            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14170
14171            synchronized (mPackages) {
14172                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14173            }
14174
14175            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14176            serializer.endDocument();
14177            serializer.flush();
14178        } catch (Exception e) {
14179            if (DEBUG_BACKUP) {
14180                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14181            }
14182            return null;
14183        }
14184
14185        return dataStream.toByteArray();
14186    }
14187
14188    @Override
14189    public void restorePreferredActivities(byte[] backup, int userId) {
14190        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14191            throw new SecurityException("Only the system may call restorePreferredActivities()");
14192        }
14193
14194        try {
14195            final XmlPullParser parser = Xml.newPullParser();
14196            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14197            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14198                    new BlobXmlRestorer() {
14199                        @Override
14200                        public void apply(XmlPullParser parser, int userId)
14201                                throws XmlPullParserException, IOException {
14202                            synchronized (mPackages) {
14203                                mSettings.readPreferredActivitiesLPw(parser, userId);
14204                            }
14205                        }
14206                    } );
14207        } catch (Exception e) {
14208            if (DEBUG_BACKUP) {
14209                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14210            }
14211        }
14212    }
14213
14214    /**
14215     * Non-Binder method, support for the backup/restore mechanism: write the
14216     * default browser (etc) settings in its canonical XML format.  Returns the default
14217     * browser XML representation as a byte array, or null if there is none.
14218     */
14219    @Override
14220    public byte[] getDefaultAppsBackup(int userId) {
14221        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14222            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14223        }
14224
14225        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14226        try {
14227            final XmlSerializer serializer = new FastXmlSerializer();
14228            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14229            serializer.startDocument(null, true);
14230            serializer.startTag(null, TAG_DEFAULT_APPS);
14231
14232            synchronized (mPackages) {
14233                mSettings.writeDefaultAppsLPr(serializer, userId);
14234            }
14235
14236            serializer.endTag(null, TAG_DEFAULT_APPS);
14237            serializer.endDocument();
14238            serializer.flush();
14239        } catch (Exception e) {
14240            if (DEBUG_BACKUP) {
14241                Slog.e(TAG, "Unable to write default apps for backup", e);
14242            }
14243            return null;
14244        }
14245
14246        return dataStream.toByteArray();
14247    }
14248
14249    @Override
14250    public void restoreDefaultApps(byte[] backup, int userId) {
14251        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14252            throw new SecurityException("Only the system may call restoreDefaultApps()");
14253        }
14254
14255        try {
14256            final XmlPullParser parser = Xml.newPullParser();
14257            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14258            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14259                    new BlobXmlRestorer() {
14260                        @Override
14261                        public void apply(XmlPullParser parser, int userId)
14262                                throws XmlPullParserException, IOException {
14263                            synchronized (mPackages) {
14264                                mSettings.readDefaultAppsLPw(parser, userId);
14265                            }
14266                        }
14267                    } );
14268        } catch (Exception e) {
14269            if (DEBUG_BACKUP) {
14270                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14271            }
14272        }
14273    }
14274
14275    @Override
14276    public byte[] getIntentFilterVerificationBackup(int userId) {
14277        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14278            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14279        }
14280
14281        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14282        try {
14283            final XmlSerializer serializer = new FastXmlSerializer();
14284            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14285            serializer.startDocument(null, true);
14286            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14287
14288            synchronized (mPackages) {
14289                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14290            }
14291
14292            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14293            serializer.endDocument();
14294            serializer.flush();
14295        } catch (Exception e) {
14296            if (DEBUG_BACKUP) {
14297                Slog.e(TAG, "Unable to write default apps for backup", e);
14298            }
14299            return null;
14300        }
14301
14302        return dataStream.toByteArray();
14303    }
14304
14305    @Override
14306    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14307        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14308            throw new SecurityException("Only the system may call restorePreferredActivities()");
14309        }
14310
14311        try {
14312            final XmlPullParser parser = Xml.newPullParser();
14313            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14314            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14315                    new BlobXmlRestorer() {
14316                        @Override
14317                        public void apply(XmlPullParser parser, int userId)
14318                                throws XmlPullParserException, IOException {
14319                            synchronized (mPackages) {
14320                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14321                                mSettings.writeLPr();
14322                            }
14323                        }
14324                    } );
14325        } catch (Exception e) {
14326            if (DEBUG_BACKUP) {
14327                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14328            }
14329        }
14330    }
14331
14332    @Override
14333    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14334            int sourceUserId, int targetUserId, int flags) {
14335        mContext.enforceCallingOrSelfPermission(
14336                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14337        int callingUid = Binder.getCallingUid();
14338        enforceOwnerRights(ownerPackage, callingUid);
14339        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14340        if (intentFilter.countActions() == 0) {
14341            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14342            return;
14343        }
14344        synchronized (mPackages) {
14345            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14346                    ownerPackage, targetUserId, flags);
14347            CrossProfileIntentResolver resolver =
14348                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14349            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14350            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14351            if (existing != null) {
14352                int size = existing.size();
14353                for (int i = 0; i < size; i++) {
14354                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14355                        return;
14356                    }
14357                }
14358            }
14359            resolver.addFilter(newFilter);
14360            scheduleWritePackageRestrictionsLocked(sourceUserId);
14361        }
14362    }
14363
14364    @Override
14365    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14366        mContext.enforceCallingOrSelfPermission(
14367                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14368        int callingUid = Binder.getCallingUid();
14369        enforceOwnerRights(ownerPackage, callingUid);
14370        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14371        synchronized (mPackages) {
14372            CrossProfileIntentResolver resolver =
14373                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14374            ArraySet<CrossProfileIntentFilter> set =
14375                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14376            for (CrossProfileIntentFilter filter : set) {
14377                if (filter.getOwnerPackage().equals(ownerPackage)) {
14378                    resolver.removeFilter(filter);
14379                }
14380            }
14381            scheduleWritePackageRestrictionsLocked(sourceUserId);
14382        }
14383    }
14384
14385    // Enforcing that callingUid is owning pkg on userId
14386    private void enforceOwnerRights(String pkg, int callingUid) {
14387        // The system owns everything.
14388        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14389            return;
14390        }
14391        int callingUserId = UserHandle.getUserId(callingUid);
14392        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14393        if (pi == null) {
14394            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14395                    + callingUserId);
14396        }
14397        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14398            throw new SecurityException("Calling uid " + callingUid
14399                    + " does not own package " + pkg);
14400        }
14401    }
14402
14403    @Override
14404    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14405        Intent intent = new Intent(Intent.ACTION_MAIN);
14406        intent.addCategory(Intent.CATEGORY_HOME);
14407
14408        final int callingUserId = UserHandle.getCallingUserId();
14409        List<ResolveInfo> list = queryIntentActivities(intent, null,
14410                PackageManager.GET_META_DATA, callingUserId);
14411        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14412                true, false, false, callingUserId);
14413
14414        allHomeCandidates.clear();
14415        if (list != null) {
14416            for (ResolveInfo ri : list) {
14417                allHomeCandidates.add(ri);
14418            }
14419        }
14420        return (preferred == null || preferred.activityInfo == null)
14421                ? null
14422                : new ComponentName(preferred.activityInfo.packageName,
14423                        preferred.activityInfo.name);
14424    }
14425
14426    @Override
14427    public void setApplicationEnabledSetting(String appPackageName,
14428            int newState, int flags, int userId, String callingPackage) {
14429        if (!sUserManager.exists(userId)) return;
14430        if (callingPackage == null) {
14431            callingPackage = Integer.toString(Binder.getCallingUid());
14432        }
14433        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14434    }
14435
14436    @Override
14437    public void setComponentEnabledSetting(ComponentName componentName,
14438            int newState, int flags, int userId) {
14439        if (!sUserManager.exists(userId)) return;
14440        setEnabledSetting(componentName.getPackageName(),
14441                componentName.getClassName(), newState, flags, userId, null);
14442    }
14443
14444    private void setEnabledSetting(final String packageName, String className, int newState,
14445            final int flags, int userId, String callingPackage) {
14446        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14447              || newState == COMPONENT_ENABLED_STATE_ENABLED
14448              || newState == COMPONENT_ENABLED_STATE_DISABLED
14449              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14450              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14451            throw new IllegalArgumentException("Invalid new component state: "
14452                    + newState);
14453        }
14454        PackageSetting pkgSetting;
14455        final int uid = Binder.getCallingUid();
14456        final int permission = mContext.checkCallingOrSelfPermission(
14457                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14458        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14459        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14460        boolean sendNow = false;
14461        boolean isApp = (className == null);
14462        String componentName = isApp ? packageName : className;
14463        int packageUid = -1;
14464        ArrayList<String> components;
14465
14466        // writer
14467        synchronized (mPackages) {
14468            pkgSetting = mSettings.mPackages.get(packageName);
14469            if (pkgSetting == null) {
14470                if (className == null) {
14471                    throw new IllegalArgumentException(
14472                            "Unknown package: " + packageName);
14473                }
14474                throw new IllegalArgumentException(
14475                        "Unknown component: " + packageName
14476                        + "/" + className);
14477            }
14478            // Allow root and verify that userId is not being specified by a different user
14479            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14480                throw new SecurityException(
14481                        "Permission Denial: attempt to change component state from pid="
14482                        + Binder.getCallingPid()
14483                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14484            }
14485            if (className == null) {
14486                // We're dealing with an application/package level state change
14487                if (pkgSetting.getEnabled(userId) == newState) {
14488                    // Nothing to do
14489                    return;
14490                }
14491                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14492                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14493                    // Don't care about who enables an app.
14494                    callingPackage = null;
14495                }
14496                pkgSetting.setEnabled(newState, userId, callingPackage);
14497                // pkgSetting.pkg.mSetEnabled = newState;
14498            } else {
14499                // We're dealing with a component level state change
14500                // First, verify that this is a valid class name.
14501                PackageParser.Package pkg = pkgSetting.pkg;
14502                if (pkg == null || !pkg.hasComponentClassName(className)) {
14503                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14504                        throw new IllegalArgumentException("Component class " + className
14505                                + " does not exist in " + packageName);
14506                    } else {
14507                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14508                                + className + " does not exist in " + packageName);
14509                    }
14510                }
14511                switch (newState) {
14512                case COMPONENT_ENABLED_STATE_ENABLED:
14513                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14514                        return;
14515                    }
14516                    break;
14517                case COMPONENT_ENABLED_STATE_DISABLED:
14518                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14519                        return;
14520                    }
14521                    break;
14522                case COMPONENT_ENABLED_STATE_DEFAULT:
14523                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14524                        return;
14525                    }
14526                    break;
14527                default:
14528                    Slog.e(TAG, "Invalid new component state: " + newState);
14529                    return;
14530                }
14531            }
14532            scheduleWritePackageRestrictionsLocked(userId);
14533            components = mPendingBroadcasts.get(userId, packageName);
14534            final boolean newPackage = components == null;
14535            if (newPackage) {
14536                components = new ArrayList<String>();
14537            }
14538            if (!components.contains(componentName)) {
14539                components.add(componentName);
14540            }
14541            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14542                sendNow = true;
14543                // Purge entry from pending broadcast list if another one exists already
14544                // since we are sending one right away.
14545                mPendingBroadcasts.remove(userId, packageName);
14546            } else {
14547                if (newPackage) {
14548                    mPendingBroadcasts.put(userId, packageName, components);
14549                }
14550                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14551                    // Schedule a message
14552                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14553                }
14554            }
14555        }
14556
14557        long callingId = Binder.clearCallingIdentity();
14558        try {
14559            if (sendNow) {
14560                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14561                sendPackageChangedBroadcast(packageName,
14562                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14563            }
14564        } finally {
14565            Binder.restoreCallingIdentity(callingId);
14566        }
14567    }
14568
14569    private void sendPackageChangedBroadcast(String packageName,
14570            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14571        if (DEBUG_INSTALL)
14572            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14573                    + componentNames);
14574        Bundle extras = new Bundle(4);
14575        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14576        String nameList[] = new String[componentNames.size()];
14577        componentNames.toArray(nameList);
14578        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14579        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14580        extras.putInt(Intent.EXTRA_UID, packageUid);
14581        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14582                new int[] {UserHandle.getUserId(packageUid)});
14583    }
14584
14585    @Override
14586    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14587        if (!sUserManager.exists(userId)) return;
14588        final int uid = Binder.getCallingUid();
14589        final int permission = mContext.checkCallingOrSelfPermission(
14590                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14591        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14592        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14593        // writer
14594        synchronized (mPackages) {
14595            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14596                    allowedByPermission, uid, userId)) {
14597                scheduleWritePackageRestrictionsLocked(userId);
14598            }
14599        }
14600    }
14601
14602    @Override
14603    public String getInstallerPackageName(String packageName) {
14604        // reader
14605        synchronized (mPackages) {
14606            return mSettings.getInstallerPackageNameLPr(packageName);
14607        }
14608    }
14609
14610    @Override
14611    public int getApplicationEnabledSetting(String packageName, int userId) {
14612        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14613        int uid = Binder.getCallingUid();
14614        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14615        // reader
14616        synchronized (mPackages) {
14617            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14618        }
14619    }
14620
14621    @Override
14622    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14623        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14624        int uid = Binder.getCallingUid();
14625        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14626        // reader
14627        synchronized (mPackages) {
14628            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14629        }
14630    }
14631
14632    @Override
14633    public void enterSafeMode() {
14634        enforceSystemOrRoot("Only the system can request entering safe mode");
14635
14636        if (!mSystemReady) {
14637            mSafeMode = true;
14638        }
14639    }
14640
14641    @Override
14642    public void systemReady() {
14643        mSystemReady = true;
14644
14645        // Read the compatibilty setting when the system is ready.
14646        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14647                mContext.getContentResolver(),
14648                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14649        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14650        if (DEBUG_SETTINGS) {
14651            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14652        }
14653
14654        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14655
14656        synchronized (mPackages) {
14657            // Verify that all of the preferred activity components actually
14658            // exist.  It is possible for applications to be updated and at
14659            // that point remove a previously declared activity component that
14660            // had been set as a preferred activity.  We try to clean this up
14661            // the next time we encounter that preferred activity, but it is
14662            // possible for the user flow to never be able to return to that
14663            // situation so here we do a sanity check to make sure we haven't
14664            // left any junk around.
14665            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14666            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14667                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14668                removed.clear();
14669                for (PreferredActivity pa : pir.filterSet()) {
14670                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14671                        removed.add(pa);
14672                    }
14673                }
14674                if (removed.size() > 0) {
14675                    for (int r=0; r<removed.size(); r++) {
14676                        PreferredActivity pa = removed.get(r);
14677                        Slog.w(TAG, "Removing dangling preferred activity: "
14678                                + pa.mPref.mComponent);
14679                        pir.removeFilter(pa);
14680                    }
14681                    mSettings.writePackageRestrictionsLPr(
14682                            mSettings.mPreferredActivities.keyAt(i));
14683                }
14684            }
14685
14686            for (int userId : UserManagerService.getInstance().getUserIds()) {
14687                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14688                    grantPermissionsUserIds = ArrayUtils.appendInt(
14689                            grantPermissionsUserIds, userId);
14690                }
14691            }
14692        }
14693        sUserManager.systemReady();
14694
14695        // If we upgraded grant all default permissions before kicking off.
14696        for (int userId : grantPermissionsUserIds) {
14697            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14698        }
14699
14700        // Kick off any messages waiting for system ready
14701        if (mPostSystemReadyMessages != null) {
14702            for (Message msg : mPostSystemReadyMessages) {
14703                msg.sendToTarget();
14704            }
14705            mPostSystemReadyMessages = null;
14706        }
14707
14708        // Watch for external volumes that come and go over time
14709        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14710        storage.registerListener(mStorageListener);
14711
14712        mInstallerService.systemReady();
14713        mPackageDexOptimizer.systemReady();
14714
14715        MountServiceInternal mountServiceInternal = LocalServices.getService(
14716                MountServiceInternal.class);
14717        mountServiceInternal.addExternalStoragePolicy(
14718                new MountServiceInternal.ExternalStorageMountPolicy() {
14719            @Override
14720            public int getMountMode(int uid, String packageName) {
14721                if (Process.isIsolated(uid)) {
14722                    return Zygote.MOUNT_EXTERNAL_NONE;
14723                }
14724                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14725                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14726                }
14727                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14728                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14729                }
14730                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14731                    return Zygote.MOUNT_EXTERNAL_READ;
14732                }
14733                return Zygote.MOUNT_EXTERNAL_WRITE;
14734            }
14735
14736            @Override
14737            public boolean hasExternalStorage(int uid, String packageName) {
14738                return true;
14739            }
14740        });
14741    }
14742
14743    @Override
14744    public boolean isSafeMode() {
14745        return mSafeMode;
14746    }
14747
14748    @Override
14749    public boolean hasSystemUidErrors() {
14750        return mHasSystemUidErrors;
14751    }
14752
14753    static String arrayToString(int[] array) {
14754        StringBuffer buf = new StringBuffer(128);
14755        buf.append('[');
14756        if (array != null) {
14757            for (int i=0; i<array.length; i++) {
14758                if (i > 0) buf.append(", ");
14759                buf.append(array[i]);
14760            }
14761        }
14762        buf.append(']');
14763        return buf.toString();
14764    }
14765
14766    static class DumpState {
14767        public static final int DUMP_LIBS = 1 << 0;
14768        public static final int DUMP_FEATURES = 1 << 1;
14769        public static final int DUMP_RESOLVERS = 1 << 2;
14770        public static final int DUMP_PERMISSIONS = 1 << 3;
14771        public static final int DUMP_PACKAGES = 1 << 4;
14772        public static final int DUMP_SHARED_USERS = 1 << 5;
14773        public static final int DUMP_MESSAGES = 1 << 6;
14774        public static final int DUMP_PROVIDERS = 1 << 7;
14775        public static final int DUMP_VERIFIERS = 1 << 8;
14776        public static final int DUMP_PREFERRED = 1 << 9;
14777        public static final int DUMP_PREFERRED_XML = 1 << 10;
14778        public static final int DUMP_KEYSETS = 1 << 11;
14779        public static final int DUMP_VERSION = 1 << 12;
14780        public static final int DUMP_INSTALLS = 1 << 13;
14781        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14782        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14783
14784        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14785
14786        private int mTypes;
14787
14788        private int mOptions;
14789
14790        private boolean mTitlePrinted;
14791
14792        private SharedUserSetting mSharedUser;
14793
14794        public boolean isDumping(int type) {
14795            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14796                return true;
14797            }
14798
14799            return (mTypes & type) != 0;
14800        }
14801
14802        public void setDump(int type) {
14803            mTypes |= type;
14804        }
14805
14806        public boolean isOptionEnabled(int option) {
14807            return (mOptions & option) != 0;
14808        }
14809
14810        public void setOptionEnabled(int option) {
14811            mOptions |= option;
14812        }
14813
14814        public boolean onTitlePrinted() {
14815            final boolean printed = mTitlePrinted;
14816            mTitlePrinted = true;
14817            return printed;
14818        }
14819
14820        public boolean getTitlePrinted() {
14821            return mTitlePrinted;
14822        }
14823
14824        public void setTitlePrinted(boolean enabled) {
14825            mTitlePrinted = enabled;
14826        }
14827
14828        public SharedUserSetting getSharedUser() {
14829            return mSharedUser;
14830        }
14831
14832        public void setSharedUser(SharedUserSetting user) {
14833            mSharedUser = user;
14834        }
14835    }
14836
14837    @Override
14838    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14839        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14840                != PackageManager.PERMISSION_GRANTED) {
14841            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14842                    + Binder.getCallingPid()
14843                    + ", uid=" + Binder.getCallingUid()
14844                    + " without permission "
14845                    + android.Manifest.permission.DUMP);
14846            return;
14847        }
14848
14849        DumpState dumpState = new DumpState();
14850        boolean fullPreferred = false;
14851        boolean checkin = false;
14852
14853        String packageName = null;
14854        ArraySet<String> permissionNames = null;
14855
14856        int opti = 0;
14857        while (opti < args.length) {
14858            String opt = args[opti];
14859            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14860                break;
14861            }
14862            opti++;
14863
14864            if ("-a".equals(opt)) {
14865                // Right now we only know how to print all.
14866            } else if ("-h".equals(opt)) {
14867                pw.println("Package manager dump options:");
14868                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14869                pw.println("    --checkin: dump for a checkin");
14870                pw.println("    -f: print details of intent filters");
14871                pw.println("    -h: print this help");
14872                pw.println("  cmd may be one of:");
14873                pw.println("    l[ibraries]: list known shared libraries");
14874                pw.println("    f[ibraries]: list device features");
14875                pw.println("    k[eysets]: print known keysets");
14876                pw.println("    r[esolvers]: dump intent resolvers");
14877                pw.println("    perm[issions]: dump permissions");
14878                pw.println("    permission [name ...]: dump declaration and use of given permission");
14879                pw.println("    pref[erred]: print preferred package settings");
14880                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14881                pw.println("    prov[iders]: dump content providers");
14882                pw.println("    p[ackages]: dump installed packages");
14883                pw.println("    s[hared-users]: dump shared user IDs");
14884                pw.println("    m[essages]: print collected runtime messages");
14885                pw.println("    v[erifiers]: print package verifier info");
14886                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14887                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14888                pw.println("    version: print database version info");
14889                pw.println("    write: write current settings now");
14890                pw.println("    installs: details about install sessions");
14891                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
14892                pw.println("    <package.name>: info about given package");
14893                return;
14894            } else if ("--checkin".equals(opt)) {
14895                checkin = true;
14896            } else if ("-f".equals(opt)) {
14897                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14898            } else {
14899                pw.println("Unknown argument: " + opt + "; use -h for help");
14900            }
14901        }
14902
14903        // Is the caller requesting to dump a particular piece of data?
14904        if (opti < args.length) {
14905            String cmd = args[opti];
14906            opti++;
14907            // Is this a package name?
14908            if ("android".equals(cmd) || cmd.contains(".")) {
14909                packageName = cmd;
14910                // When dumping a single package, we always dump all of its
14911                // filter information since the amount of data will be reasonable.
14912                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14913            } else if ("check-permission".equals(cmd)) {
14914                if (opti >= args.length) {
14915                    pw.println("Error: check-permission missing permission argument");
14916                    return;
14917                }
14918                String perm = args[opti];
14919                opti++;
14920                if (opti >= args.length) {
14921                    pw.println("Error: check-permission missing package argument");
14922                    return;
14923                }
14924                String pkg = args[opti];
14925                opti++;
14926                int user = UserHandle.getUserId(Binder.getCallingUid());
14927                if (opti < args.length) {
14928                    try {
14929                        user = Integer.parseInt(args[opti]);
14930                    } catch (NumberFormatException e) {
14931                        pw.println("Error: check-permission user argument is not a number: "
14932                                + args[opti]);
14933                        return;
14934                    }
14935                }
14936                pw.println(checkPermission(perm, pkg, user));
14937                return;
14938            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14939                dumpState.setDump(DumpState.DUMP_LIBS);
14940            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14941                dumpState.setDump(DumpState.DUMP_FEATURES);
14942            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14943                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14944            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14945                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14946            } else if ("permission".equals(cmd)) {
14947                if (opti >= args.length) {
14948                    pw.println("Error: permission requires permission name");
14949                    return;
14950                }
14951                permissionNames = new ArraySet<>();
14952                while (opti < args.length) {
14953                    permissionNames.add(args[opti]);
14954                    opti++;
14955                }
14956                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14957                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14958            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14959                dumpState.setDump(DumpState.DUMP_PREFERRED);
14960            } else if ("preferred-xml".equals(cmd)) {
14961                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14962                if (opti < args.length && "--full".equals(args[opti])) {
14963                    fullPreferred = true;
14964                    opti++;
14965                }
14966            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14967                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14968            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14969                dumpState.setDump(DumpState.DUMP_PACKAGES);
14970            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14971                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14972            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14973                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14974            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14975                dumpState.setDump(DumpState.DUMP_MESSAGES);
14976            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14977                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14978            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14979                    || "intent-filter-verifiers".equals(cmd)) {
14980                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14981            } else if ("version".equals(cmd)) {
14982                dumpState.setDump(DumpState.DUMP_VERSION);
14983            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14984                dumpState.setDump(DumpState.DUMP_KEYSETS);
14985            } else if ("installs".equals(cmd)) {
14986                dumpState.setDump(DumpState.DUMP_INSTALLS);
14987            } else if ("write".equals(cmd)) {
14988                synchronized (mPackages) {
14989                    mSettings.writeLPr();
14990                    pw.println("Settings written.");
14991                    return;
14992                }
14993            }
14994        }
14995
14996        if (checkin) {
14997            pw.println("vers,1");
14998        }
14999
15000        // reader
15001        synchronized (mPackages) {
15002            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15003                if (!checkin) {
15004                    if (dumpState.onTitlePrinted())
15005                        pw.println();
15006                    pw.println("Database versions:");
15007                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15008                }
15009            }
15010
15011            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15012                if (!checkin) {
15013                    if (dumpState.onTitlePrinted())
15014                        pw.println();
15015                    pw.println("Verifiers:");
15016                    pw.print("  Required: ");
15017                    pw.print(mRequiredVerifierPackage);
15018                    pw.print(" (uid=");
15019                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15020                    pw.println(")");
15021                } else if (mRequiredVerifierPackage != null) {
15022                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15023                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15024                }
15025            }
15026
15027            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15028                    packageName == null) {
15029                if (mIntentFilterVerifierComponent != null) {
15030                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15031                    if (!checkin) {
15032                        if (dumpState.onTitlePrinted())
15033                            pw.println();
15034                        pw.println("Intent Filter Verifier:");
15035                        pw.print("  Using: ");
15036                        pw.print(verifierPackageName);
15037                        pw.print(" (uid=");
15038                        pw.print(getPackageUid(verifierPackageName, 0));
15039                        pw.println(")");
15040                    } else if (verifierPackageName != null) {
15041                        pw.print("ifv,"); pw.print(verifierPackageName);
15042                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15043                    }
15044                } else {
15045                    pw.println();
15046                    pw.println("No Intent Filter Verifier available!");
15047                }
15048            }
15049
15050            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15051                boolean printedHeader = false;
15052                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15053                while (it.hasNext()) {
15054                    String name = it.next();
15055                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15056                    if (!checkin) {
15057                        if (!printedHeader) {
15058                            if (dumpState.onTitlePrinted())
15059                                pw.println();
15060                            pw.println("Libraries:");
15061                            printedHeader = true;
15062                        }
15063                        pw.print("  ");
15064                    } else {
15065                        pw.print("lib,");
15066                    }
15067                    pw.print(name);
15068                    if (!checkin) {
15069                        pw.print(" -> ");
15070                    }
15071                    if (ent.path != null) {
15072                        if (!checkin) {
15073                            pw.print("(jar) ");
15074                            pw.print(ent.path);
15075                        } else {
15076                            pw.print(",jar,");
15077                            pw.print(ent.path);
15078                        }
15079                    } else {
15080                        if (!checkin) {
15081                            pw.print("(apk) ");
15082                            pw.print(ent.apk);
15083                        } else {
15084                            pw.print(",apk,");
15085                            pw.print(ent.apk);
15086                        }
15087                    }
15088                    pw.println();
15089                }
15090            }
15091
15092            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15093                if (dumpState.onTitlePrinted())
15094                    pw.println();
15095                if (!checkin) {
15096                    pw.println("Features:");
15097                }
15098                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15099                while (it.hasNext()) {
15100                    String name = it.next();
15101                    if (!checkin) {
15102                        pw.print("  ");
15103                    } else {
15104                        pw.print("feat,");
15105                    }
15106                    pw.println(name);
15107                }
15108            }
15109
15110            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15111                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15112                        : "Activity Resolver Table:", "  ", packageName,
15113                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15114                    dumpState.setTitlePrinted(true);
15115                }
15116                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15117                        : "Receiver Resolver Table:", "  ", packageName,
15118                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15119                    dumpState.setTitlePrinted(true);
15120                }
15121                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15122                        : "Service Resolver Table:", "  ", packageName,
15123                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15124                    dumpState.setTitlePrinted(true);
15125                }
15126                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15127                        : "Provider Resolver Table:", "  ", packageName,
15128                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15129                    dumpState.setTitlePrinted(true);
15130                }
15131            }
15132
15133            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15134                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15135                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15136                    int user = mSettings.mPreferredActivities.keyAt(i);
15137                    if (pir.dump(pw,
15138                            dumpState.getTitlePrinted()
15139                                ? "\nPreferred Activities User " + user + ":"
15140                                : "Preferred Activities User " + user + ":", "  ",
15141                            packageName, true, false)) {
15142                        dumpState.setTitlePrinted(true);
15143                    }
15144                }
15145            }
15146
15147            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15148                pw.flush();
15149                FileOutputStream fout = new FileOutputStream(fd);
15150                BufferedOutputStream str = new BufferedOutputStream(fout);
15151                XmlSerializer serializer = new FastXmlSerializer();
15152                try {
15153                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15154                    serializer.startDocument(null, true);
15155                    serializer.setFeature(
15156                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15157                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15158                    serializer.endDocument();
15159                    serializer.flush();
15160                } catch (IllegalArgumentException e) {
15161                    pw.println("Failed writing: " + e);
15162                } catch (IllegalStateException e) {
15163                    pw.println("Failed writing: " + e);
15164                } catch (IOException e) {
15165                    pw.println("Failed writing: " + e);
15166                }
15167            }
15168
15169            if (!checkin
15170                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15171                    && packageName == null) {
15172                pw.println();
15173                int count = mSettings.mPackages.size();
15174                if (count == 0) {
15175                    pw.println("No applications!");
15176                    pw.println();
15177                } else {
15178                    final String prefix = "  ";
15179                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15180                    if (allPackageSettings.size() == 0) {
15181                        pw.println("No domain preferred apps!");
15182                        pw.println();
15183                    } else {
15184                        pw.println("App verification status:");
15185                        pw.println();
15186                        count = 0;
15187                        for (PackageSetting ps : allPackageSettings) {
15188                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15189                            if (ivi == null || ivi.getPackageName() == null) continue;
15190                            pw.println(prefix + "Package: " + ivi.getPackageName());
15191                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15192                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15193                            pw.println();
15194                            count++;
15195                        }
15196                        if (count == 0) {
15197                            pw.println(prefix + "No app verification established.");
15198                            pw.println();
15199                        }
15200                        for (int userId : sUserManager.getUserIds()) {
15201                            pw.println("App linkages for user " + userId + ":");
15202                            pw.println();
15203                            count = 0;
15204                            for (PackageSetting ps : allPackageSettings) {
15205                                final long status = ps.getDomainVerificationStatusForUser(userId);
15206                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15207                                    continue;
15208                                }
15209                                pw.println(prefix + "Package: " + ps.name);
15210                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15211                                String statusStr = IntentFilterVerificationInfo.
15212                                        getStatusStringFromValue(status);
15213                                pw.println(prefix + "Status:  " + statusStr);
15214                                pw.println();
15215                                count++;
15216                            }
15217                            if (count == 0) {
15218                                pw.println(prefix + "No configured app linkages.");
15219                                pw.println();
15220                            }
15221                        }
15222                    }
15223                }
15224            }
15225
15226            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15227                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15228                if (packageName == null && permissionNames == null) {
15229                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15230                        if (iperm == 0) {
15231                            if (dumpState.onTitlePrinted())
15232                                pw.println();
15233                            pw.println("AppOp Permissions:");
15234                        }
15235                        pw.print("  AppOp Permission ");
15236                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15237                        pw.println(":");
15238                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15239                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15240                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15241                        }
15242                    }
15243                }
15244            }
15245
15246            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15247                boolean printedSomething = false;
15248                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15249                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15250                        continue;
15251                    }
15252                    if (!printedSomething) {
15253                        if (dumpState.onTitlePrinted())
15254                            pw.println();
15255                        pw.println("Registered ContentProviders:");
15256                        printedSomething = true;
15257                    }
15258                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15259                    pw.print("    "); pw.println(p.toString());
15260                }
15261                printedSomething = false;
15262                for (Map.Entry<String, PackageParser.Provider> entry :
15263                        mProvidersByAuthority.entrySet()) {
15264                    PackageParser.Provider p = entry.getValue();
15265                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15266                        continue;
15267                    }
15268                    if (!printedSomething) {
15269                        if (dumpState.onTitlePrinted())
15270                            pw.println();
15271                        pw.println("ContentProvider Authorities:");
15272                        printedSomething = true;
15273                    }
15274                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15275                    pw.print("    "); pw.println(p.toString());
15276                    if (p.info != null && p.info.applicationInfo != null) {
15277                        final String appInfo = p.info.applicationInfo.toString();
15278                        pw.print("      applicationInfo="); pw.println(appInfo);
15279                    }
15280                }
15281            }
15282
15283            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15284                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15285            }
15286
15287            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15288                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15289            }
15290
15291            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15292                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15293            }
15294
15295            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15296                // XXX should handle packageName != null by dumping only install data that
15297                // the given package is involved with.
15298                if (dumpState.onTitlePrinted()) pw.println();
15299                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15300            }
15301
15302            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15303                if (dumpState.onTitlePrinted()) pw.println();
15304                mSettings.dumpReadMessagesLPr(pw, dumpState);
15305
15306                pw.println();
15307                pw.println("Package warning messages:");
15308                BufferedReader in = null;
15309                String line = null;
15310                try {
15311                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15312                    while ((line = in.readLine()) != null) {
15313                        if (line.contains("ignored: updated version")) continue;
15314                        pw.println(line);
15315                    }
15316                } catch (IOException ignored) {
15317                } finally {
15318                    IoUtils.closeQuietly(in);
15319                }
15320            }
15321
15322            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15323                BufferedReader in = null;
15324                String line = null;
15325                try {
15326                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15327                    while ((line = in.readLine()) != null) {
15328                        if (line.contains("ignored: updated version")) continue;
15329                        pw.print("msg,");
15330                        pw.println(line);
15331                    }
15332                } catch (IOException ignored) {
15333                } finally {
15334                    IoUtils.closeQuietly(in);
15335                }
15336            }
15337        }
15338    }
15339
15340    private String dumpDomainString(String packageName) {
15341        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15342        List<IntentFilter> filters = getAllIntentFilters(packageName);
15343
15344        ArraySet<String> result = new ArraySet<>();
15345        if (iviList.size() > 0) {
15346            for (IntentFilterVerificationInfo ivi : iviList) {
15347                for (String host : ivi.getDomains()) {
15348                    result.add(host);
15349                }
15350            }
15351        }
15352        if (filters != null && filters.size() > 0) {
15353            for (IntentFilter filter : filters) {
15354                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15355                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15356                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15357                    result.addAll(filter.getHostsList());
15358                }
15359            }
15360        }
15361
15362        StringBuilder sb = new StringBuilder(result.size() * 16);
15363        for (String domain : result) {
15364            if (sb.length() > 0) sb.append(" ");
15365            sb.append(domain);
15366        }
15367        return sb.toString();
15368    }
15369
15370    // ------- apps on sdcard specific code -------
15371    static final boolean DEBUG_SD_INSTALL = false;
15372
15373    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15374
15375    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15376
15377    private boolean mMediaMounted = false;
15378
15379    static String getEncryptKey() {
15380        try {
15381            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15382                    SD_ENCRYPTION_KEYSTORE_NAME);
15383            if (sdEncKey == null) {
15384                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15385                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15386                if (sdEncKey == null) {
15387                    Slog.e(TAG, "Failed to create encryption keys");
15388                    return null;
15389                }
15390            }
15391            return sdEncKey;
15392        } catch (NoSuchAlgorithmException nsae) {
15393            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15394            return null;
15395        } catch (IOException ioe) {
15396            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15397            return null;
15398        }
15399    }
15400
15401    /*
15402     * Update media status on PackageManager.
15403     */
15404    @Override
15405    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15406        int callingUid = Binder.getCallingUid();
15407        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15408            throw new SecurityException("Media status can only be updated by the system");
15409        }
15410        // reader; this apparently protects mMediaMounted, but should probably
15411        // be a different lock in that case.
15412        synchronized (mPackages) {
15413            Log.i(TAG, "Updating external media status from "
15414                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15415                    + (mediaStatus ? "mounted" : "unmounted"));
15416            if (DEBUG_SD_INSTALL)
15417                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15418                        + ", mMediaMounted=" + mMediaMounted);
15419            if (mediaStatus == mMediaMounted) {
15420                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15421                        : 0, -1);
15422                mHandler.sendMessage(msg);
15423                return;
15424            }
15425            mMediaMounted = mediaStatus;
15426        }
15427        // Queue up an async operation since the package installation may take a
15428        // little while.
15429        mHandler.post(new Runnable() {
15430            public void run() {
15431                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15432            }
15433        });
15434    }
15435
15436    /**
15437     * Called by MountService when the initial ASECs to scan are available.
15438     * Should block until all the ASEC containers are finished being scanned.
15439     */
15440    public void scanAvailableAsecs() {
15441        updateExternalMediaStatusInner(true, false, false);
15442        if (mShouldRestoreconData) {
15443            SELinuxMMAC.setRestoreconDone();
15444            mShouldRestoreconData = false;
15445        }
15446    }
15447
15448    /*
15449     * Collect information of applications on external media, map them against
15450     * existing containers and update information based on current mount status.
15451     * Please note that we always have to report status if reportStatus has been
15452     * set to true especially when unloading packages.
15453     */
15454    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15455            boolean externalStorage) {
15456        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15457        int[] uidArr = EmptyArray.INT;
15458
15459        final String[] list = PackageHelper.getSecureContainerList();
15460        if (ArrayUtils.isEmpty(list)) {
15461            Log.i(TAG, "No secure containers found");
15462        } else {
15463            // Process list of secure containers and categorize them
15464            // as active or stale based on their package internal state.
15465
15466            // reader
15467            synchronized (mPackages) {
15468                for (String cid : list) {
15469                    // Leave stages untouched for now; installer service owns them
15470                    if (PackageInstallerService.isStageName(cid)) continue;
15471
15472                    if (DEBUG_SD_INSTALL)
15473                        Log.i(TAG, "Processing container " + cid);
15474                    String pkgName = getAsecPackageName(cid);
15475                    if (pkgName == null) {
15476                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15477                        continue;
15478                    }
15479                    if (DEBUG_SD_INSTALL)
15480                        Log.i(TAG, "Looking for pkg : " + pkgName);
15481
15482                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15483                    if (ps == null) {
15484                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15485                        continue;
15486                    }
15487
15488                    /*
15489                     * Skip packages that are not external if we're unmounting
15490                     * external storage.
15491                     */
15492                    if (externalStorage && !isMounted && !isExternal(ps)) {
15493                        continue;
15494                    }
15495
15496                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15497                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15498                    // The package status is changed only if the code path
15499                    // matches between settings and the container id.
15500                    if (ps.codePathString != null
15501                            && ps.codePathString.startsWith(args.getCodePath())) {
15502                        if (DEBUG_SD_INSTALL) {
15503                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15504                                    + " at code path: " + ps.codePathString);
15505                        }
15506
15507                        // We do have a valid package installed on sdcard
15508                        processCids.put(args, ps.codePathString);
15509                        final int uid = ps.appId;
15510                        if (uid != -1) {
15511                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15512                        }
15513                    } else {
15514                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15515                                + ps.codePathString);
15516                    }
15517                }
15518            }
15519
15520            Arrays.sort(uidArr);
15521        }
15522
15523        // Process packages with valid entries.
15524        if (isMounted) {
15525            if (DEBUG_SD_INSTALL)
15526                Log.i(TAG, "Loading packages");
15527            loadMediaPackages(processCids, uidArr, externalStorage);
15528            startCleaningPackages();
15529            mInstallerService.onSecureContainersAvailable();
15530        } else {
15531            if (DEBUG_SD_INSTALL)
15532                Log.i(TAG, "Unloading packages");
15533            unloadMediaPackages(processCids, uidArr, reportStatus);
15534        }
15535    }
15536
15537    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15538            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15539        final int size = infos.size();
15540        final String[] packageNames = new String[size];
15541        final int[] packageUids = new int[size];
15542        for (int i = 0; i < size; i++) {
15543            final ApplicationInfo info = infos.get(i);
15544            packageNames[i] = info.packageName;
15545            packageUids[i] = info.uid;
15546        }
15547        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15548                finishedReceiver);
15549    }
15550
15551    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15552            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15553        sendResourcesChangedBroadcast(mediaStatus, replacing,
15554                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15555    }
15556
15557    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15558            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15559        int size = pkgList.length;
15560        if (size > 0) {
15561            // Send broadcasts here
15562            Bundle extras = new Bundle();
15563            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15564            if (uidArr != null) {
15565                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15566            }
15567            if (replacing) {
15568                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15569            }
15570            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15571                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15572            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15573        }
15574    }
15575
15576   /*
15577     * Look at potentially valid container ids from processCids If package
15578     * information doesn't match the one on record or package scanning fails,
15579     * the cid is added to list of removeCids. We currently don't delete stale
15580     * containers.
15581     */
15582    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
15583            boolean externalStorage) {
15584        ArrayList<String> pkgList = new ArrayList<String>();
15585        Set<AsecInstallArgs> keys = processCids.keySet();
15586
15587        for (AsecInstallArgs args : keys) {
15588            String codePath = processCids.get(args);
15589            if (DEBUG_SD_INSTALL)
15590                Log.i(TAG, "Loading container : " + args.cid);
15591            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15592            try {
15593                // Make sure there are no container errors first.
15594                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15595                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15596                            + " when installing from sdcard");
15597                    continue;
15598                }
15599                // Check code path here.
15600                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15601                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15602                            + " does not match one in settings " + codePath);
15603                    continue;
15604                }
15605                // Parse package
15606                int parseFlags = mDefParseFlags;
15607                if (args.isExternalAsec()) {
15608                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15609                }
15610                if (args.isFwdLocked()) {
15611                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15612                }
15613
15614                synchronized (mInstallLock) {
15615                    PackageParser.Package pkg = null;
15616                    try {
15617                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15618                    } catch (PackageManagerException e) {
15619                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15620                    }
15621                    // Scan the package
15622                    if (pkg != null) {
15623                        /*
15624                         * TODO why is the lock being held? doPostInstall is
15625                         * called in other places without the lock. This needs
15626                         * to be straightened out.
15627                         */
15628                        // writer
15629                        synchronized (mPackages) {
15630                            retCode = PackageManager.INSTALL_SUCCEEDED;
15631                            pkgList.add(pkg.packageName);
15632                            // Post process args
15633                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15634                                    pkg.applicationInfo.uid);
15635                        }
15636                    } else {
15637                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15638                    }
15639                }
15640
15641            } finally {
15642                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15643                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15644                }
15645            }
15646        }
15647        // writer
15648        synchronized (mPackages) {
15649            // If the platform SDK has changed since the last time we booted,
15650            // we need to re-grant app permission to catch any new ones that
15651            // appear. This is really a hack, and means that apps can in some
15652            // cases get permissions that the user didn't initially explicitly
15653            // allow... it would be nice to have some better way to handle
15654            // this situation.
15655            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
15656                    : mSettings.getInternalVersion();
15657            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
15658                    : StorageManager.UUID_PRIVATE_INTERNAL;
15659
15660            int updateFlags = UPDATE_PERMISSIONS_ALL;
15661            if (ver.sdkVersion != mSdkVersion) {
15662                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15663                        + mSdkVersion + "; regranting permissions for external");
15664                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15665            }
15666            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
15667
15668            // Yay, everything is now upgraded
15669            ver.forceCurrent();
15670
15671            // can downgrade to reader
15672            // Persist settings
15673            mSettings.writeLPr();
15674        }
15675        // Send a broadcast to let everyone know we are done processing
15676        if (pkgList.size() > 0) {
15677            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15678        }
15679    }
15680
15681   /*
15682     * Utility method to unload a list of specified containers
15683     */
15684    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15685        // Just unmount all valid containers.
15686        for (AsecInstallArgs arg : cidArgs) {
15687            synchronized (mInstallLock) {
15688                arg.doPostDeleteLI(false);
15689           }
15690       }
15691   }
15692
15693    /*
15694     * Unload packages mounted on external media. This involves deleting package
15695     * data from internal structures, sending broadcasts about diabled packages,
15696     * gc'ing to free up references, unmounting all secure containers
15697     * corresponding to packages on external media, and posting a
15698     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15699     * that we always have to post this message if status has been requested no
15700     * matter what.
15701     */
15702    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15703            final boolean reportStatus) {
15704        if (DEBUG_SD_INSTALL)
15705            Log.i(TAG, "unloading media packages");
15706        ArrayList<String> pkgList = new ArrayList<String>();
15707        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15708        final Set<AsecInstallArgs> keys = processCids.keySet();
15709        for (AsecInstallArgs args : keys) {
15710            String pkgName = args.getPackageName();
15711            if (DEBUG_SD_INSTALL)
15712                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15713            // Delete package internally
15714            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15715            synchronized (mInstallLock) {
15716                boolean res = deletePackageLI(pkgName, null, false, null, null,
15717                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15718                if (res) {
15719                    pkgList.add(pkgName);
15720                } else {
15721                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15722                    failedList.add(args);
15723                }
15724            }
15725        }
15726
15727        // reader
15728        synchronized (mPackages) {
15729            // We didn't update the settings after removing each package;
15730            // write them now for all packages.
15731            mSettings.writeLPr();
15732        }
15733
15734        // We have to absolutely send UPDATED_MEDIA_STATUS only
15735        // after confirming that all the receivers processed the ordered
15736        // broadcast when packages get disabled, force a gc to clean things up.
15737        // and unload all the containers.
15738        if (pkgList.size() > 0) {
15739            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15740                    new IIntentReceiver.Stub() {
15741                public void performReceive(Intent intent, int resultCode, String data,
15742                        Bundle extras, boolean ordered, boolean sticky,
15743                        int sendingUser) throws RemoteException {
15744                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15745                            reportStatus ? 1 : 0, 1, keys);
15746                    mHandler.sendMessage(msg);
15747                }
15748            });
15749        } else {
15750            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15751                    keys);
15752            mHandler.sendMessage(msg);
15753        }
15754    }
15755
15756    private void loadPrivatePackages(final VolumeInfo vol) {
15757        mHandler.post(new Runnable() {
15758            @Override
15759            public void run() {
15760                loadPrivatePackagesInner(vol);
15761            }
15762        });
15763    }
15764
15765    private void loadPrivatePackagesInner(VolumeInfo vol) {
15766        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15767        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15768
15769        final VersionInfo ver;
15770        final List<PackageSetting> packages;
15771        synchronized (mPackages) {
15772            ver = mSettings.findOrCreateVersion(vol.fsUuid);
15773            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15774        }
15775
15776        for (PackageSetting ps : packages) {
15777            synchronized (mInstallLock) {
15778                final PackageParser.Package pkg;
15779                try {
15780                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15781                    loaded.add(pkg.applicationInfo);
15782                } catch (PackageManagerException e) {
15783                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15784                }
15785
15786                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15787                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15788                }
15789            }
15790        }
15791
15792        synchronized (mPackages) {
15793            int updateFlags = UPDATE_PERMISSIONS_ALL;
15794            if (ver.sdkVersion != mSdkVersion) {
15795                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15796                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15797                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15798            }
15799            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
15800
15801            // Yay, everything is now upgraded
15802            ver.forceCurrent();
15803
15804            mSettings.writeLPr();
15805        }
15806
15807        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15808        sendResourcesChangedBroadcast(true, false, loaded, null);
15809    }
15810
15811    private void unloadPrivatePackages(final VolumeInfo vol) {
15812        mHandler.post(new Runnable() {
15813            @Override
15814            public void run() {
15815                unloadPrivatePackagesInner(vol);
15816            }
15817        });
15818    }
15819
15820    private void unloadPrivatePackagesInner(VolumeInfo vol) {
15821        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15822        synchronized (mInstallLock) {
15823        synchronized (mPackages) {
15824            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15825            for (PackageSetting ps : packages) {
15826                if (ps.pkg == null) continue;
15827
15828                final ApplicationInfo info = ps.pkg.applicationInfo;
15829                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15830                if (deletePackageLI(ps.name, null, false, null, null,
15831                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15832                    unloaded.add(info);
15833                } else {
15834                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15835                }
15836            }
15837
15838            mSettings.writeLPr();
15839        }
15840        }
15841
15842        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15843        sendResourcesChangedBroadcast(false, false, unloaded, null);
15844    }
15845
15846    /**
15847     * Examine all users present on given mounted volume, and destroy data
15848     * belonging to users that are no longer valid, or whose user ID has been
15849     * recycled.
15850     */
15851    private void reconcileUsers(String volumeUuid) {
15852        final File[] files = FileUtils
15853                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15854        for (File file : files) {
15855            if (!file.isDirectory()) continue;
15856
15857            final int userId;
15858            final UserInfo info;
15859            try {
15860                userId = Integer.parseInt(file.getName());
15861                info = sUserManager.getUserInfo(userId);
15862            } catch (NumberFormatException e) {
15863                Slog.w(TAG, "Invalid user directory " + file);
15864                continue;
15865            }
15866
15867            boolean destroyUser = false;
15868            if (info == null) {
15869                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15870                        + " because no matching user was found");
15871                destroyUser = true;
15872            } else {
15873                try {
15874                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15875                } catch (IOException e) {
15876                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15877                            + " because we failed to enforce serial number: " + e);
15878                    destroyUser = true;
15879                }
15880            }
15881
15882            if (destroyUser) {
15883                synchronized (mInstallLock) {
15884                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15885                }
15886            }
15887        }
15888
15889        final UserManager um = mContext.getSystemService(UserManager.class);
15890        for (UserInfo user : um.getUsers()) {
15891            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15892            if (userDir.exists()) continue;
15893
15894            try {
15895                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15896                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15897            } catch (IOException e) {
15898                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15899            }
15900        }
15901    }
15902
15903    /**
15904     * Examine all apps present on given mounted volume, and destroy apps that
15905     * aren't expected, either due to uninstallation or reinstallation on
15906     * another volume.
15907     */
15908    private void reconcileApps(String volumeUuid) {
15909        final File[] files = FileUtils
15910                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15911        for (File file : files) {
15912            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15913                    && !PackageInstallerService.isStageName(file.getName());
15914            if (!isPackage) {
15915                // Ignore entries which are not packages
15916                continue;
15917            }
15918
15919            boolean destroyApp = false;
15920            String packageName = null;
15921            try {
15922                final PackageLite pkg = PackageParser.parsePackageLite(file,
15923                        PackageParser.PARSE_MUST_BE_APK);
15924                packageName = pkg.packageName;
15925
15926                synchronized (mPackages) {
15927                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15928                    if (ps == null) {
15929                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15930                                + volumeUuid + " because we found no install record");
15931                        destroyApp = true;
15932                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15933                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15934                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15935                        destroyApp = true;
15936                    }
15937                }
15938
15939            } catch (PackageParserException e) {
15940                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15941                destroyApp = true;
15942            }
15943
15944            if (destroyApp) {
15945                synchronized (mInstallLock) {
15946                    if (packageName != null) {
15947                        removeDataDirsLI(volumeUuid, packageName);
15948                    }
15949                    if (file.isDirectory()) {
15950                        mInstaller.rmPackageDir(file.getAbsolutePath());
15951                    } else {
15952                        file.delete();
15953                    }
15954                }
15955            }
15956        }
15957    }
15958
15959    private void unfreezePackage(String packageName) {
15960        synchronized (mPackages) {
15961            final PackageSetting ps = mSettings.mPackages.get(packageName);
15962            if (ps != null) {
15963                ps.frozen = false;
15964            }
15965        }
15966    }
15967
15968    @Override
15969    public int movePackage(final String packageName, final String volumeUuid) {
15970        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15971
15972        final int moveId = mNextMoveId.getAndIncrement();
15973        try {
15974            movePackageInternal(packageName, volumeUuid, moveId);
15975        } catch (PackageManagerException e) {
15976            Slog.w(TAG, "Failed to move " + packageName, e);
15977            mMoveCallbacks.notifyStatusChanged(moveId,
15978                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15979        }
15980        return moveId;
15981    }
15982
15983    private void movePackageInternal(final String packageName, final String volumeUuid,
15984            final int moveId) throws PackageManagerException {
15985        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15986        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15987        final PackageManager pm = mContext.getPackageManager();
15988
15989        final boolean currentAsec;
15990        final String currentVolumeUuid;
15991        final File codeFile;
15992        final String installerPackageName;
15993        final String packageAbiOverride;
15994        final int appId;
15995        final String seinfo;
15996        final String label;
15997
15998        // reader
15999        synchronized (mPackages) {
16000            final PackageParser.Package pkg = mPackages.get(packageName);
16001            final PackageSetting ps = mSettings.mPackages.get(packageName);
16002            if (pkg == null || ps == null) {
16003                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16004            }
16005
16006            if (pkg.applicationInfo.isSystemApp()) {
16007                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16008                        "Cannot move system application");
16009            }
16010
16011            if (pkg.applicationInfo.isExternalAsec()) {
16012                currentAsec = true;
16013                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16014            } else if (pkg.applicationInfo.isForwardLocked()) {
16015                currentAsec = true;
16016                currentVolumeUuid = "forward_locked";
16017            } else {
16018                currentAsec = false;
16019                currentVolumeUuid = ps.volumeUuid;
16020
16021                final File probe = new File(pkg.codePath);
16022                final File probeOat = new File(probe, "oat");
16023                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16024                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16025                            "Move only supported for modern cluster style installs");
16026                }
16027            }
16028
16029            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16030                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16031                        "Package already moved to " + volumeUuid);
16032            }
16033
16034            if (ps.frozen) {
16035                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16036                        "Failed to move already frozen package");
16037            }
16038            ps.frozen = true;
16039
16040            codeFile = new File(pkg.codePath);
16041            installerPackageName = ps.installerPackageName;
16042            packageAbiOverride = ps.cpuAbiOverrideString;
16043            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16044            seinfo = pkg.applicationInfo.seinfo;
16045            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16046        }
16047
16048        // Now that we're guarded by frozen state, kill app during move
16049        final long token = Binder.clearCallingIdentity();
16050        try {
16051            killApplication(packageName, appId, "move pkg");
16052        } finally {
16053            Binder.restoreCallingIdentity(token);
16054        }
16055
16056        final Bundle extras = new Bundle();
16057        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16058        extras.putString(Intent.EXTRA_TITLE, label);
16059        mMoveCallbacks.notifyCreated(moveId, extras);
16060
16061        int installFlags;
16062        final boolean moveCompleteApp;
16063        final File measurePath;
16064
16065        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16066            installFlags = INSTALL_INTERNAL;
16067            moveCompleteApp = !currentAsec;
16068            measurePath = Environment.getDataAppDirectory(volumeUuid);
16069        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16070            installFlags = INSTALL_EXTERNAL;
16071            moveCompleteApp = false;
16072            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16073        } else {
16074            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16075            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16076                    || !volume.isMountedWritable()) {
16077                unfreezePackage(packageName);
16078                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16079                        "Move location not mounted private volume");
16080            }
16081
16082            Preconditions.checkState(!currentAsec);
16083
16084            installFlags = INSTALL_INTERNAL;
16085            moveCompleteApp = true;
16086            measurePath = Environment.getDataAppDirectory(volumeUuid);
16087        }
16088
16089        final PackageStats stats = new PackageStats(null, -1);
16090        synchronized (mInstaller) {
16091            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16092                unfreezePackage(packageName);
16093                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16094                        "Failed to measure package size");
16095            }
16096        }
16097
16098        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16099                + stats.dataSize);
16100
16101        final long startFreeBytes = measurePath.getFreeSpace();
16102        final long sizeBytes;
16103        if (moveCompleteApp) {
16104            sizeBytes = stats.codeSize + stats.dataSize;
16105        } else {
16106            sizeBytes = stats.codeSize;
16107        }
16108
16109        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16110            unfreezePackage(packageName);
16111            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16112                    "Not enough free space to move");
16113        }
16114
16115        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16116
16117        final CountDownLatch installedLatch = new CountDownLatch(1);
16118        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16119            @Override
16120            public void onUserActionRequired(Intent intent) throws RemoteException {
16121                throw new IllegalStateException();
16122            }
16123
16124            @Override
16125            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16126                    Bundle extras) throws RemoteException {
16127                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16128                        + PackageManager.installStatusToString(returnCode, msg));
16129
16130                installedLatch.countDown();
16131
16132                // Regardless of success or failure of the move operation,
16133                // always unfreeze the package
16134                unfreezePackage(packageName);
16135
16136                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16137                switch (status) {
16138                    case PackageInstaller.STATUS_SUCCESS:
16139                        mMoveCallbacks.notifyStatusChanged(moveId,
16140                                PackageManager.MOVE_SUCCEEDED);
16141                        break;
16142                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16143                        mMoveCallbacks.notifyStatusChanged(moveId,
16144                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16145                        break;
16146                    default:
16147                        mMoveCallbacks.notifyStatusChanged(moveId,
16148                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16149                        break;
16150                }
16151            }
16152        };
16153
16154        final MoveInfo move;
16155        if (moveCompleteApp) {
16156            // Kick off a thread to report progress estimates
16157            new Thread() {
16158                @Override
16159                public void run() {
16160                    while (true) {
16161                        try {
16162                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16163                                break;
16164                            }
16165                        } catch (InterruptedException ignored) {
16166                        }
16167
16168                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16169                        final int progress = 10 + (int) MathUtils.constrain(
16170                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16171                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16172                    }
16173                }
16174            }.start();
16175
16176            final String dataAppName = codeFile.getName();
16177            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16178                    dataAppName, appId, seinfo);
16179        } else {
16180            move = null;
16181        }
16182
16183        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16184
16185        final Message msg = mHandler.obtainMessage(INIT_COPY);
16186        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16187        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
16188                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16189        mHandler.sendMessage(msg);
16190    }
16191
16192    @Override
16193    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16194        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16195
16196        final int realMoveId = mNextMoveId.getAndIncrement();
16197        final Bundle extras = new Bundle();
16198        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16199        mMoveCallbacks.notifyCreated(realMoveId, extras);
16200
16201        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16202            @Override
16203            public void onCreated(int moveId, Bundle extras) {
16204                // Ignored
16205            }
16206
16207            @Override
16208            public void onStatusChanged(int moveId, int status, long estMillis) {
16209                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16210            }
16211        };
16212
16213        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16214        storage.setPrimaryStorageUuid(volumeUuid, callback);
16215        return realMoveId;
16216    }
16217
16218    @Override
16219    public int getMoveStatus(int moveId) {
16220        mContext.enforceCallingOrSelfPermission(
16221                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16222        return mMoveCallbacks.mLastStatus.get(moveId);
16223    }
16224
16225    @Override
16226    public void registerMoveCallback(IPackageMoveObserver callback) {
16227        mContext.enforceCallingOrSelfPermission(
16228                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16229        mMoveCallbacks.register(callback);
16230    }
16231
16232    @Override
16233    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16234        mContext.enforceCallingOrSelfPermission(
16235                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16236        mMoveCallbacks.unregister(callback);
16237    }
16238
16239    @Override
16240    public boolean setInstallLocation(int loc) {
16241        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16242                null);
16243        if (getInstallLocation() == loc) {
16244            return true;
16245        }
16246        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16247                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16248            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16249                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16250            return true;
16251        }
16252        return false;
16253   }
16254
16255    @Override
16256    public int getInstallLocation() {
16257        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16258                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16259                PackageHelper.APP_INSTALL_AUTO);
16260    }
16261
16262    /** Called by UserManagerService */
16263    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16264        mDirtyUsers.remove(userHandle);
16265        mSettings.removeUserLPw(userHandle);
16266        mPendingBroadcasts.remove(userHandle);
16267        if (mInstaller != null) {
16268            // Technically, we shouldn't be doing this with the package lock
16269            // held.  However, this is very rare, and there is already so much
16270            // other disk I/O going on, that we'll let it slide for now.
16271            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16272            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16273                final String volumeUuid = vol.getFsUuid();
16274                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16275                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16276            }
16277        }
16278        mUserNeedsBadging.delete(userHandle);
16279        removeUnusedPackagesLILPw(userManager, userHandle);
16280    }
16281
16282    /**
16283     * We're removing userHandle and would like to remove any downloaded packages
16284     * that are no longer in use by any other user.
16285     * @param userHandle the user being removed
16286     */
16287    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16288        final boolean DEBUG_CLEAN_APKS = false;
16289        int [] users = userManager.getUserIdsLPr();
16290        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16291        while (psit.hasNext()) {
16292            PackageSetting ps = psit.next();
16293            if (ps.pkg == null) {
16294                continue;
16295            }
16296            final String packageName = ps.pkg.packageName;
16297            // Skip over if system app
16298            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16299                continue;
16300            }
16301            if (DEBUG_CLEAN_APKS) {
16302                Slog.i(TAG, "Checking package " + packageName);
16303            }
16304            boolean keep = false;
16305            for (int i = 0; i < users.length; i++) {
16306                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16307                    keep = true;
16308                    if (DEBUG_CLEAN_APKS) {
16309                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16310                                + users[i]);
16311                    }
16312                    break;
16313                }
16314            }
16315            if (!keep) {
16316                if (DEBUG_CLEAN_APKS) {
16317                    Slog.i(TAG, "  Removing package " + packageName);
16318                }
16319                mHandler.post(new Runnable() {
16320                    public void run() {
16321                        deletePackageX(packageName, userHandle, 0);
16322                    } //end run
16323                });
16324            }
16325        }
16326    }
16327
16328    /** Called by UserManagerService */
16329    void createNewUserLILPw(int userHandle) {
16330        if (mInstaller != null) {
16331            mInstaller.createUserConfig(userHandle);
16332            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16333            applyFactoryDefaultBrowserLPw(userHandle);
16334            primeDomainVerificationsLPw(userHandle);
16335        }
16336    }
16337
16338    void newUserCreated(final int userHandle) {
16339        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16340    }
16341
16342    @Override
16343    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16344        mContext.enforceCallingOrSelfPermission(
16345                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16346                "Only package verification agents can read the verifier device identity");
16347
16348        synchronized (mPackages) {
16349            return mSettings.getVerifierDeviceIdentityLPw();
16350        }
16351    }
16352
16353    @Override
16354    public void setPermissionEnforced(String permission, boolean enforced) {
16355        // TODO: Now that we no longer change GID for storage, this should to away.
16356        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16357                "setPermissionEnforced");
16358        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16359            synchronized (mPackages) {
16360                if (mSettings.mReadExternalStorageEnforced == null
16361                        || mSettings.mReadExternalStorageEnforced != enforced) {
16362                    mSettings.mReadExternalStorageEnforced = enforced;
16363                    mSettings.writeLPr();
16364                }
16365            }
16366            // kill any non-foreground processes so we restart them and
16367            // grant/revoke the GID.
16368            final IActivityManager am = ActivityManagerNative.getDefault();
16369            if (am != null) {
16370                final long token = Binder.clearCallingIdentity();
16371                try {
16372                    am.killProcessesBelowForeground("setPermissionEnforcement");
16373                } catch (RemoteException e) {
16374                } finally {
16375                    Binder.restoreCallingIdentity(token);
16376                }
16377            }
16378        } else {
16379            throw new IllegalArgumentException("No selective enforcement for " + permission);
16380        }
16381    }
16382
16383    @Override
16384    @Deprecated
16385    public boolean isPermissionEnforced(String permission) {
16386        return true;
16387    }
16388
16389    @Override
16390    public boolean isStorageLow() {
16391        final long token = Binder.clearCallingIdentity();
16392        try {
16393            final DeviceStorageMonitorInternal
16394                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16395            if (dsm != null) {
16396                return dsm.isMemoryLow();
16397            } else {
16398                return false;
16399            }
16400        } finally {
16401            Binder.restoreCallingIdentity(token);
16402        }
16403    }
16404
16405    @Override
16406    public IPackageInstaller getPackageInstaller() {
16407        return mInstallerService;
16408    }
16409
16410    private boolean userNeedsBadging(int userId) {
16411        int index = mUserNeedsBadging.indexOfKey(userId);
16412        if (index < 0) {
16413            final UserInfo userInfo;
16414            final long token = Binder.clearCallingIdentity();
16415            try {
16416                userInfo = sUserManager.getUserInfo(userId);
16417            } finally {
16418                Binder.restoreCallingIdentity(token);
16419            }
16420            final boolean b;
16421            if (userInfo != null && userInfo.isManagedProfile()) {
16422                b = true;
16423            } else {
16424                b = false;
16425            }
16426            mUserNeedsBadging.put(userId, b);
16427            return b;
16428        }
16429        return mUserNeedsBadging.valueAt(index);
16430    }
16431
16432    @Override
16433    public KeySet getKeySetByAlias(String packageName, String alias) {
16434        if (packageName == null || alias == null) {
16435            return null;
16436        }
16437        synchronized(mPackages) {
16438            final PackageParser.Package pkg = mPackages.get(packageName);
16439            if (pkg == null) {
16440                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16441                throw new IllegalArgumentException("Unknown package: " + packageName);
16442            }
16443            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16444            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16445        }
16446    }
16447
16448    @Override
16449    public KeySet getSigningKeySet(String packageName) {
16450        if (packageName == null) {
16451            return null;
16452        }
16453        synchronized(mPackages) {
16454            final PackageParser.Package pkg = mPackages.get(packageName);
16455            if (pkg == null) {
16456                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16457                throw new IllegalArgumentException("Unknown package: " + packageName);
16458            }
16459            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16460                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16461                throw new SecurityException("May not access signing KeySet of other apps.");
16462            }
16463            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16464            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16465        }
16466    }
16467
16468    @Override
16469    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16470        if (packageName == null || ks == null) {
16471            return false;
16472        }
16473        synchronized(mPackages) {
16474            final PackageParser.Package pkg = mPackages.get(packageName);
16475            if (pkg == null) {
16476                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16477                throw new IllegalArgumentException("Unknown package: " + packageName);
16478            }
16479            IBinder ksh = ks.getToken();
16480            if (ksh instanceof KeySetHandle) {
16481                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16482                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16483            }
16484            return false;
16485        }
16486    }
16487
16488    @Override
16489    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16490        if (packageName == null || ks == null) {
16491            return false;
16492        }
16493        synchronized(mPackages) {
16494            final PackageParser.Package pkg = mPackages.get(packageName);
16495            if (pkg == null) {
16496                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16497                throw new IllegalArgumentException("Unknown package: " + packageName);
16498            }
16499            IBinder ksh = ks.getToken();
16500            if (ksh instanceof KeySetHandle) {
16501                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16502                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16503            }
16504            return false;
16505        }
16506    }
16507
16508    public void getUsageStatsIfNoPackageUsageInfo() {
16509        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16510            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16511            if (usm == null) {
16512                throw new IllegalStateException("UsageStatsManager must be initialized");
16513            }
16514            long now = System.currentTimeMillis();
16515            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16516            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16517                String packageName = entry.getKey();
16518                PackageParser.Package pkg = mPackages.get(packageName);
16519                if (pkg == null) {
16520                    continue;
16521                }
16522                UsageStats usage = entry.getValue();
16523                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16524                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16525            }
16526        }
16527    }
16528
16529    /**
16530     * Check and throw if the given before/after packages would be considered a
16531     * downgrade.
16532     */
16533    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16534            throws PackageManagerException {
16535        if (after.versionCode < before.mVersionCode) {
16536            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16537                    "Update version code " + after.versionCode + " is older than current "
16538                    + before.mVersionCode);
16539        } else if (after.versionCode == before.mVersionCode) {
16540            if (after.baseRevisionCode < before.baseRevisionCode) {
16541                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16542                        "Update base revision code " + after.baseRevisionCode
16543                        + " is older than current " + before.baseRevisionCode);
16544            }
16545
16546            if (!ArrayUtils.isEmpty(after.splitNames)) {
16547                for (int i = 0; i < after.splitNames.length; i++) {
16548                    final String splitName = after.splitNames[i];
16549                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16550                    if (j != -1) {
16551                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16552                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16553                                    "Update split " + splitName + " revision code "
16554                                    + after.splitRevisionCodes[i] + " is older than current "
16555                                    + before.splitRevisionCodes[j]);
16556                        }
16557                    }
16558                }
16559            }
16560        }
16561    }
16562
16563    private static class MoveCallbacks extends Handler {
16564        private static final int MSG_CREATED = 1;
16565        private static final int MSG_STATUS_CHANGED = 2;
16566
16567        private final RemoteCallbackList<IPackageMoveObserver>
16568                mCallbacks = new RemoteCallbackList<>();
16569
16570        private final SparseIntArray mLastStatus = new SparseIntArray();
16571
16572        public MoveCallbacks(Looper looper) {
16573            super(looper);
16574        }
16575
16576        public void register(IPackageMoveObserver callback) {
16577            mCallbacks.register(callback);
16578        }
16579
16580        public void unregister(IPackageMoveObserver callback) {
16581            mCallbacks.unregister(callback);
16582        }
16583
16584        @Override
16585        public void handleMessage(Message msg) {
16586            final SomeArgs args = (SomeArgs) msg.obj;
16587            final int n = mCallbacks.beginBroadcast();
16588            for (int i = 0; i < n; i++) {
16589                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16590                try {
16591                    invokeCallback(callback, msg.what, args);
16592                } catch (RemoteException ignored) {
16593                }
16594            }
16595            mCallbacks.finishBroadcast();
16596            args.recycle();
16597        }
16598
16599        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16600                throws RemoteException {
16601            switch (what) {
16602                case MSG_CREATED: {
16603                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16604                    break;
16605                }
16606                case MSG_STATUS_CHANGED: {
16607                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16608                    break;
16609                }
16610            }
16611        }
16612
16613        private void notifyCreated(int moveId, Bundle extras) {
16614            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16615
16616            final SomeArgs args = SomeArgs.obtain();
16617            args.argi1 = moveId;
16618            args.arg2 = extras;
16619            obtainMessage(MSG_CREATED, args).sendToTarget();
16620        }
16621
16622        private void notifyStatusChanged(int moveId, int status) {
16623            notifyStatusChanged(moveId, status, -1);
16624        }
16625
16626        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16627            Slog.v(TAG, "Move " + moveId + " status " + status);
16628
16629            final SomeArgs args = SomeArgs.obtain();
16630            args.argi1 = moveId;
16631            args.argi2 = status;
16632            args.arg3 = estMillis;
16633            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16634
16635            synchronized (mLastStatus) {
16636                mLastStatus.put(moveId, status);
16637            }
16638        }
16639    }
16640
16641    private final class OnPermissionChangeListeners extends Handler {
16642        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16643
16644        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16645                new RemoteCallbackList<>();
16646
16647        public OnPermissionChangeListeners(Looper looper) {
16648            super(looper);
16649        }
16650
16651        @Override
16652        public void handleMessage(Message msg) {
16653            switch (msg.what) {
16654                case MSG_ON_PERMISSIONS_CHANGED: {
16655                    final int uid = msg.arg1;
16656                    handleOnPermissionsChanged(uid);
16657                } break;
16658            }
16659        }
16660
16661        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16662            mPermissionListeners.register(listener);
16663
16664        }
16665
16666        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16667            mPermissionListeners.unregister(listener);
16668        }
16669
16670        public void onPermissionsChanged(int uid) {
16671            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16672                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16673            }
16674        }
16675
16676        private void handleOnPermissionsChanged(int uid) {
16677            final int count = mPermissionListeners.beginBroadcast();
16678            try {
16679                for (int i = 0; i < count; i++) {
16680                    IOnPermissionsChangeListener callback = mPermissionListeners
16681                            .getBroadcastItem(i);
16682                    try {
16683                        callback.onPermissionsChanged(uid);
16684                    } catch (RemoteException e) {
16685                        Log.e(TAG, "Permission listener is dead", e);
16686                    }
16687                }
16688            } finally {
16689                mPermissionListeners.finishBroadcast();
16690            }
16691        }
16692    }
16693
16694    private class PackageManagerInternalImpl extends PackageManagerInternal {
16695        @Override
16696        public void setLocationPackagesProvider(PackagesProvider provider) {
16697            synchronized (mPackages) {
16698                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16699            }
16700        }
16701
16702        @Override
16703        public void setImePackagesProvider(PackagesProvider provider) {
16704            synchronized (mPackages) {
16705                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16706            }
16707        }
16708
16709        @Override
16710        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16711            synchronized (mPackages) {
16712                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16713            }
16714        }
16715
16716        @Override
16717        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16718            synchronized (mPackages) {
16719                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16720            }
16721        }
16722
16723        @Override
16724        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16725            synchronized (mPackages) {
16726                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16727            }
16728        }
16729
16730        @Override
16731        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16732            synchronized (mPackages) {
16733                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16734            }
16735        }
16736
16737        @Override
16738        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16739            synchronized (mPackages) {
16740                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16741            }
16742        }
16743
16744        @Override
16745        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16746            synchronized (mPackages) {
16747                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16748                        packageName, userId);
16749            }
16750        }
16751
16752        @Override
16753        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16754            synchronized (mPackages) {
16755                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16756                        packageName, userId);
16757            }
16758        }
16759        @Override
16760        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16761            synchronized (mPackages) {
16762                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16763                        packageName, userId);
16764            }
16765        }
16766    }
16767
16768    @Override
16769    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16770        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16771        synchronized (mPackages) {
16772            final long identity = Binder.clearCallingIdentity();
16773            try {
16774                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16775                        packageNames, userId);
16776            } finally {
16777                Binder.restoreCallingIdentity(identity);
16778            }
16779        }
16780    }
16781
16782    private static void enforceSystemOrPhoneCaller(String tag) {
16783        int callingUid = Binder.getCallingUid();
16784        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16785            throw new SecurityException(
16786                    "Cannot call " + tag + " from UID " + callingUid);
16787        }
16788    }
16789}
16790